From 7350d37e918d0e8be6e4a18bbf207475bc3142de Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 22 May 2013 19:42:31 +0200 Subject: [PATCH] Remove ember-data, add Ember model, update ember --- assets/scripts/vendor/ember-data.js | 8328 -------------------------- assets/scripts/vendor/ember-model.js | 1259 ++++ assets/scripts/vendor/ember.js | 5916 +++++++++++++----- assets/scripts/vendor/handlebars.js | 2735 +++++---- 4 files changed, 6930 insertions(+), 11308 deletions(-) delete mode 100644 assets/scripts/vendor/ember-data.js create mode 100644 assets/scripts/vendor/ember-model.js diff --git a/assets/scripts/vendor/ember-data.js b/assets/scripts/vendor/ember-data.js deleted file mode 100644 index 4b83ba82..00000000 --- a/assets/scripts/vendor/ember-data.js +++ /dev/null @@ -1,8328 +0,0 @@ -// Last commit: 0c516e4 (2013-03-08 15:59:48 +0100) - - -(function() { -window.DS = Ember.Namespace.create({ - // this one goes past 11 - CURRENT_API_REVISION: 12 -}); - -})(); - - - -(function() { -var DeferredMixin = Ember.DeferredMixin, // ember-runtime/mixins/deferred - Evented = Ember.Evented, // ember-runtime/mixins/evented - run = Ember.run, // ember-metal/run-loop - get = Ember.get; // ember-metal/accessors - -var LoadPromise = Ember.Mixin.create(Evented, DeferredMixin, { - init: function() { - this._super.apply(this, arguments); - this.one('didLoad', function() { - run(this, 'resolve', this); - }); - - if (get(this, 'isLoaded')) { - this.trigger('didLoad'); - } - } -}); - -DS.LoadPromise = LoadPromise; - -})(); - - - -(function() { -var get = Ember.get, set = Ember.set; - -var LoadPromise = DS.LoadPromise; // system/mixins/load_promise - -/** - A record array is an array that contains records of a certain type. The record - array materializes records as needed when they are retrieved for the first - time. You should not create record arrays yourself. Instead, an instance of - DS.RecordArray or its subclasses will be returned by your application's store - in response to queries. -*/ - -DS.RecordArray = Ember.ArrayProxy.extend(Ember.Evented, LoadPromise, { - /** - The model type contained by this record array. - - @type DS.Model - */ - type: null, - - // The array of client ids backing the record array. When a - // record is requested from the record array, the record - // for the client id at the same index is materialized, if - // necessary, by the store. - content: null, - - isLoaded: false, - isUpdating: false, - - // The store that created this record array. - store: null, - - objectAtContent: function(index) { - var content = get(this, 'content'), - reference = content.objectAt(index), - store = get(this, 'store'); - - if (reference) { - return store.recordForReference(reference); - } - }, - - materializedObjectAt: function(index) { - var reference = get(this, 'content').objectAt(index); - if (!reference) { return; } - - if (get(this, 'store').recordIsMaterialized(reference)) { - return this.objectAt(index); - } - }, - - update: function() { - if (get(this, 'isUpdating')) { return; } - - var store = get(this, 'store'), - type = get(this, 'type'); - - store.fetchAll(type, this); - }, - - addReference: function(reference) { - get(this, 'content').addObject(reference); - }, - - removeReference: function(reference) { - get(this, 'content').removeObject(reference); - } -}); - -})(); - - - -(function() { -var get = Ember.get; - -DS.FilteredRecordArray = DS.RecordArray.extend({ - filterFunction: null, - isLoaded: true, - - replace: function() { - var type = get(this, 'type').toString(); - throw new Error("The result of a client-side filter (on " + type + ") is immutable."); - }, - - updateFilter: Ember.observer(function() { - var store = get(this, 'store'); - store.updateRecordArrayFilter(this, get(this, 'type'), get(this, 'filterFunction')); - }, 'filterFunction') -}); - -})(); - - - -(function() { -var get = Ember.get, set = Ember.set; - -DS.AdapterPopulatedRecordArray = DS.RecordArray.extend({ - query: null, - - replace: function() { - var type = get(this, 'type').toString(); - throw new Error("The result of a server query (on " + type + ") is immutable."); - }, - - load: function(references) { - var store = get(this, 'store'), type = get(this, 'type'); - - this.beginPropertyChanges(); - set(this, 'content', Ember.A(references)); - set(this, 'isLoaded', true); - this.endPropertyChanges(); - - var self = this; - // TODO: does triggering didLoad event should be the last action of the runLoop? - Ember.run.once(function() { - self.trigger('didLoad'); - }); - } -}); - -})(); - - - -(function() { -var get = Ember.get, set = Ember.set; - -/** - A ManyArray is a RecordArray that represents the contents of a has-many - relationship. - - The ManyArray is instantiated lazily the first time the relationship is - requested. - - ### Inverses - - Often, the relationships in Ember Data applications will have - an inverse. For example, imagine the following models are - defined: - - App.Post = DS.Model.extend({ - comments: DS.hasMany('App.Comment') - }); - - App.Comment = DS.Model.extend({ - post: DS.belongsTo('App.Post') - }); - - If you created a new instance of `App.Post` and added - a `App.Comment` record to its `comments` has-many - relationship, you would expect the comment's `post` - property to be set to the post that contained - the has-many. - - We call the record to which a relationship belongs the - relationship's _owner_. -*/ -DS.ManyArray = DS.RecordArray.extend({ - init: function() { - this._super.apply(this, arguments); - this._changesToSync = Ember.OrderedSet.create(); - }, - - /** - @private - - The record to which this relationship belongs. - - @property {DS.Model} - */ - owner: null, - - // LOADING STATE - - isLoaded: false, - - loadingRecordsCount: function(count) { - this.loadingRecordsCount = count; - }, - - loadedRecord: function() { - this.loadingRecordsCount--; - if (this.loadingRecordsCount === 0) { - set(this, 'isLoaded', true); - this.trigger('didLoad'); - } - }, - - fetch: function() { - var references = get(this, 'content'), - store = get(this, 'store'), - type = get(this, 'type'), - owner = get(this, 'owner'); - - store.fetchUnloadedReferences(type, references, owner); - }, - - // Overrides Ember.Array's replace method to implement - replaceContent: function(index, removed, added) { - // Map the array of record objects into an array of client ids. - added = added.map(function(record) { - Ember.assert("You can only add records of " + (get(this, 'type') && get(this, 'type').toString()) + " to this relationship.", !get(this, 'type') || (get(this, 'type') === record.constructor)); - return get(record, '_reference'); - }, this); - - this._super(index, removed, added); - }, - - arrangedContentDidChange: function() { - this.fetch(); - }, - - arrayContentWillChange: function(index, removed, added) { - var owner = get(this, 'owner'), - name = get(this, 'name'); - - if (!owner._suspendedRelationships) { - // This code is the first half of code that continues inside - // of arrayContentDidChange. It gets or creates a change from - // the child object, adds the current owner as the old - // parent if this is the first time the object was removed - // from a ManyArray, and sets `newParent` to null. - // - // Later, if the object is added to another ManyArray, - // the `arrayContentDidChange` will set `newParent` on - // the change. - for (var i=index; i "created.uncommitted" - - The `DS.Model` states are themselves stateless. What we mean is that, - though each instance of a record also has a unique instance of a - `DS.StateManager`, the hierarchical states that each of *those* points - to is a shared data structure. For performance reasons, instead of each - record getting its own copy of the hierarchy of states, each state - manager points to this global, immutable shared instance. How does a - state know which record it should be acting on? We pass a reference to - the current state manager as the first parameter to every method invoked - on a state. - - The state manager passed as the first parameter is where you should stash - state about the record if needed; you should never store data on the state - object itself. If you need access to the record being acted on, you can - retrieve the state manager's `record` property. For example, if you had - an event handler `myEvent`: - - myEvent: function(manager) { - var record = manager.get('record'); - record.doSomething(); - } - - For more information about state managers in general, see the Ember.js - documentation on `Ember.StateManager`. - - ### Events, Flags, and Transitions - - A state may implement zero or more events, flags, or transitions. - - #### Events - - Events are named functions that are invoked when sent to a record. The - state manager will first look for a method with the given name on the - current state. If no method is found, it will search the current state's - parent, and then its grandparent, and so on until reaching the top of - the hierarchy. If the root is reached without an event handler being found, - an exception will be raised. This can be very helpful when debugging new - features. - - Here's an example implementation of a state with a `myEvent` event handler: - - aState: DS.State.create({ - myEvent: function(manager, param) { - console.log("Received myEvent with "+param); - } - }) - - To trigger this event: - - record.send('myEvent', 'foo'); - //=> "Received myEvent with foo" - - Note that an optional parameter can be sent to a record's `send()` method, - which will be passed as the second parameter to the event handler. - - Events should transition to a different state if appropriate. This can be - done by calling the state manager's `transitionTo()` method with a path to the - desired state. The state manager will attempt to resolve the state path - relative to the current state. If no state is found at that path, it will - attempt to resolve it relative to the current state's parent, and then its - parent, and so on until the root is reached. For example, imagine a hierarchy - like this: - - * created - * start <-- currentState - * inFlight - * updated - * inFlight - - If we are currently in the `start` state, calling - `transitionTo('inFlight')` would transition to the `created.inFlight` state, - while calling `transitionTo('updated.inFlight')` would transition to - the `updated.inFlight` state. - - Remember that *only events* should ever cause a state transition. You should - never call `transitionTo()` from outside a state's event handler. If you are - tempted to do so, create a new event and send that to the state manager. - - #### Flags - - Flags are Boolean values that can be used to introspect a record's current - state in a more user-friendly way than examining its state path. For example, - instead of doing this: - - var statePath = record.get('stateManager.currentPath'); - if (statePath === 'created.inFlight') { - doSomething(); - } - - You can say: - - if (record.get('isNew') && record.get('isSaving')) { - doSomething(); - } - - If your state does not set a value for a given flag, the value will - be inherited from its parent (or the first place in the state hierarchy - where it is defined). - - The current set of flags are defined below. If you want to add a new flag, - in addition to the area below, you will also need to declare it in the - `DS.Model` class. - - #### Transitions - - Transitions are like event handlers but are called automatically upon - entering or exiting a state. To implement a transition, just call a method - either `enter` or `exit`: - - myState: DS.State.create({ - // Gets called automatically when entering - // this state. - enter: function(manager) { - console.log("Entered myState"); - } - }) - - Note that enter and exit events are called once per transition. If the - current state changes, but changes to another child state of the parent, - the transition event on the parent will not be triggered. -*/ - -var stateProperty = Ember.computed(function(key) { - var parent = get(this, 'parentState'); - if (parent) { - return get(parent, key); - } -}).property(); - -var isEmptyObject = function(object) { - for (var name in object) { - if (object.hasOwnProperty(name)) { return false; } - } - - return true; -}; - -var hasDefinedProperties = function(object) { - for (var name in object) { - if (object.hasOwnProperty(name) && object[name]) { return true; } - } - - return false; -}; - -var didChangeData = function(manager) { - var record = get(manager, 'record'); - record.materializeData(); -}; - -var willSetProperty = function(manager, context) { - context.oldValue = get(get(manager, 'record'), context.name); - - var change = DS.AttributeChange.createChange(context); - get(manager, 'record')._changesToSync[context.attributeName] = change; -}; - -var didSetProperty = function(manager, context) { - var change = get(manager, 'record')._changesToSync[context.attributeName]; - change.value = get(get(manager, 'record'), context.name); - change.sync(); -}; - -// Whenever a property is set, recompute all dependent filters -var updateRecordArrays = function(manager) { - var record = manager.get('record'); - record.updateRecordArraysLater(); -}; - -DS.State = Ember.State.extend({ - isLoaded: stateProperty, - isReloading: stateProperty, - isDirty: stateProperty, - isSaving: stateProperty, - isDeleted: stateProperty, - isError: stateProperty, - isNew: stateProperty, - isValid: stateProperty, - - // For states that are substates of a - // DirtyState (updated or created), it is - // useful to be able to determine which - // type of dirty state it is. - dirtyType: stateProperty -}); - -// Implementation notes: -// -// Each state has a boolean value for all of the following flags: -// -// * isLoaded: The record has a populated `data` property. When a -// record is loaded via `store.find`, `isLoaded` is false -// until the adapter sets it. When a record is created locally, -// its `isLoaded` property is always true. -// * isDirty: The record has local changes that have not yet been -// saved by the adapter. This includes records that have been -// created (but not yet saved) or deleted. -// * isSaving: The record's transaction has been committed, but -// the adapter has not yet acknowledged that the changes have -// been persisted to the backend. -// * isDeleted: The record was marked for deletion. When `isDeleted` -// is true and `isDirty` is true, the record is deleted locally -// but the deletion was not yet persisted. When `isSaving` is -// true, the change is in-flight. When both `isDirty` and -// `isSaving` are false, the change has persisted. -// * isError: The adapter reported that it was unable to save -// local changes to the backend. This may also result in the -// record having its `isValid` property become false if the -// adapter reported that server-side validations failed. -// * isNew: The record was created on the client and the adapter -// did not yet report that it was successfully saved. -// * isValid: No client-side validations have failed and the -// adapter did not report any server-side validation failures. - -// The dirty state is a abstract state whose functionality is -// shared between the `created` and `updated` states. -// -// The deleted state shares the `isDirty` flag with the -// subclasses of `DirtyState`, but with a very different -// implementation. -// -// Dirty states have three child states: -// -// `uncommitted`: the store has not yet handed off the record -// to be saved. -// `inFlight`: the store has handed off the record to be saved, -// but the adapter has not yet acknowledged success. -// `invalid`: the record has invalid information and cannot be -// send to the adapter yet. -var DirtyState = DS.State.extend({ - initialState: 'uncommitted', - - // FLAGS - isDirty: true, - - // SUBSTATES - - // When a record first becomes dirty, it is `uncommitted`. - // This means that there are local pending changes, but they - // have not yet begun to be saved, and are not invalid. - uncommitted: DS.State.extend({ - // TRANSITIONS - enter: function(manager) { - var dirtyType = get(this, 'dirtyType'), - record = get(manager, 'record'); - - record.withTransaction(function (t) { - t.recordBecameDirty(dirtyType, record); - }); - }, - - // EVENTS - willSetProperty: willSetProperty, - didSetProperty: didSetProperty, - - becomeDirty: Ember.K, - - willCommit: function(manager) { - manager.transitionTo('inFlight'); - }, - - becameClean: function(manager) { - var record = get(manager, 'record'), - dirtyType = get(this, 'dirtyType'); - - record.withTransaction(function(t) { - t.recordBecameClean(dirtyType, record); - }); - - manager.transitionTo('loaded.materializing'); - }, - - becameInvalid: function(manager) { - var dirtyType = get(this, 'dirtyType'), - record = get(manager, 'record'); - - record.withTransaction(function (t) { - t.recordBecameInFlight(dirtyType, record); - }); - - manager.transitionTo('invalid'); - }, - - rollback: function(manager) { - get(manager, 'record').rollback(); - } - }), - - // Once a record has been handed off to the adapter to be - // saved, it is in the 'in flight' state. Changes to the - // record cannot be made during this window. - inFlight: DS.State.extend({ - // FLAGS - isSaving: true, - - // TRANSITIONS - enter: function(manager) { - var dirtyType = get(this, 'dirtyType'), - record = get(manager, 'record'); - - record.becameInFlight(); - - record.withTransaction(function (t) { - t.recordBecameInFlight(dirtyType, record); - }); - }, - - // EVENTS - didCommit: function(manager) { - var dirtyType = get(this, 'dirtyType'), - record = get(manager, 'record'); - - record.withTransaction(function(t) { - t.recordBecameClean('inflight', record); - }); - - manager.transitionTo('saved'); - manager.send('invokeLifecycleCallbacks', dirtyType); - }, - - becameInvalid: function(manager, errors) { - var record = get(manager, 'record'); - - set(record, 'errors', errors); - - manager.transitionTo('invalid'); - manager.send('invokeLifecycleCallbacks'); - }, - - becameError: function(manager) { - manager.transitionTo('error'); - manager.send('invokeLifecycleCallbacks'); - } - }), - - // A record is in the `invalid` state when its client-side - // invalidations have failed, or if the adapter has indicated - // the the record failed server-side invalidations. - invalid: DS.State.extend({ - // FLAGS - isValid: false, - - exit: function(manager) { - var record = get(manager, 'record'); - - record.withTransaction(function (t) { - t.recordBecameClean('inflight', record); - }); - }, - - // EVENTS - deleteRecord: function(manager) { - manager.transitionTo('deleted'); - get(manager, 'record').clearRelationships(); - }, - - willSetProperty: willSetProperty, - - didSetProperty: function(manager, context) { - var record = get(manager, 'record'), - errors = get(record, 'errors'), - key = context.name; - - set(errors, key, null); - - if (!hasDefinedProperties(errors)) { - manager.send('becameValid'); - } - - didSetProperty(manager, context); - }, - - becomeDirty: Ember.K, - - rollback: function(manager) { - manager.send('becameValid'); - manager.send('rollback'); - }, - - becameValid: function(manager) { - manager.transitionTo('uncommitted'); - }, - - invokeLifecycleCallbacks: function(manager) { - var record = get(manager, 'record'); - record.trigger('becameInvalid', record); - } - }) -}); - -// The created and updated states are created outside the state -// chart so we can reopen their substates and add mixins as -// necessary. - -var createdState = DirtyState.create({ - dirtyType: 'created', - - // FLAGS - isNew: true -}); - -var updatedState = DirtyState.create({ - dirtyType: 'updated' -}); - -createdState.states.uncommitted.reopen({ - deleteRecord: function(manager) { - var record = get(manager, 'record'); - - record.withTransaction(function(t) { - t.recordIsMoving('created', record); - }); - - record.clearRelationships(); - manager.transitionTo('deleted.saved'); - } -}); - -createdState.states.uncommitted.reopen({ - rollback: function(manager) { - this._super(manager); - manager.transitionTo('deleted.saved'); - } -}); - -updatedState.states.uncommitted.reopen({ - deleteRecord: function(manager) { - var record = get(manager, 'record'); - - record.withTransaction(function(t) { - t.recordIsMoving('updated', record); - }); - - manager.transitionTo('deleted'); - get(manager, 'record').clearRelationships(); - } -}); - -var states = { - rootState: Ember.State.create({ - // FLAGS - isLoaded: false, - isReloading: false, - isDirty: false, - isSaving: false, - isDeleted: false, - isError: false, - isNew: false, - isValid: true, - - // SUBSTATES - - // A record begins its lifecycle in the `empty` state. - // If its data will come from the adapter, it will - // transition into the `loading` state. Otherwise, if - // the record is being created on the client, it will - // transition into the `created` state. - empty: DS.State.create({ - // EVENTS - loadingData: function(manager) { - manager.transitionTo('loading'); - }, - - loadedData: function(manager) { - manager.transitionTo('loaded.created'); - } - }), - - // A record enters this state when the store askes - // the adapter for its data. It remains in this state - // until the adapter provides the requested data. - // - // Usually, this process is asynchronous, using an - // XHR to retrieve the data. - loading: DS.State.create({ - // EVENTS - loadedData: didChangeData, - - materializingData: function(manager) { - manager.transitionTo('loaded.materializing.firstTime'); - } - }), - - // A record enters this state when its data is populated. - // Most of a record's lifecycle is spent inside substates - // of the `loaded` state. - loaded: DS.State.create({ - initialState: 'saved', - - // FLAGS - isLoaded: true, - - // SUBSTATES - - materializing: DS.State.create({ - // FLAGS - isLoaded: false, - - // EVENTS - willSetProperty: Ember.K, - didSetProperty: Ember.K, - - didChangeData: didChangeData, - - finishedMaterializing: function(manager) { - manager.transitionTo('loaded.saved'); - }, - - // SUBSTATES - firstTime: DS.State.create({ - exit: function(manager) { - var record = get(manager, 'record'); - - Ember.run.once(function() { - record.trigger('didLoad'); - }); - } - }) - }), - - reloading: DS.State.create({ - // FLAGS - isReloading: true, - - // TRANSITIONS - enter: function(manager) { - var record = get(manager, 'record'), - store = get(record, 'store'); - - store.reloadRecord(record); - }, - - exit: function(manager) { - var record = get(manager, 'record'); - - once(record, 'trigger', 'didReload'); - }, - - // EVENTS - loadedData: didChangeData, - - materializingData: function(manager) { - manager.transitionTo('loaded.materializing'); - } - }), - - // If there are no local changes to a record, it remains - // in the `saved` state. - saved: DS.State.create({ - // EVENTS - willSetProperty: willSetProperty, - didSetProperty: didSetProperty, - - didChangeData: didChangeData, - loadedData: didChangeData, - - reloadRecord: function(manager) { - manager.transitionTo('loaded.reloading'); - }, - - materializingData: function(manager) { - manager.transitionTo('loaded.materializing'); - }, - - becomeDirty: function(manager) { - manager.transitionTo('updated'); - }, - - deleteRecord: function(manager) { - manager.transitionTo('deleted'); - get(manager, 'record').clearRelationships(); - }, - - unloadRecord: function(manager) { - manager.transitionTo('deleted.saved'); - get(manager, 'record').clearRelationships(); - }, - - invokeLifecycleCallbacks: function(manager, dirtyType) { - var record = get(manager, 'record'); - if (dirtyType === 'created') { - record.trigger('didCreate', record); - } else { - record.trigger('didUpdate', record); - } - } - }), - - // A record is in this state after it has been locally - // created but before the adapter has indicated that - // it has been saved. - created: createdState, - - // A record is in this state if it has already been - // saved to the server, but there are new local changes - // that have not yet been saved. - updated: updatedState - }), - - // A record is in this state if it was deleted from the store. - deleted: DS.State.create({ - initialState: 'uncommitted', - dirtyType: 'deleted', - - // FLAGS - isDeleted: true, - isLoaded: true, - isDirty: true, - - // TRANSITIONS - setup: function(manager) { - var record = get(manager, 'record'), - store = get(record, 'store'); - - store.removeFromRecordArrays(record); - }, - - // SUBSTATES - - // When a record is deleted, it enters the `start` - // state. It will exit this state when the record's - // transaction starts to commit. - uncommitted: DS.State.create({ - // TRANSITIONS - enter: function(manager) { - var record = get(manager, 'record'); - - record.withTransaction(function(t) { - t.recordBecameDirty('deleted', record); - }); - }, - - // EVENTS - willCommit: function(manager) { - manager.transitionTo('inFlight'); - }, - - rollback: function(manager) { - get(manager, 'record').rollback(); - }, - - becomeDirty: Ember.K, - - becameClean: function(manager) { - var record = get(manager, 'record'); - - record.withTransaction(function(t) { - t.recordBecameClean('deleted', record); - }); - - manager.transitionTo('loaded.materializing'); - } - }), - - // After a record's transaction is committing, but - // before the adapter indicates that the deletion - // has saved to the server, a record is in the - // `inFlight` substate of `deleted`. - inFlight: DS.State.create({ - // FLAGS - isSaving: true, - - // TRANSITIONS - enter: function(manager) { - var record = get(manager, 'record'); - - record.becameInFlight(); - - record.withTransaction(function (t) { - t.recordBecameInFlight('deleted', record); - }); - }, - - // EVENTS - didCommit: function(manager) { - var record = get(manager, 'record'); - - record.withTransaction(function(t) { - t.recordBecameClean('inflight', record); - }); - - manager.transitionTo('saved'); - - manager.send('invokeLifecycleCallbacks'); - } - }), - - // Once the adapter indicates that the deletion has - // been saved, the record enters the `saved` substate - // of `deleted`. - saved: DS.State.create({ - // FLAGS - isDirty: false, - - setup: function(manager) { - var record = get(manager, 'record'), - store = get(record, 'store'); - - store.dematerializeRecord(record); - }, - - invokeLifecycleCallbacks: function(manager) { - var record = get(manager, 'record'); - record.trigger('didDelete', record); - } - }) - }), - - // If the adapter indicates that there was an unknown - // error saving a record, the record enters the `error` - // state. - error: DS.State.create({ - isError: true, - - // EVENTS - - invokeLifecycleCallbacks: function(manager) { - var record = get(manager, 'record'); - record.trigger('becameError', record); - } - }) - }) -}; - -DS.StateManager = Ember.StateManager.extend({ - record: null, - initialState: 'rootState', - states: states, - unhandledEvent: function(manager, originalEvent) { - var record = manager.get('record'), - contexts = [].slice.call(arguments, 2), - errorMessage; - errorMessage = "Attempted to handle event `" + originalEvent + "` "; - errorMessage += "on " + record.toString() + " while in state "; - errorMessage += get(manager, 'currentState.path') + ". Called with "; - errorMessage += arrayMap.call(contexts, function(context){ - return Ember.inspect(context); - }).join(', '); - throw new Ember.Error(errorMessage); - } -}); - -})(); - - - -(function() { -var LoadPromise = DS.LoadPromise; // system/mixins/load_promise - -var get = Ember.get, set = Ember.set, none = Ember.isNone, map = Ember.EnumerableUtils.map; - -var retrieveFromCurrentState = Ember.computed(function(key) { - return get(get(this, 'stateManager.currentState'), key); -}).property('stateManager.currentState'); - -DS.Model = Ember.Object.extend(Ember.Evented, LoadPromise, { - isLoaded: retrieveFromCurrentState, - isReloading: retrieveFromCurrentState, - isDirty: retrieveFromCurrentState, - isSaving: retrieveFromCurrentState, - isDeleted: retrieveFromCurrentState, - isError: retrieveFromCurrentState, - isNew: retrieveFromCurrentState, - isValid: retrieveFromCurrentState, - - clientId: null, - id: null, - transaction: null, - stateManager: null, - errors: null, - - /** - Create a JSON representation of the record, using the serialization - strategy of the store's adapter. - - Available options: - - * `includeId`: `true` if the record's ID should be included in the - JSON representation. - - @param {Object} options - @returns {Object} an object whose values are primitive JSON values only - */ - serialize: function(options) { - var store = get(this, 'store'); - return store.serialize(this, options); - }, - - didLoad: Ember.K, - didReload: Ember.K, - didUpdate: Ember.K, - didCreate: Ember.K, - didDelete: Ember.K, - becameInvalid: Ember.K, - becameError: Ember.K, - - data: Ember.computed(function() { - if (!this._data) { - this.materializeData(); - } - - return this._data; - }).property(), - - materializeData: function() { - this.send('materializingData'); - - get(this, 'store').materializeData(this); - - this.suspendRelationshipObservers(function() { - this.notifyPropertyChange('data'); - }); - }, - - _data: null, - - init: function() { - this._super(); - - var stateManager = DS.StateManager.create({ record: this }); - set(this, 'stateManager', stateManager); - - this._setup(); - - stateManager.goToState('empty'); - }, - - _setup: function() { - this._relationshipChanges = {}; - this._changesToSync = {}; - }, - - send: function(name, context) { - return get(this, 'stateManager').send(name, context); - }, - - withTransaction: function(fn) { - var transaction = get(this, 'transaction'); - if (transaction) { fn(transaction); } - }, - - loadingData: function() { - this.send('loadingData'); - }, - - loadedData: function() { - this.send('loadedData'); - }, - - didChangeData: function() { - this.send('didChangeData'); - }, - - setProperty: function(key, value, oldValue) { - this.send('setProperty', { key: key, value: value, oldValue: oldValue }); - }, - - /** - Reload the record from the adapter. - - This will only work if the record has already finished loading - and has not yet been modified (`isLoaded` but not `isDirty`, - or `isSaving`). - */ - reload: function() { - this.send('reloadRecord'); - }, - - deleteRecord: function() { - this.send('deleteRecord'); - }, - - unloadRecord: function() { - Ember.assert("You can only unload a loaded, non-dirty record.", !get(this, 'isDirty')); - - this.send('unloadRecord'); - }, - - clearRelationships: function() { - this.eachRelationship(function(name, relationship) { - if (relationship.kind === 'belongsTo') { - set(this, name, null); - } else if (relationship.kind === 'hasMany') { - get(this, name).clear(); - } - }, this); - }, - - updateRecordArrays: function() { - var store = get(this, 'store'); - if (store) { - store.dataWasUpdated(this.constructor, get(this, '_reference'), this); - } - }, - - /** - If the adapter did not return a hash in response to a commit, - merge the changed attributes and relationships into the existing - saved data. - */ - adapterDidCommit: function() { - var attributes = get(this, 'data').attributes; - - get(this.constructor, 'attributes').forEach(function(name, meta) { - attributes[name] = get(this, name); - }, this); - - this.send('didCommit'); - this.updateRecordArraysLater(); - }, - - adapterDidDirty: function() { - this.send('becomeDirty'); - this.updateRecordArraysLater(); - }, - - dataDidChange: Ember.observer(function() { - var relationships = get(this.constructor, 'relationshipsByName'); - - this.updateRecordArraysLater(); - - relationships.forEach(function(name, relationship) { - if (relationship.kind === 'hasMany') { - this.hasManyDidChange(relationship.key); - } - }, this); - - this.send('finishedMaterializing'); - }, 'data'), - - hasManyDidChange: function(key) { - var cachedValue = this.cacheFor(key); - - if (cachedValue) { - var type = get(this.constructor, 'relationshipsByName').get(key).type; - var store = get(this, 'store'); - var ids = this._data.hasMany[key] || []; - - var references = map(ids, function(id) { - // if it was already a reference, return the reference - if (typeof id === 'object') { return id; } - return store.referenceForId(type, id); - }); - - set(cachedValue, 'content', Ember.A(references)); - } - }, - - updateRecordArraysLater: function() { - Ember.run.once(this, this.updateRecordArrays); - }, - - setupData: function(prematerialized) { - this._data = { - attributes: {}, - belongsTo: {}, - hasMany: {}, - id: null - }; - }, - - materializeId: function(id) { - set(this, 'id', id); - }, - - materializeAttributes: function(attributes) { - Ember.assert("Must pass a hash of attributes to materializeAttributes", !!attributes); - this._data.attributes = attributes; - }, - - materializeAttribute: function(name, value) { - this._data.attributes[name] = value; - }, - - materializeHasMany: function(name, ids) { - this._data.hasMany[name] = ids; - }, - - materializeBelongsTo: function(name, id) { - this._data.belongsTo[name] = id; - }, - - rollback: function() { - this._setup(); - this.send('becameClean'); - - this.suspendRelationshipObservers(function() { - this.notifyPropertyChange('data'); - }); - }, - - toStringExtension: function() { - return get(this, 'id'); - }, - - /** - @private - - The goal of this method is to temporarily disable specific observers - that take action in response to application changes. - - This allows the system to make changes (such as materialization and - rollback) that should not trigger secondary behavior (such as setting an - inverse relationship or marking records as dirty). - - The specific implementation will likely change as Ember proper provides - better infrastructure for suspending groups of observers, and if Array - observation becomes more unified with regular observers. - */ - suspendRelationshipObservers: function(callback, binding) { - var observers = get(this.constructor, 'relationshipNames').belongsTo; - var self = this; - - try { - this._suspendedRelationships = true; - Ember._suspendObservers(self, observers, null, 'belongsToDidChange', function() { - Ember._suspendBeforeObservers(self, observers, null, 'belongsToWillChange', function() { - callback.call(binding || self); - }); - }); - } finally { - this._suspendedRelationships = false; - } - }, - - becameInFlight: function() { - }, - - // FOR USE DURING COMMIT PROCESS - - adapterDidUpdateAttribute: function(attributeName, value) { - - // If a value is passed in, update the internal attributes and clear - // the attribute cache so it picks up the new value. Otherwise, - // collapse the current value into the internal attributes because - // the adapter has acknowledged it. - if (value !== undefined) { - get(this, 'data.attributes')[attributeName] = value; - this.notifyPropertyChange(attributeName); - } else { - value = get(this, attributeName); - get(this, 'data.attributes')[attributeName] = value; - } - - this.updateRecordArraysLater(); - }, - - _reference: Ember.computed(function() { - return get(this, 'store').referenceForClientId(get(this, 'clientId')); - }), - - adapterDidInvalidate: function(errors) { - this.send('becameInvalid', errors); - }, - - adapterDidError: function() { - this.send('becameError'); - }, - - /** - @private - - Override the default event firing from Ember.Evented to - also call methods with the given name. - */ - trigger: function(name) { - Ember.tryInvoke(this, name, [].slice.call(arguments, 1)); - this._super.apply(this, arguments); - } -}); - -// Helper function to generate store aliases. -// This returns a function that invokes the named alias -// on the default store, but injects the class as the -// first parameter. -var storeAlias = function(methodName) { - return function() { - var store = get(DS, 'defaultStore'), - args = [].slice.call(arguments); - - args.unshift(this); - Ember.assert("Your application does not have a 'Store' property defined. Attempts to call '" + methodName + "' on model classes will fail. Please provide one as with 'YourAppName.Store = DS.Store.extend()'", !!store); - return store[methodName].apply(store, args); - }; -}; - -DS.Model.reopenClass({ - isLoaded: storeAlias('recordIsLoaded'), - find: storeAlias('find'), - all: storeAlias('all'), - query: storeAlias('findQuery'), - filter: storeAlias('filter'), - - _create: DS.Model.create, - - create: function() { - throw new Ember.Error("You should not call `create` on a model. Instead, call `createRecord` with the attributes you would like to set."); - }, - - createRecord: storeAlias('createRecord') -}); - -})(); - - - -(function() { -var get = Ember.get; -DS.Model.reopenClass({ - attributes: Ember.computed(function() { - var map = Ember.Map.create(); - - this.eachComputedProperty(function(name, meta) { - if (meta.isAttribute) { - Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('')` from " + this.toString(), name !== 'id'); - - meta.name = name; - map.set(name, meta); - } - }); - - return map; - }) -}); - -var AttributeChange = DS.AttributeChange = function(options) { - this.reference = options.reference; - this.store = options.store; - this.name = options.name; - this.oldValue = options.oldValue; -}; - -AttributeChange.createChange = function(options) { - return new AttributeChange(options); -}; - -AttributeChange.prototype = { - sync: function() { - this.store.recordAttributeDidChange(this.reference, this.name, this.value, this.oldValue); - - // TODO: Use this object in the commit process - this.destroy(); - }, - - destroy: function() { - delete this.store.recordForReference(this.reference)._changesToSync[this.name]; - } -}; - -DS.Model.reopen({ - eachAttribute: function(callback, binding) { - get(this.constructor, 'attributes').forEach(function(name, meta) { - callback.call(binding, name, meta); - }, binding); - }, - - attributeWillChange: Ember.beforeObserver(function(record, key) { - var reference = get(record, '_reference'), - store = get(record, 'store'); - - record.send('willSetProperty', { reference: reference, store: store, name: key }); - }), - - attributeDidChange: Ember.observer(function(record, key) { - record.send('didSetProperty', { name: key }); - }), - - getAttr: function(key, options) { - var attributes = get(this, 'data').attributes; - var value = attributes[key]; - - if (value === undefined) { - value = options.defaultValue ; - } - - return value; - } -}); - -DS.attr = function(type, options) { - options = options || {}; - - var meta = { - type: type, - isAttribute: true, - options: options - }; - - return Ember.computed(function(key, value, oldValue) { - var data; - - if (arguments.length > 1) { - Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('')` from " + this.constructor.toString(), key !== 'id'); - } else { - value = this.getAttr(key, options); - } - - return value; - // `data` is never set directly. However, it may be - // invalidated from the state manager's setData - // event. - }).property('data').meta(meta); -}; - - -})(); - - - -(function() { - -})(); - - - -(function() { -var get = Ember.get, set = Ember.set, - none = Ember.isNone; - -DS.Model.reopen({ - getBelongsTo: function(key, type, meta) { - var data = get(this, 'data').belongsTo, - store = get(this, 'store'), id; - - if (typeof type === 'string') { - type = get(this, type, false) || get(Ember.lookup, type); - } - - id = data[key]; - - if(!id) { - return null; - } else if (typeof id === 'object') { - return store.recordForReference(id); - } else { - return store.find(type, id); - } - } -}); - -DS.belongsTo = function(type, options) { - Ember.assert("The first argument DS.belongsTo must be a model type or string, like DS.belongsTo(App.Person)", !!type && (typeof type === 'string' || DS.Model.detect(type))); - - options = options || {}; - - var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo' }; - - return Ember.computed(function(key, value) { - if (arguments.length === 2) { - return value === undefined ? null : value; - } - - return this.getBelongsTo(key, type, meta); - }).property('data').meta(meta); -}; - -/** - These observers observe all `belongsTo` relationships on the record. See - `relationships/ext` to see how these observers get their dependencies. - -*/ - -DS.Model.reopen({ - /** @private */ - belongsToWillChange: Ember.beforeObserver(function(record, key) { - if (get(record, 'isLoaded')) { - var oldParent = get(record, key); - - var childReference = get(record, '_reference'), - store = get(record, 'store'); - if (oldParent){ - var change = DS.RelationshipChange.createChange(childReference, get(oldParent, '_reference'), store, { key: key, kind:"belongsTo", changeType: "remove" }); - change.sync(); - this._changesToSync[key] = change; - } - } - }), - - /** @private */ - belongsToDidChange: Ember.immediateObserver(function(record, key) { - if (get(record, 'isLoaded')) { - var newParent = get(record, key); - if(newParent){ - var childReference = get(record, '_reference'), - store = get(record, 'store'); - var change = DS.RelationshipChange.createChange(childReference, get(newParent, '_reference'), store, { key: key, kind:"belongsTo", changeType: "add" }); - change.sync(); - if(this._changesToSync[key]){ - DS.OneToManyChange.ensureSameTransaction([change, this._changesToSync[key]], store); - } - } - } - delete this._changesToSync[key]; - }) -}); - -})(); - - - -(function() { -var get = Ember.get, set = Ember.set; -DS.Model.reopen({ - getHasMany: function(key, type, meta) { - var data = get(this, 'data').hasMany, - store = get(this, 'store'), - ids, relationship; - - if (typeof type === 'string') { - type = get(this, type, false) || get(Ember.lookup, type); - } - - ids = data[key]; - relationship = store.findMany(type, ids || [], this, meta); - set(relationship, 'owner', this); - set(relationship, 'name', key); - - return relationship; - } -}); - -var hasRelationship = function(type, options) { - options = options || {}; - - var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany' }; - - return Ember.computed(function(key, value) { - return this.getHasMany(key, type, meta); - }).property().meta(meta); -}; - -DS.hasMany = function(type, options) { - Ember.assert("The type passed to DS.hasMany must be defined", !!type); - return hasRelationship(type, options); -}; - -})(); - - - -(function() { -var get = Ember.get, set = Ember.set; - -/** - @private - - This file defines several extensions to the base `DS.Model` class that - add support for one-to-many relationships. -*/ - -DS.Model.reopen({ - // This Ember.js hook allows an object to be notified when a property - // is defined. - // - // In this case, we use it to be notified when an Ember Data user defines a - // belongs-to relationship. In that case, we need to set up observers for - // each one, allowing us to track relationship changes and automatically - // reflect changes in the inverse has-many array. - // - // This hook passes the class being set up, as well as the key and value - // being defined. So, for example, when the user does this: - // - // DS.Model.extend({ - // parent: DS.belongsTo(App.User) - // }); - // - // This hook would be called with "parent" as the key and the computed - // property returned by `DS.belongsTo` as the value. - didDefineProperty: function(proto, key, value) { - // Check if the value being set is a computed property. - if (value instanceof Ember.Descriptor) { - - // If it is, get the metadata for the relationship. This is - // populated by the `DS.belongsTo` helper when it is creating - // the computed property. - var meta = value.meta(); - - if (meta.isRelationship && meta.kind === 'belongsTo') { - Ember.addObserver(proto, key, null, 'belongsToDidChange'); - Ember.addBeforeObserver(proto, key, null, 'belongsToWillChange'); - } - - if (meta.isAttribute) { - Ember.addObserver(proto, key, null, 'attributeDidChange'); - Ember.addBeforeObserver(proto, key, null, 'attributeWillChange'); - } - - meta.parentType = proto.constructor; - } - } -}); - -/** - These DS.Model extensions add class methods that provide relationship - introspection abilities about relationships. - - A note about the computed properties contained here: - - **These properties are effectively sealed once called for the first time.** - To avoid repeatedly doing expensive iteration over a model's fields, these - values are computed once and then cached for the remainder of the runtime of - your application. - - If your application needs to modify a class after its initial definition - (for example, using `reopen()` to add additional attributes), make sure you - do it before using your model with the store, which uses these properties - extensively. -*/ - -DS.Model.reopenClass({ - /** - For a given relationship name, returns the model type of the relationship. - - For example, if you define a model like this: - - App.Post = DS.Model.extend({ - comments: DS.hasMany(App.Comment) - }); - - Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`. - - @param {String} name the name of the relationship - @return {subclass of DS.Model} the type of the relationship, or undefined - */ - typeForRelationship: function(name) { - var relationship = get(this, 'relationshipsByName').get(name); - return relationship && relationship.type; - }, - - /** - The model's relationships as a map, keyed on the type of the - relationship. The value of each entry is an array containing a descriptor - for each relationship with that type, describing the name of the relationship - as well as the type. - - For example, given the following model definition: - - App.Blog = DS.Model.extend({ - users: DS.hasMany(App.User), - owner: DS.belongsTo(App.User), - posts: DS.hasMany(App.Post) - }); - - This computed property would return a map describing these - relationships, like this: - - var relationships = Ember.get(App.Blog, 'relationships'); - associatons.get(App.User); - //=> [ { name: 'users', kind: 'hasMany' }, - // { name: 'owner', kind: 'belongsTo' } ] - relationships.get(App.Post); - //=> [ { name: 'posts', kind: 'hasMany' } ] - - @type Ember.Map - @readOnly - */ - relationships: Ember.computed(function() { - var map = new Ember.MapWithDefault({ - defaultValue: function() { return []; } - }); - - // Loop through each computed property on the class - this.eachComputedProperty(function(name, meta) { - - // If the computed property is a relationship, add - // it to the map. - if (meta.isRelationship) { - if (typeof meta.type === 'string') { - meta.type = Ember.get(Ember.lookup, meta.type); - } - - var relationshipsForType = map.get(meta.type); - - relationshipsForType.push({ name: name, kind: meta.kind }); - } - }); - - return map; - }), - - /** - A hash containing lists of the model's relationships, grouped - by the relationship kind. For example, given a model with this - definition: - - App.Blog = DS.Model.extend({ - users: DS.hasMany(App.User), - owner: DS.belongsTo(App.User), - - posts: DS.hasMany(App.Post) - }); - - This property would contain the following: - - var relationshipNames = Ember.get(App.Blog, 'relationshipNames'); - relationshipNames.hasMany; - //=> ['users', 'posts'] - relationshipNames.belongsTo; - //=> ['owner'] - - @type Object - @readOnly - */ - relationshipNames: Ember.computed(function() { - var names = { hasMany: [], belongsTo: [] }; - - this.eachComputedProperty(function(name, meta) { - if (meta.isRelationship) { - names[meta.kind].push(name); - } - }); - - return names; - }), - - /** - An array of types directly related to a model. Each type will be - included once, regardless of the number of relationships it has with - the model. - - For example, given a model with this definition: - - App.Blog = DS.Model.extend({ - users: DS.hasMany(App.User), - owner: DS.belongsTo(App.User), - posts: DS.hasMany(App.Post) - }); - - This property would contain the following: - - var relatedTypes = Ember.get(App.Blog, 'relatedTypes'); - //=> [ App.User, App.Post ] - - @type Ember.Array - @readOnly - */ - relatedTypes: Ember.computed(function() { - var type, - types = Ember.A([]); - - // Loop through each computed property on the class, - // and create an array of the unique types involved - // in relationships - this.eachComputedProperty(function(name, meta) { - if (meta.isRelationship) { - type = meta.type; - - if (typeof type === 'string') { - type = get(this, type, false) || get(Ember.lookup, type); - } - - if (!types.contains(type)) { - types.push(type); - } - } - }); - - return types; - }), - - /** - A map whose keys are the relationships of a model and whose values are - relationship descriptors. - - For example, given a model with this - definition: - - App.Blog = DS.Model.extend({ - users: DS.hasMany(App.User), - owner: DS.belongsTo(App.User), - - posts: DS.hasMany(App.Post) - }); - - This property would contain the following: - - var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName'); - relationshipsByName.get('users'); - //=> { key: 'users', kind: 'hasMany', type: App.User } - relationshipsByName.get('owner'); - //=> { key: 'owner', kind: 'belongsTo', type: App.User } - - @type Ember.Map - @readOnly - */ - relationshipsByName: Ember.computed(function() { - var map = Ember.Map.create(), type; - - this.eachComputedProperty(function(name, meta) { - if (meta.isRelationship) { - meta.key = name; - type = meta.type; - - if (typeof type === 'string') { - type = get(this, type, false) || get(Ember.lookup, type); - meta.type = type; - } - - map.set(name, meta); - } - }); - - return map; - }), - - /** - A map whose keys are the fields of the model and whose values are strings - describing the kind of the field. A model's fields are the union of all of its - attributes and relationships. - - For example: - - App.Blog = DS.Model.extend({ - users: DS.hasMany(App.User), - owner: DS.belongsTo(App.User), - - posts: DS.hasMany(App.Post), - - title: DS.attr('string') - }); - - var fields = Ember.get(App.Blog, 'fields'); - fields.forEach(function(field, kind) { - console.log(field, kind); - }); - - // prints: - // users, hasMany - // owner, belongsTo - // posts, hasMany - // title, attribute - - @type Ember.Map - @readOnly - */ - fields: Ember.computed(function() { - var map = Ember.Map.create(), type; - - this.eachComputedProperty(function(name, meta) { - if (meta.isRelationship) { - map.set(name, meta.kind); - } else if (meta.isAttribute) { - map.set(name, 'attribute'); - } - }); - - return map; - }), - - /** - Given a callback, iterates over each of the relationships in the model, - invoking the callback with the name of each relationship and its relationship - descriptor. - - @param {Function} callback the callback to invoke - @param {any} binding the value to which the callback's `this` should be bound - */ - eachRelationship: function(callback, binding) { - get(this, 'relationshipsByName').forEach(function(name, relationship) { - callback.call(binding, name, relationship); - }); - }, - - /** - Given a callback, iterates over each of the types related to a model, - invoking the callback with the related type's class. Each type will be - returned just once, regardless of how many different relationships it has - with a model. - - @param {Function} callback the callback to invoke - @param {any} binding the value to which the callback's `this` should be bound - */ - eachRelatedType: function(callback, binding) { - get(this, 'relatedTypes').forEach(function(type) { - callback.call(binding, type); - }); - } -}); - -DS.Model.reopen({ - /** - Given a callback, iterates over each of the relationships in the model, - invoking the callback with the name of each relationship and its relationship - descriptor. - - @param {Function} callback the callback to invoke - @param {any} binding the value to which the callback's `this` should be bound - */ - eachRelationship: function(callback, binding) { - this.constructor.eachRelationship(callback, binding); - } -}); - -/** - @private - - Helper method to look up the name of the inverse of a relationship. - - In a has-many relationship, there are always two sides: the `belongsTo` side - and the `hasMany` side. When one side changes, the other side should be updated - automatically. - - Given a model, the model of the inverse, and the kind of the relationship, this - helper returns the name of the relationship on the inverse. - - For example, imagine the following two associated models: - - App.Post = DS.Model.extend({ - comments: DS.hasMany('App.Comment') - }); - - App.Comment = DS.Model.extend({ - post: DS.belongsTo('App.Post') - }); - - If the `post` property of a `Comment` was modified, Ember Data would invoke - this helper like this: - - DS._inverseNameFor(App.Comment, App.Post, 'hasMany'); - //=> 'comments' - - Ember Data uses the name of the relationship returned to reflect the changed - relationship on the other side. -*/ -DS._inverseRelationshipFor = function(modelType, inverseModelType) { - var relationshipMap = get(modelType, 'relationships'), - possibleRelationships = relationshipMap.get(inverseModelType), - possible, actual, oldValue; - - if (!possibleRelationships) { return; } - if (possibleRelationships.length > 1) { return; } - return possibleRelationships[0]; -}; - -/** - @private - - Given a model and a relationship name, returns the model type of - the named relationship. - - App.Post = DS.Model.extend({ - comments: DS.hasMany('App.Comment') - }); - - DS._inverseTypeFor(App.Post, 'comments'); - //=> App.Comment - @param {DS.Model class} modelType - @param {String} relationshipName - @return {DS.Model class} -*/ -DS._inverseTypeFor = function(modelType, relationshipName) { - var relationships = get(modelType, 'relationshipsByName'), - relationship = relationships.get(relationshipName); - - if (relationship) { return relationship.type; } -}; - -})(); - - - -(function() { -var get = Ember.get, set = Ember.set; -var forEach = Ember.EnumerableUtils.forEach; - -DS.RelationshipChange = function(options) { - this.parentReference = options.parentReference; - this.childReference = options.childReference; - this.firstRecordReference = options.firstRecordReference; - this.firstRecordKind = options.firstRecordKind; - this.firstRecordName = options.firstRecordName; - this.secondRecordReference = options.secondRecordReference; - this.secondRecordKind = options.secondRecordKind; - this.secondRecordName = options.secondRecordName; - this.store = options.store; - this.committed = {}; - this.changeType = options.changeType; -}; - -DS.RelationshipChangeAdd = function(options){ - DS.RelationshipChange.call(this, options); -}; - -DS.RelationshipChangeRemove = function(options){ - DS.RelationshipChange.call(this, options); -}; - -/** @private */ -DS.RelationshipChange.create = function(options) { - return new DS.RelationshipChange(options); -}; - -/** @private */ -DS.RelationshipChangeAdd.create = function(options) { - return new DS.RelationshipChangeAdd(options); -}; - -/** @private */ -DS.RelationshipChangeRemove.create = function(options) { - return new DS.RelationshipChangeRemove(options); -}; - -DS.OneToManyChange = {}; -DS.OneToNoneChange = {}; -DS.ManyToNoneChange = {}; -DS.OneToOneChange = {}; -DS.ManyToManyChange = {}; - -DS.RelationshipChange._createChange = function(options){ - if(options.changeType === "add"){ - return DS.RelationshipChangeAdd.create(options); - } - if(options.changeType === "remove"){ - return DS.RelationshipChangeRemove.create(options); - } -}; - - -DS.RelationshipChange.determineRelationshipType = function(recordType, knownSide){ - var knownKey = knownSide.key, key, type, otherContainerType,assoc; - var knownContainerType = knownSide.kind; - var options = recordType.metaForProperty(knownKey).options; - var otherType = DS._inverseTypeFor(recordType, knownKey); - - if(options.inverse){ - key = options.inverse; - otherContainerType = get(otherType, 'relationshipsByName').get(key).kind; - } - else if(assoc = DS._inverseRelationshipFor(otherType, recordType)){ - key = assoc.name; - otherContainerType = assoc.kind; - } - if(!key){ - return knownContainerType === "belongsTo" ? "oneToNone" : "manyToNone"; - } - else{ - if(otherContainerType === "belongsTo"){ - return knownContainerType === "belongsTo" ? "oneToOne" : "manyToOne"; - } - else{ - return knownContainerType === "belongsTo" ? "oneToMany" : "manyToMany"; - } - } - -}; - -DS.RelationshipChange.createChange = function(firstRecordReference, secondRecordReference, store, options){ - // Get the type of the child based on the child's client ID - var firstRecordType = firstRecordReference.type, key, changeType; - changeType = DS.RelationshipChange.determineRelationshipType(firstRecordType, options); - if (changeType === "oneToMany"){ - return DS.OneToManyChange.createChange(firstRecordReference, secondRecordReference, store, options); - } - else if (changeType === "manyToOne"){ - return DS.OneToManyChange.createChange(secondRecordReference, firstRecordReference, store, options); - } - else if (changeType === "oneToNone"){ - return DS.OneToNoneChange.createChange(firstRecordReference, secondRecordReference, store, options); - } - else if (changeType === "manyToNone"){ - return DS.ManyToNoneChange.createChange(firstRecordReference, secondRecordReference, store, options); - } - else if (changeType === "oneToOne"){ - return DS.OneToOneChange.createChange(firstRecordReference, secondRecordReference, store, options); - } - else if (changeType === "manyToMany"){ - return DS.ManyToManyChange.createChange(firstRecordReference, secondRecordReference, store, options); - } -}; - -/** @private */ -DS.OneToNoneChange.createChange = function(childReference, parentReference, store, options) { - var key = options.key; - var change = DS.RelationshipChange._createChange({ - parentReference: parentReference, - childReference: childReference, - firstRecordReference: childReference, - store: store, - changeType: options.changeType, - firstRecordName: key, - firstRecordKind: "belongsTo" - }); - - store.addRelationshipChangeFor(childReference, key, parentReference, null, change); - - return change; -}; - -/** @private */ -DS.ManyToNoneChange.createChange = function(childReference, parentReference, store, options) { - var key = options.key; - var change = DS.RelationshipChange._createChange({ - parentReference: childReference, - childReference: parentReference, - secondRecordReference: childReference, - store: store, - changeType: options.changeType, - secondRecordName: options.key, - secondRecordKind: "hasMany" - }); - - store.addRelationshipChangeFor(childReference, key, parentReference, null, change); - return change; -}; - - -/** @private */ -DS.ManyToManyChange.createChange = function(childReference, parentReference, store, options) { - // Get the type of the child based on the child's client ID - var childType = childReference.type, key; - - // If the name of the belongsTo side of the relationship is specified, - // use that - // If the type of the parent is specified, look it up on the child's type - // definition. - key = options.key; - - var change = DS.RelationshipChange._createChange({ - parentReference: parentReference, - childReference: childReference, - firstRecordReference: childReference, - secondRecordReference: parentReference, - firstRecordKind: "hasMany", - secondRecordKind: "hasMany", - store: store, - changeType: options.changeType, - firstRecordName: key - }); - - store.addRelationshipChangeFor(childReference, key, parentReference, null, change); - - - return change; -}; - -/** @private */ -DS.OneToOneChange.createChange = function(childReference, parentReference, store, options) { - // Get the type of the child based on the child's client ID - var childType = childReference.type, key; - - // If the name of the belongsTo side of the relationship is specified, - // use that - // If the type of the parent is specified, look it up on the child's type - // definition. - if (options.parentType) { - key = inverseBelongsToName(options.parentType, childType, options.key); - //DS.OneToOneChange.maintainInvariant( options, store, childReference, key ); - } else if (options.key) { - key = options.key; - } else { - Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false); - } - - var change = DS.RelationshipChange._createChange({ - parentReference: parentReference, - childReference: childReference, - firstRecordReference: childReference, - secondRecordReference: parentReference, - firstRecordKind: "belongsTo", - secondRecordKind: "belongsTo", - store: store, - changeType: options.changeType, - firstRecordName: key - }); - - store.addRelationshipChangeFor(childReference, key, parentReference, null, change); - - - return change; -}; - -DS.OneToOneChange.maintainInvariant = function(options, store, childReference, key){ - if (options.changeType === "add" && store.recordIsMaterialized(childReference)) { - var child = store.recordForReference(childReference); - var oldParent = get(child, key); - if (oldParent){ - var correspondingChange = DS.OneToOneChange.createChange(childReference, oldParent.get('_reference'), store, { - parentType: options.parentType, - hasManyName: options.hasManyName, - changeType: "remove", - key: options.key - }); - store.addRelationshipChangeFor(childReference, key, options.parentReference , null, correspondingChange); - correspondingChange.sync(); - } - } -}; - -/** @private */ -DS.OneToManyChange.createChange = function(childReference, parentReference, store, options) { - // Get the type of the child based on the child's client ID - var childType = childReference.type, key; - - // If the name of the belongsTo side of the relationship is specified, - // use that - // If the type of the parent is specified, look it up on the child's type - // definition. - if (options.parentType) { - key = inverseBelongsToName(options.parentType, childType, options.key); - DS.OneToManyChange.maintainInvariant( options, store, childReference, key ); - } else if (options.key) { - key = options.key; - } else { - Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false); - } - - var change = DS.RelationshipChange._createChange({ - parentReference: parentReference, - childReference: childReference, - firstRecordReference: childReference, - secondRecordReference: parentReference, - firstRecordKind: "belongsTo", - secondRecordKind: "hasMany", - store: store, - changeType: options.changeType, - firstRecordName: key - }); - - store.addRelationshipChangeFor(childReference, key, parentReference, null, change); - - - return change; -}; - - -DS.OneToManyChange.maintainInvariant = function(options, store, childReference, key){ - if (options.changeType === "add" && store.recordIsMaterialized(childReference)) { - var child = store.recordForReference(childReference); - var oldParent = get(child, key); - if (oldParent){ - var correspondingChange = DS.OneToManyChange.createChange(childReference, oldParent.get('_reference'), store, { - parentType: options.parentType, - hasManyName: options.hasManyName, - changeType: "remove", - key: options.key - }); - store.addRelationshipChangeFor(childReference, key, options.parentReference , null, correspondingChange); - correspondingChange.sync(); - } - } -}; - -DS.OneToManyChange.ensureSameTransaction = function(changes, store){ - var records = Ember.A(); - forEach(changes, function(change){ - records.addObject(change.getSecondRecord()); - records.addObject(change.getFirstRecord()); - }); - var transaction = store.ensureSameTransaction(records); - forEach(changes, function(change){ - change.transaction = transaction; - }); -}; - -DS.RelationshipChange.prototype = { - - getSecondRecordName: function() { - var name = this.secondRecordName, store = this.store, parent; - - if (!name) { - parent = this.secondRecordReference; - if (!parent) { return; } - - var childType = this.firstRecordReference.type; - var inverseType = DS._inverseTypeFor(childType, this.firstRecordName); - name = inverseHasManyName(inverseType, childType, this.firstRecordName); - this.secondRecordName = name; - } - - return name; - }, - - /** - Get the name of the relationship on the belongsTo side. - - @returns {String} - */ - getFirstRecordName: function() { - var name = this.firstRecordName, store = this.store, parent, child; - - if (!name) { - parent = this.secondRecordReference; - child = this.firstRecordReference; - if (!(child && parent)) { return; } - - name = DS._inverseRelationshipFor(child.type, parent.type).name; - - this.firstRecordName = name; - } - - return name; - }, - - /** @private */ - destroy: function() { - var childReference = this.childReference, - belongsToName = this.getFirstRecordName(), - hasManyName = this.getSecondRecordName(), - store = this.store, - child, oldParent, newParent, lastParent, transaction; - - store.removeRelationshipChangeFor(childReference, belongsToName, this.parentReference, hasManyName, this.changeType); - - if (transaction = this.transaction) { - transaction.relationshipBecameClean(this); - } - }, - - /** @private */ - getByReference: function(reference) { - var store = this.store; - - // return null or undefined if the original reference was null or undefined - if (!reference) { return reference; } - - if (store.recordIsMaterialized(reference)) { - return store.recordForReference(reference); - } - }, - - getSecondRecord: function(){ - return this.getByReference(this.secondRecordReference); - }, - - /** @private */ - getFirstRecord: function() { - return this.getByReference(this.firstRecordReference); - }, - - /** - @private - - Make sure that all three parts of the relationship change are part of - the same transaction. If any of the three records is clean and in the - default transaction, and the rest are in a different transaction, move - them all into that transaction. - */ - ensureSameTransaction: function() { - var child = this.getFirstRecord(), - parentRecord = this.getSecondRecord(); - - var transaction = this.store.ensureSameTransaction([child, parentRecord]); - - this.transaction = transaction; - return transaction; - }, - - callChangeEvents: function(){ - var hasManyName = this.getSecondRecordName(), - belongsToName = this.getFirstRecordName(), - child = this.getFirstRecord(), - parentRecord = this.getSecondRecord(); - - var dirtySet = new Ember.OrderedSet(); - - // TODO: This implementation causes a race condition in key-value - // stores. The fix involves buffering changes that happen while - // a record is loading. A similar fix is required for other parts - // of ember-data, and should be done as new infrastructure, not - // a one-off hack. [tomhuda] - if (parentRecord && get(parentRecord, 'isLoaded')) { - this.store.recordHasManyDidChange(dirtySet, parentRecord, this); - } - - if (child) { - this.store.recordBelongsToDidChange(dirtySet, child, this); - } - - dirtySet.forEach(function(record) { - record.adapterDidDirty(); - }); - }, - - coalesce: function(){ - var relationshipPairs = this.store.relationshipChangePairsFor(this.firstRecordReference); - forEach(relationshipPairs, function(pair){ - var addedChange = pair["add"]; - var removedChange = pair["remove"]; - if(addedChange && removedChange) { - addedChange.destroy(); - removedChange.destroy(); - } - }); - } -}; - -DS.RelationshipChangeAdd.prototype = Ember.create(DS.RelationshipChange.create({})); -DS.RelationshipChangeRemove.prototype = Ember.create(DS.RelationshipChange.create({})); - -DS.RelationshipChangeAdd.prototype.changeType = "add"; -DS.RelationshipChangeAdd.prototype.sync = function() { - var secondRecordName = this.getSecondRecordName(), - firstRecordName = this.getFirstRecordName(), - firstRecord = this.getFirstRecord(), - secondRecord = this.getSecondRecord(); - - //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); - //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); - - var transaction = this.ensureSameTransaction(); - transaction.relationshipBecameDirty(this); - - this.callChangeEvents(); - - if (secondRecord && firstRecord) { - if(this.secondRecordKind === "belongsTo"){ - secondRecord.suspendRelationshipObservers(function(){ - set(secondRecord, secondRecordName, firstRecord); - }); - - } - else if(this.secondRecordKind === "hasMany"){ - secondRecord.suspendRelationshipObservers(function(){ - get(secondRecord, secondRecordName).addObject(firstRecord); - }); - } - } - - if (firstRecord && secondRecord && get(firstRecord, firstRecordName) !== secondRecord) { - if(this.firstRecordKind === "belongsTo"){ - firstRecord.suspendRelationshipObservers(function(){ - set(firstRecord, firstRecordName, secondRecord); - }); - } - else if(this.firstdRecordKind === "hasMany"){ - firstRecord.suspendRelationshipObservers(function(){ - get(firstRecord, firstRecordName).addObject(secondRecord); - }); - } - } - - this.coalesce(); -}; - -DS.RelationshipChangeRemove.prototype.changeType = "remove"; -DS.RelationshipChangeRemove.prototype.sync = function() { - var secondRecordName = this.getSecondRecordName(), - firstRecordName = this.getFirstRecordName(), - firstRecord = this.getFirstRecord(), - secondRecord = this.getSecondRecord(); - - //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); - //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); - - var transaction = this.ensureSameTransaction(firstRecord, secondRecord, secondRecordName, firstRecordName); - transaction.relationshipBecameDirty(this); - - this.callChangeEvents(); - - if (secondRecord && firstRecord) { - if(this.secondRecordKind === "belongsTo"){ - secondRecord.suspendRelationshipObservers(function(){ - set(secondRecord, secondRecordName, null); - }); - } - else if(this.secondRecordKind === "hasMany"){ - secondRecord.suspendRelationshipObservers(function(){ - get(secondRecord, secondRecordName).removeObject(firstRecord); - }); - } - } - - if (firstRecord && get(firstRecord, firstRecordName)) { - if(this.firstRecordKind === "belongsTo"){ - firstRecord.suspendRelationshipObservers(function(){ - set(firstRecord, firstRecordName, null); - }); - } - else if(this.firstdRecordKind === "hasMany"){ - firstRecord.suspendRelationshipObservers(function(){ - get(firstRecord, firstRecordName).removeObject(secondRecord); - }); - } - } - - this.coalesce(); -}; - -function inverseBelongsToName(parentType, childType, hasManyName) { - // Get the options passed to the parent's DS.hasMany() - var options = parentType.metaForProperty(hasManyName).options; - var belongsToName; - - if (belongsToName = options.inverse) { - return belongsToName; - } - - return DS._inverseRelationshipFor(childType, parentType).name; -} - -function inverseHasManyName(parentType, childType, belongsToName) { - var options = childType.metaForProperty(belongsToName).options; - var hasManyName; - - if (hasManyName = options.inverse) { - return hasManyName; - } - - return DS._inverseRelationshipFor(parentType, childType).name; -} - -})(); - - - -(function() { - -})(); - - - -(function() { -var set = Ember.set; - -/** - This code registers an injection for Ember.Application. - - If an Ember.js developer defines a subclass of DS.Store on their application, - this code will automatically instantiate it and make it available on the - router. - - Additionally, after an application's controllers have been injected, they will - each have the store made available to them. - - For example, imagine an Ember.js application with the following classes: - - App.Store = DS.Store.extend({ - adapter: 'App.MyCustomAdapter' - }); - - App.PostsController = Ember.ArrayController.extend({ - // ... - }); - - When the application is initialized, `App.Store` will automatically be - instantiated, and the instance of `App.PostsController` will have its `store` - property set to that instance. - - Note that this code will only be run if the `ember-application` package is - loaded. If Ember Data is being used in an environment other than a - typical application (e.g., node.js where only `ember-runtime` is available), - this code will be ignored. -*/ - -Ember.onLoad('Ember.Application', function(Application) { - if (Application.registerInjection) { - Application.registerInjection({ - name: "store", - before: "controllers", - - // If a store subclass is defined, like App.Store, - // instantiate it and inject it into the router. - injection: function(app, stateManager, property) { - if (!stateManager) { return; } - if (property === 'Store') { - set(stateManager, 'store', app[property].create()); - } - } - }); - - Application.registerInjection({ - name: "giveStoreToControllers", - after: ['store','controllers'], - - // For each controller, set its `store` property - // to the DS.Store instance we created above. - injection: function(app, stateManager, property) { - if (!stateManager) { return; } - if (/^[A-Z].*Controller$/.test(property)) { - var controllerName = property.charAt(0).toLowerCase() + property.substr(1); - var store = stateManager.get('store'); - var controller = stateManager.get(controllerName); - if(!controller) { return; } - - controller.set('store', store); - } - } - }); - } else if (Application.initializer) { - Application.initializer({ - name: "store", - - initialize: function(container, application) { - container.register('store', 'main', application.Store); - - // Eagerly generate the store so defaultStore is populated. - // TODO: Do this in a finisher hook - container.lookup('store:main'); - } - }); - - Application.initializer({ - name: "injectStore", - - initialize: function(container) { - container.typeInjection('controller', 'store', 'store:main'); - container.typeInjection('route', 'store', 'store:main'); - } - }); - } -}); - -})(); - - - -(function() { -var get = Ember.get, set = Ember.set, map = Ember.ArrayPolyfills.map, isNone = Ember.isNone; - -function mustImplement(name) { - return function() { - throw new Ember.Error("Your serializer " + this.toString() + " does not implement the required method " + name); - }; -} - -/** - A serializer is responsible for serializing and deserializing a group of - records. - - `DS.Serializer` is an abstract base class designed to help you build a - serializer that can read to and write from any serialized form. While most - applications will use `DS.JSONSerializer`, which reads and writes JSON, the - serializer architecture allows your adapter to transmit things like XML, - strings, or custom binary data. - - Typically, your application's `DS.Adapter` is responsible for both creating a - serializer as well as calling the appropriate methods when it needs to - materialize data or serialize a record. - - The serializer API is designed as a series of layered hooks that you can - override to customize any of the individual steps of serialization and - deserialization. - - The hooks are organized by the three responsibilities of the serializer: - - 1. Determining naming conventions - 2. Serializing records into a serialized form - 3. Deserializing records from a serialized form - - Because Ember Data lazily materializes records, the deserialization - step, and therefore the hooks you implement, are split into two phases: - - 1. Extraction, where the serialized forms for multiple records are - extracted from a single payload. The IDs of each record are also - extracted for indexing. - 2. Materialization, where a newly-created record has its attributes - and relationships initialized based on the serialized form loaded - by the adapter. - - Additionally, a serializer can convert values from their JavaScript - versions into their serialized versions via a declarative API. - - ## Naming Conventions - - One of the most common uses of the serializer is to map attribute names - from the serialized form to your `DS.Model`. For example, in your model, - you may have an attribute called `firstName`: - - ```javascript - App.Person = DS.Model.extend({ - firstName: DS.attr('string') - }); - ``` - - However, because the web API your adapter is communicating with is - legacy, it calls this attribute `FIRST_NAME`. - - You can determine the attribute name used in the serialized form - by implementing `keyForAttributeName`: - - ```javascript - keyForAttributeName: function(type, name) { - return name.underscore.toUpperCase(); - } - ``` - - If your attribute names are not predictable, you can re-map them - one-by-one using the `map` API: - - ```javascript - App.Person.map('App.Person', { - firstName: { key: '*API_USER_FIRST_NAME*' } - }); - ``` - - ## Serialization - - During the serialization process, a record or records are converted - from Ember.js objects into their serialized form. - - These methods are designed in layers, like a delicious 7-layer - cake (but with fewer layers). - - The main entry point for serialization is the `serialize` - method, which takes the record and options. - - The `serialize` method is responsible for: - - * turning the record's attributes (`DS.attr`) into - attributes on the JSON object. - * optionally adding the record's ID onto the hash - * adding relationships (`DS.hasMany` and `DS.belongsTo`) - to the JSON object. - - Depending on the backend, the serializer can choose - whether to include the `hasMany` or `belongsTo` - relationships on the JSON hash. - - For very custom serialization, you can implement your - own `serialize` method. In general, however, you will want - to override the hooks described below. - - ### Adding the ID - - The default `serialize` will optionally call your serializer's - `addId` method with the JSON hash it is creating, the - record's type, and the record's ID. The `serialize` method - will not call `addId` if the record's ID is undefined. - - Your adapter must specifically request ID inclusion by - passing `{ includeId: true }` as an option to `serialize`. - - NOTE: You may not want to include the ID when updating an - existing record, because your server will likely disallow - changing an ID after it is created, and the PUT request - itself will include the record's identification. - - By default, `addId` will: - - 1. Get the primary key name for the record by calling - the serializer's `primaryKey` with the record's type. - Unless you override the `primaryKey` method, this - will be `'id'`. - 2. Assign the record's ID to the primary key in the - JSON hash being built. - - If your backend expects a JSON object with the primary - key at the root, you can just override the `primaryKey` - method on your serializer subclass. - - Otherwise, you can override the `addId` method for - more specialized handling. - - ### Adding Attributes - - By default, the serializer's `serialize` method will call - `addAttributes` with the JSON object it is creating - and the record to serialize. - - The `addAttributes` method will then call `addAttribute` - in turn, with the JSON object, the record to serialize, - the attribute's name and its type. - - Finally, the `addAttribute` method will serialize the - attribute: - - 1. It will call `keyForAttributeName` to determine - the key to use in the JSON hash. - 2. It will get the value from the record. - 3. It will call `serializeValue` with the attribute's - value and attribute type to convert it into a - JSON-compatible value. For example, it will convert a - Date into a String. - - If your backend expects a JSON object with attributes as - keys at the root, you can just override the `serializeValue` - and `keyForAttributeName` methods in your serializer - subclass and let the base class do the heavy lifting. - - If you need something more specialized, you can probably - override `addAttribute` and let the default `addAttributes` - handle the nitty gritty. - - ### Adding Relationships - - By default, `serialize` will call your serializer's - `addRelationships` method with the JSON object that is - being built and the record being serialized. The default - implementation of this method is to loop over all of the - relationships defined on your record type and: - - * If the relationship is a `DS.hasMany` relationship, - call `addHasMany` with the JSON object, the record - and a description of the relationship. - * If the relationship is a `DS.belongsTo` relationship, - call `addBelongsTo` with the JSON object, the record - and a description of the relationship. - - The relationship description has the following keys: - - * `type`: the class of the associated information (the - first parameter to `DS.hasMany` or `DS.belongsTo`) - * `kind`: either `hasMany` or `belongsTo` - - The relationship description may get additional - information in the future if more capabilities or - relationship types are added. However, it will - remain backwards-compatible, so the mere existence - of new features should not break existing adapters. -*/ -DS.Serializer = Ember.Object.extend({ - init: function() { - this.mappings = Ember.Map.create(); - this.configurations = Ember.Map.create(); - this.globalConfigurations = {}; - }, - - extract: mustImplement('extract'), - extractMany: mustImplement('extractMany'), - - extractRecordRepresentation: function(loader, type, json, shouldSideload) { - var mapping = this.mappingForType(type); - var embeddedData, prematerialized = {}, reference; - - if (shouldSideload) { - reference = loader.sideload(type, json); - } else { - reference = loader.load(type, json); - } - - this.eachEmbeddedHasMany(type, function(name, relationship) { - var embeddedData = json[this.keyFor(relationship)]; - if (!isNone(embeddedData)) { - this.extractEmbeddedHasMany(loader, relationship, embeddedData, reference, prematerialized); - } - }, this); - - this.eachEmbeddedBelongsTo(type, function(name, relationship) { - var embeddedData = json[this.keyFor(relationship)]; - if (!isNone(embeddedData)) { - this.extractEmbeddedBelongsTo(loader, relationship, embeddedData, reference, prematerialized); - } - }, this); - - loader.prematerialize(reference, prematerialized); - - return reference; - }, - - extractEmbeddedHasMany: function(loader, relationship, array, parent, prematerialized) { - var references = map.call(array, function(item) { - if (!item) { return; } - - var reference = this.extractRecordRepresentation(loader, relationship.type, item, true); - - // If the embedded record should also be saved back when serializing the parent, - // make sure we set its parent since it will not have an ID. - var embeddedType = this.embeddedType(parent.type, relationship.key); - if (embeddedType === 'always') { - reference.parent = parent; - } - - return reference; - }, this); - - prematerialized[relationship.key] = references; - }, - - extractEmbeddedBelongsTo: function(loader, relationship, data, parent, prematerialized) { - var reference = this.extractRecordRepresentation(loader, relationship.type, data, true); - prematerialized[relationship.key] = reference; - - // If the embedded record should also be saved back when serializing the parent, - // make sure we set its parent since it will not have an ID. - var embeddedType = this.embeddedType(parent.type, relationship.key); - if (embeddedType === 'always') { - reference.parent = parent; - } - }, - - //....................... - //. SERIALIZATION HOOKS - //....................... - - /** - The main entry point for serializing a record. While you can consider this - a hook that can be overridden in your serializer, you will have to manually - handle serialization. For most cases, there are more granular hooks that you - can override. - - If overriding this method, these are the responsibilities that you will need - to implement yourself: - - * If the option hash contains `includeId`, add the record's ID to the serialized form. - By default, `serialize` calls `addId` if appropriate. - * Add the record's attributes to the serialized form. By default, `serialize` calls - `addAttributes`. - * Add the record's relationships to the serialized form. By default, `serialize` calls - `addRelationships`. - - @param {DS.Model} record the record to serialize - @param {Object} [options] a hash of options - @returns {any} the serialized form of the record - */ - serialize: function(record, options) { - options = options || {}; - - var serialized = this.createSerializedForm(), id; - - if (options.includeId) { - if (id = get(record, 'id')) { - this._addId(serialized, record.constructor, id); - } - } - - this.addAttributes(serialized, record); - this.addRelationships(serialized, record); - - return serialized; - }, - - /** - @private - - Given an attribute type and value, convert the value into the - serialized form using the transform registered for that type. - - @param {any} value the value to convert to the serialized form - @param {String} attributeType the registered type (e.g. `string` - or `boolean`) - @returns {any} the serialized form of the value - */ - serializeValue: function(value, attributeType) { - var transform = this.transforms ? this.transforms[attributeType] : null; - - Ember.assert("You tried to use an attribute type (" + attributeType + ") that has not been registered", transform); - return transform.serialize(value); - }, - - /** - A hook you can use to normalize IDs before adding them to the - serialized representation. - - Because the store coerces all IDs to strings for consistency, - this is the opportunity for the serializer to, for example, - convert numerical IDs back into number form. - - @param {String} id the id from the record - @returns {any} the serialized representation of the id - */ - serializeId: function(id) { - if (isNaN(id)) { return id; } - return +id; - }, - - /** - A hook you can use to change how attributes are added to the serialized - representation of a record. - - By default, `addAttributes` simply loops over all of the attributes of the - passed record, maps the attribute name to the key for the serialized form, - and invokes any registered transforms on the value. It then invokes the - more granular `addAttribute` with the key and transformed value. - - Since you can override `keyForAttributeName`, `addAttribute`, and register - custom tranforms, you should rarely need to override this hook. - - @param {any} data the serialized representation that is being built - @param {DS.Model} record the record to serialize - */ - addAttributes: function(data, record) { - record.eachAttribute(function(name, attribute) { - this._addAttribute(data, record, name, attribute.type); - }, this); - }, - - /** - A hook you can use to customize how the key/value pair is added to - the serialized data. - - @param {any} serialized the serialized form being built - @param {String} key the key to add to the serialized data - @param {any} value the value to add to the serialized data - */ - addAttribute: Ember.K, - - /** - A hook you can use to customize how the record's id is added to - the serialized data. - - The `addId` hook is called with: - - * the serialized representation being built - * the resolved primary key (taking configurations and the - `primaryKey` hook into consideration) - * the serialized id (after calling the `serializeId` hook) - - @param {any} data the serialized representation that is being built - @param {String} key the resolved primary key - @param {id} id the serialized id - */ - addId: Ember.K, - - /** - A hook you can use to change how relationships are added to the serialized - representation of a record. - - By default, `addAttributes` loops over all of the relationships of the - passed record, maps the relationship names to the key for the serialized form, - and then invokes the public `addBelongsTo` and `addHasMany` hooks. - - Since you can override `keyForBelongsTo`, `keyForHasMany`, `addBelongsTo`, - `addHasMany`, and register mappings, you should rarely need to override this - hook. - - @param {any} data the serialized representation that is being built - @param {DS.Model} record the record to serialize - */ - addRelationships: function(data, record) { - record.eachRelationship(function(name, relationship) { - if (relationship.kind === 'belongsTo') { - this._addBelongsTo(data, record, name, relationship); - } else if (relationship.kind === 'hasMany') { - this._addHasMany(data, record, name, relationship); - } - }, this); - }, - - /** - A hook you can use to add a `belongsTo` relationship to the - serialized representation. - - The specifics of this hook are very adapter-specific, so there - is no default implementation. You can see `DS.JSONSerializer` - for an example of an implementation of the `addBelongsTo` hook. - - The `belongsTo` relationship object has the following properties: - - * **type** a subclass of DS.Model that is the type of the - relationship. This is the first parameter to DS.belongsTo - * **options** the options passed to the call to DS.belongsTo - * **kind** always `belongsTo` - - Additional properties may be added in the future. - - @param {any} data the serialized representation that is being built - @param {DS.Model} record the record to serialize - @param {String} key the key for the serialized object - @param {Object} relationship an object representing the relationship - */ - addBelongsTo: Ember.K, - - /** - A hook you can use to add a `hasMany` relationship to the - serialized representation. - - The specifics of this hook are very adapter-specific, so there - is no default implementation. You may not need to implement this, - for example, if your backend only expects relationships on the - child of a one to many relationship. - - The `hasMany` relationship object has the following properties: - - * **type** a subclass of DS.Model that is the type of the - relationship. This is the first parameter to DS.hasMany - * **options** the options passed to the call to DS.hasMany - * **kind** always `hasMany` - - Additional properties may be added in the future. - - @param {any} data the serialized representation that is being built - @param {DS.Model} record the record to serialize - @param {String} key the key for the serialized object - @param {Object} relationship an object representing the relationship - */ - addHasMany: Ember.K, - - /** - NAMING CONVENTIONS - - The most commonly overridden APIs of the serializer are - the naming convention methods: - - * `keyForAttributeName`: converts a camelized attribute name - into a key in the adapter-provided data hash. For example, - if the model's attribute name was `firstName`, and the - server used underscored names, you would return `first_name`. - * `primaryKey`: returns the key that should be used to - extract the id from the adapter-provided data hash. It is - also used when serializing a record. - */ - - /** - A hook you can use in your serializer subclass to customize - how an unmapped attribute name is converted into a key. - - By default, this method returns the `name` parameter. - - For example, if the attribute names in your JSON are underscored, - you will want to convert them into JavaScript conventional - camelcase: - - ```javascript - App.MySerializer = DS.Serializer.extend({ - // ... - - keyForAttributeName: function(type, name) { - return name.camelize(); - } - }); - ``` - - @param {DS.Model subclass} type the type of the record with - the attribute name `name` - @param {String} name the attribute name to convert into a key - - @returns {String} the key - */ - keyForAttributeName: function(type, name) { - return name; - }, - - /** - A hook you can use in your serializer to specify a conventional - primary key. - - By default, this method will return the string `id`. - - In general, you should not override this hook to specify a special - primary key for an individual type; use `configure` instead. - - For example, if your primary key is always `__id__`: - - ```javascript - App.MySerializer = DS.Serializer.extend({ - // ... - primaryKey: function(type) { - return '__id__'; - } - }); - ``` - - In another example, if the primary key always includes the - underscored version of the type before the string `id`: - - ```javascript - App.MySerializer = DS.Serializer.extend({ - // ... - primaryKey: function(type) { - // If the type is `BlogPost`, this will return - // `blog_post_id`. - var typeString = type.toString().split(".")[1].underscore(); - return typeString + "_id"; - } - }); - ``` - - @param {DS.Model subclass} type - @returns {String} the primary key for the type - */ - primaryKey: function(type) { - return "id"; - }, - - /** - A hook you can use in your serializer subclass to customize - how an unmapped `belongsTo` relationship is converted into - a key. - - By default, this method calls `keyForAttributeName`, so if - your naming convention is uniform across attributes and - relationships, you can use the default here and override - just `keyForAttributeName` as needed. - - For example, if the `belongsTo` names in your JSON always - begin with `BT_` (e.g. `BT_posts`), you can strip out the - `BT_` prefix:" - - ```javascript - App.MySerializer = DS.Serializer.extend({ - // ... - keyForBelongsTo: function(type, name) { - return name.match(/^BT_(.*)$/)[1].camelize(); - } - }); - ``` - - @param {DS.Model subclass} type the type of the record with - the `belongsTo` relationship. - @param {String} name the relationship name to convert into a key - - @returns {String} the key - */ - keyForBelongsTo: function(type, name) { - return this.keyForAttributeName(type, name); - }, - - /** - A hook you can use in your serializer subclass to customize - how an unmapped `hasMany` relationship is converted into - a key. - - By default, this method calls `keyForAttributeName`, so if - your naming convention is uniform across attributes and - relationships, you can use the default here and override - just `keyForAttributeName` as needed. - - For example, if the `hasMany` names in your JSON always - begin with the "table name" for the current type (e.g. - `post_comments`), you can strip out the prefix:" - - ```javascript - App.MySerializer = DS.Serializer.extend({ - // ... - keyForHasMany: function(type, name) { - // if your App.BlogPost has many App.BlogComment, the key from - // the server would look like: `blog_post_blog_comments` - // - // 1. Convert the type into a string and underscore the - // second part (App.BlogPost -> blog_post) - // 2. Extract the part after `blog_post_` (`blog_comments`) - // 3. Underscore it, to become `blogComments` - var typeString = type.toString().split(".")[1].underscore(); - return name.match(new RegExp("^" + typeString + "_(.*)$"))[1].camelize(); - } - }); - ``` - - @param {DS.Model subclass} type the type of the record with - the `belongsTo` relationship. - @param {String} name the relationship name to convert into a key - - @returns {String} the key - */ - keyForHasMany: function(type, name) { - return this.keyForAttributeName(type, name); - }, - - //......................... - //. MATERIALIZATION HOOKS - //......................... - - materialize: function(record, serialized, prematerialized) { - var id; - if (Ember.isNone(get(record, 'id'))) { - if (prematerialized && prematerialized.hasOwnProperty('id')) { - id = prematerialized.id; - } else { - id = this.extractId(record.constructor, serialized); - } - record.materializeId(id); - } - - this.materializeAttributes(record, serialized, prematerialized); - this.materializeRelationships(record, serialized, prematerialized); - }, - - deserializeValue: function(value, attributeType) { - var transform = this.transforms ? this.transforms[attributeType] : null; - - Ember.assert("You tried to use a attribute type (" + attributeType + ") that has not been registered", transform); - return transform.deserialize(value); - }, - - materializeAttributes: function(record, serialized, prematerialized) { - record.eachAttribute(function(name, attribute) { - if (prematerialized && prematerialized.hasOwnProperty(name)) { - record.materializeAttribute(name, prematerialized[name]); - } else { - this.materializeAttribute(record, serialized, name, attribute.type); - } - }, this); - }, - - materializeAttribute: function(record, serialized, attributeName, attributeType) { - var value = this.extractAttribute(record.constructor, serialized, attributeName); - value = this.deserializeValue(value, attributeType); - - record.materializeAttribute(attributeName, value); - }, - - materializeRelationships: function(record, hash, prematerialized) { - record.eachRelationship(function(name, relationship) { - if (relationship.kind === 'hasMany') { - if (prematerialized && prematerialized.hasOwnProperty(name)) { - record.materializeHasMany(name, prematerialized[name]); - } else { - this.materializeHasMany(name, record, hash, relationship, prematerialized); - } - } else if (relationship.kind === 'belongsTo') { - if (prematerialized && prematerialized.hasOwnProperty(name)) { - record.materializeBelongsTo(name, prematerialized[name]); - } else { - this.materializeBelongsTo(name, record, hash, relationship, prematerialized); - } - } - }, this); - }, - - materializeHasMany: function(name, record, hash, relationship) { - var key = this._keyForHasMany(record.constructor, relationship.key); - record.materializeHasMany(name, this.extractHasMany(record.constructor, hash, key)); - }, - - materializeBelongsTo: function(name, record, hash, relationship) { - var key = this._keyForBelongsTo(record.constructor, relationship.key); - record.materializeBelongsTo(name, this.extractBelongsTo(record.constructor, hash, key)); - }, - - _extractEmbeddedRelationship: function(type, hash, name, relationshipType) { - var key = this['_keyFor' + relationshipType](type, name); - - if (this.embeddedType(type, name)) { - return this['extractEmbedded' + relationshipType](type, hash, key); - } - }, - - _extractEmbeddedBelongsTo: function(type, hash, name) { - return this._extractEmbeddedRelationship(type, hash, name, 'BelongsTo'); - }, - - _extractEmbeddedHasMany: function(type, hash, name) { - return this._extractEmbeddedRelationship(type, hash, name, 'HasMany'); - }, - - /** - @private - - This method is called to get the primary key for a given - type. - - If a primary key configuration exists for this type, this - method will return the configured value. Otherwise, it will - call the public `primaryKey` hook. - - @param {DS.Model subclass} type - @returns {String} the primary key for the type - */ - _primaryKey: function(type) { - var config = this.configurationForType(type), - primaryKey = config && config.primaryKey; - - if (primaryKey) { - return primaryKey; - } else { - return this.primaryKey(type); - } - }, - - /** - @private - - This method looks up the key for the attribute name and transforms the - attribute's value using registered transforms. - - Specifically: - - 1. Look up the key for the attribute name. If available, this will use - any registered mappings. Otherwise, it will invoke the public - `keyForAttributeName` hook. - 2. Get the value from the record using the `attributeName`. - 3. Transform the value using registered transforms for the `attributeType`. - 4. Invoke the public `addAttribute` hook with the hash, key, and - transformed value. - - @param {any} data the serialized representation being built - @param {DS.Model} record the record to serialize - @param {String} attributeName the name of the attribute on the record - @param {String} attributeType the type of the attribute (e.g. `string` - or `boolean`) - */ - _addAttribute: function(data, record, attributeName, attributeType) { - var key = this._keyForAttributeName(record.constructor, attributeName); - var value = get(record, attributeName); - - this.addAttribute(data, key, this.serializeValue(value, attributeType)); - }, - - /** - @private - - This method looks up the primary key for the `type` and invokes - `serializeId` on the `id`. - - It then invokes the public `addId` hook with the primary key and - the serialized id. - - @param {any} data the serialized representation that is being built - @param {Ember.Model subclass} type - @param {any} id the materialized id from the record - */ - _addId: function(hash, type, id) { - var primaryKey = this._primaryKey(type); - - this.addId(hash, primaryKey, this.serializeId(id)); - }, - - /** - @private - - This method is called to get a key used in the data from - an attribute name. It first checks for any mappings before - calling the public hook `keyForAttributeName`. - - @param {DS.Model subclass} type the type of the record with - the attribute name `name` - @param {String} name the attribute name to convert into a key - - @returns {String} the key - */ - _keyForAttributeName: function(type, name) { - return this._keyFromMappingOrHook('keyForAttributeName', type, name); - }, - - /** - @private - - This method is called to get a key used in the data from - a belongsTo relationship. It first checks for any mappings before - calling the public hook `keyForBelongsTo`. - - @param {DS.Model subclass} type the type of the record with - the `belongsTo` relationship. - @param {String} name the relationship name to convert into a key - - @returns {String} the key - */ - _keyForBelongsTo: function(type, name) { - return this._keyFromMappingOrHook('keyForBelongsTo', type, name); - }, - - keyFor: function(description) { - var type = description.parentType, - name = description.key; - - switch (description.kind) { - case 'belongsTo': - return this._keyForBelongsTo(type, name); - case 'hasMany': - return this._keyForHasMany(type, name); - } - }, - - /** - @private - - This method is called to get a key used in the data from - a hasMany relationship. It first checks for any mappings before - calling the public hook `keyForHasMany`. - - @param {DS.Model subclass} type the type of the record with - the `hasMany` relationship. - @param {String} name the relationship name to convert into a key - - @returns {String} the key - */ - _keyForHasMany: function(type, name) { - return this._keyFromMappingOrHook('keyForHasMany', type, name); - }, - /** - @private - - This method converts the relationship name to a key for serialization, - and then invokes the public `addBelongsTo` hook. - - @param {any} data the serialized representation that is being built - @param {DS.Model} record the record to serialize - @param {String} name the relationship name - @param {Object} relationship an object representing the relationship - */ - _addBelongsTo: function(data, record, name, relationship) { - var key = this._keyForBelongsTo(record.constructor, name); - this.addBelongsTo(data, record, key, relationship); - }, - - /** - @private - - This method converts the relationship name to a key for serialization, - and then invokes the public `addHasMany` hook. - - @param {any} data the serialized representation that is being built - @param {DS.Model} record the record to serialize - @param {String} name the relationship name - @param {Object} relationship an object representing the relationship - */ - _addHasMany: function(data, record, name, relationship) { - var key = this._keyForHasMany(record.constructor, name); - this.addHasMany(data, record, key, relationship); - }, - - /** - @private - - An internal method that handles checking whether a mapping - exists for a particular attribute or relationship name before - calling the public hooks. - - If a mapping is found, and the mapping has a key defined, - use that instead of invoking the hook. - - @param {String} publicMethod the public hook to invoke if - a mapping is not found (e.g. `keyForAttributeName`) - @param {DS.Model subclass} type the type of the record with - the attribute or relationship name. - @param {String} name the attribute or relationship name to - convert into a key - */ - _keyFromMappingOrHook: function(publicMethod, type, name) { - var key = this.mappingOption(type, name, 'key'); - - if (key) { - return key; - } else { - return this[publicMethod](type, name); - } - }, - - /** - TRANSFORMS - */ - - registerTransform: function(type, transform) { - this.transforms[type] = transform; - }, - - registerEnumTransform: function(type, objects) { - var transform = { - deserialize: function(deserialized) { - return Ember.A(objects).objectAt(deserialized); - }, - serialize: function(serialized) { - return Ember.EnumerableUtils.indexOf(objects, serialized); - }, - values: objects - }; - this.registerTransform(type, transform); - }, - - /** - MAPPING CONVENIENCE - */ - - map: function(type, mappings) { - this.mappings.set(type, mappings); - }, - - configure: function(type, configuration) { - if (type && !configuration) { - Ember.merge(this.globalConfigurations, type); - return; - } - - var config = Ember.create(this.globalConfigurations); - Ember.merge(config, configuration); - - this.configurations.set(type, config); - }, - - mappingForType: function(type) { - this._reifyMappings(); - return this.mappings.get(type) || {}; - }, - - configurationForType: function(type) { - this._reifyConfigurations(); - return this.configurations.get(type) || this.globalConfigurations; - }, - - _reifyMappings: function() { - if (this._didReifyMappings) { return; } - - var mappings = this.mappings, - reifiedMappings = Ember.Map.create(); - - mappings.forEach(function(key, mapping) { - if (typeof key === 'string') { - var type = Ember.get(Ember.lookup, key); - Ember.assert("Could not find model at path " + key, type); - - reifiedMappings.set(type, mapping); - } else { - reifiedMappings.set(key, mapping); - } - }); - - this.mappings = reifiedMappings; - - this._didReifyMappings = true; - }, - - _reifyConfigurations: function() { - if (this._didReifyConfigurations) { return; } - - var configurations = this.configurations, - reifiedConfigurations = Ember.Map.create(); - - configurations.forEach(function(key, mapping) { - if (typeof key === 'string' && key !== 'plurals') { - var type = Ember.get(Ember.lookup, key); - Ember.assert("Could not find model at path " + key, type); - - reifiedConfigurations.set(type, mapping); - } else { - reifiedConfigurations.set(key, mapping); - } - }); - - this.configurations = reifiedConfigurations; - - this._didReifyConfigurations = true; - }, - - mappingOption: function(type, name, option) { - var mapping = this.mappingForType(type)[name]; - - return mapping && mapping[option]; - }, - - configOption: function(type, option) { - var config = this.configurationForType(type); - - return config[option]; - }, - - // EMBEDDED HELPERS - - embeddedType: function(type, name) { - return this.mappingOption(type, name, 'embedded'); - }, - - eachEmbeddedRecord: function(record, callback, binding) { - this.eachEmbeddedBelongsToRecord(record, callback, binding); - this.eachEmbeddedHasManyRecord(record, callback, binding); - }, - - eachEmbeddedBelongsToRecord: function(record, callback, binding) { - var type = record.constructor; - - this.eachEmbeddedBelongsTo(record.constructor, function(name, relationship, embeddedType) { - var embeddedRecord = get(record, name); - if (embeddedRecord) { callback.call(binding, embeddedRecord, embeddedType); } - }); - }, - - eachEmbeddedHasManyRecord: function(record, callback, binding) { - var type = record.constructor; - - this.eachEmbeddedHasMany(record.constructor, function(name, relationship, embeddedType) { - var array = get(record, name); - for (var i=0, l=get(array, 'length'); i types) before sideloading. - // We can't do this conversion immediately here, because `configure` - // may be called before certain types have been defined. - this.sideloadMapping.normalized = false; - - delete configuration.sideloadAs; - } - - this._super.apply(this, arguments); - }, - - addId: function(data, key, id) { - data[key] = id; - }, - - /** - A hook you can use to customize how the key/value pair is added to - the serialized data. - - @param {any} hash the JSON hash being built - @param {String} key the key to add to the serialized data - @param {any} value the value to add to the serialized data - */ - addAttribute: function(hash, key, value) { - hash[key] = value; - }, - - /** - @private - - Creates an empty hash that will be filled in by the hooks called from the - `serialize()` method. - - @return {Object} - */ - createSerializedForm: function() { - return {}; - }, - - extractAttribute: function(type, hash, attributeName) { - var key = this._keyForAttributeName(type, attributeName); - return hash[key]; - }, - - extractId: function(type, hash) { - var primaryKey = this._primaryKey(type); - - if (hash.hasOwnProperty(primaryKey)) { - // Ensure that we coerce IDs to strings so that record - // IDs remain consistent between application runs; especially - // if the ID is serialized and later deserialized from the URL, - // when type information will have been lost. - return hash[primaryKey]+''; - } else { - return null; - } - }, - - extractHasMany: function(type, hash, key) { - return hash[key]; - }, - - extractBelongsTo: function(type, hash, key) { - return hash[key]; - }, - - addBelongsTo: function(hash, record, key, relationship) { - var type = record.constructor, - name = relationship.key, - value = null, - embeddedChild; - - if (this.embeddedType(type, name)) { - if (embeddedChild = get(record, name)) { - value = this.serialize(embeddedChild, { includeId: true }); - } - - hash[key] = value; - } else { - var id = get(record, relationship.key+'.id'); - if (!Ember.isNone(id)) { hash[key] = id; } - } - }, - - /** - Adds a has-many relationship to the JSON hash being built. - - The default REST semantics are to only add a has-many relationship if it - is embedded. If the relationship was initially loaded by ID, we assume that - that was done as a performance optimization, and that changes to the - has-many should be saved as foreign key changes on the child's belongs-to - relationship. - - @param {Object} hash the JSON being built - @param {DS.Model} record the record being serialized - @param {String} key the JSON key into which the serialized relationship - should be saved - @param {Object} relationship metadata about the relationship being serialized - */ - addHasMany: function(hash, record, key, relationship) { - var type = record.constructor, - name = relationship.key, - serializedHasMany = [], - manyArray, embeddedType; - - // If the has-many is not embedded, there is nothing to do. - embeddedType = this.embeddedType(type, name); - if (embeddedType !== 'always') { return; } - - // Get the DS.ManyArray for the relationship off the record - manyArray = get(record, name); - - // Build up the array of serialized records - manyArray.forEach(function (record) { - serializedHasMany.push(this.serialize(record, { includeId: true })); - }, this); - - // Set the appropriate property of the serialized JSON to the - // array of serialized embedded records - hash[key] = serializedHasMany; - }, - - // EXTRACTION - - extract: function(loader, json, type, record) { - var root = this.rootForType(type); - - this.sideload(loader, type, json, root); - this.extractMeta(loader, type, json); - - if (json[root]) { - if (record) { loader.updateId(record, json[root]); } - this.extractRecordRepresentation(loader, type, json[root]); - } - }, - - extractMany: function(loader, json, type, records) { - var root = this.rootForType(type); - root = this.pluralize(root); - - this.sideload(loader, type, json, root); - this.extractMeta(loader, type, json); - - if (json[root]) { - var objects = json[root], references = []; - if (records) { records = records.toArray(); } - - for (var i = 0; i < objects.length; i++) { - if (records) { loader.updateId(records[i], objects[i]); } - var reference = this.extractRecordRepresentation(loader, type, objects[i]); - references.push(reference); - } - - loader.populateArray(references); - } - }, - - extractMeta: function(loader, type, json) { - var meta = json[this.configOption(type, 'meta')], since; - if (!meta) { return; } - - if (since = meta[this.configOption(type, 'since')]) { - loader.sinceForType(type, since); - } - }, - - /** - @private - - Iterates over the `json` payload and attempts to load any data - included alongside `root`. - - The keys expected for sideloaded data are based upon the types related - to the root model. Recursion is used to ensure that types related to - related types can be loaded as well. Any custom keys specified by - `sideloadAs` mappings will also be respected. - - @param {DS.Store subclass} loader - @param {DS.Model subclass} type - @param {Object} json - @param {String} root - */ - sideload: function(loader, type, json, root) { - var sideloadedType; - - this.normalizeSideloadMappings(); - this.configureSideloadMappingForType(type); - - for (var prop in json) { - if (!json.hasOwnProperty(prop) || - prop === root || - prop === this.configOption(type, 'meta')) { - continue; - } - - sideloadedType = this.sideloadMapping.get(prop); - Ember.assert("Your server returned a hash with the key " + prop + - " but you have no mapping for it", - !!sideloadedType); - - this.loadValue(loader, sideloadedType, json[prop]); - } - }, - - /** - @private - - Iterates over all the `sideloadAs` mappings and converts any that are - strings to their equivalent types. - - This is an optimization used to avoid performing lookups for every - call to `sideload`. - */ - normalizeSideloadMappings: function() { - if (! this.sideloadMapping.normalized) { - this.sideloadMapping.forEach(function(key, value) { - if (typeof value === 'string') { - this.sideloadMapping.set(key, get(Ember.lookup, value)); - } - }, this); - this.sideloadMapping.normalized = true; - } - }, - - /** - @private - - Configures possible sideload mappings for the types related to a - particular model. This recursive method ensures that sideloading - works for related models as well. - - @param {DS.Model subclass} type - @param {Ember.A} configured an array of types that have already been configured - */ - configureSideloadMappingForType: function(type, configured) { - if (!configured) {configured = Ember.A([]);} - configured.pushObject(type); - - type.eachRelatedType(function(relatedType) { - if (!configured.contains(relatedType)) { - var root = this.sideloadMappingForType(relatedType); - if (!root) { - root = this.defaultSideloadRootForType(relatedType); - this.sideloadMapping.set(root, relatedType); - } - this.configureSideloadMappingForType(relatedType, configured); - } - }, this); - }, - - loadValue: function(loader, type, value) { - if (value instanceof Array) { - for (var i=0; i < value.length; i++) { - loader.sideload(type, value[i]); - } - } else { - loader.sideload(type, value); - } - }, - - // HELPERS - - // define a plurals hash in your subclass to define - // special-case pluralization - pluralize: function(name) { - var plurals = this.configurations.get('plurals'); - return (plurals && plurals[name]) || name + "s"; - }, - - // use the same plurals hash to determine - // special-case singularization - singularize: function(name) { - var plurals = this.configurations.get('plurals'); - if (plurals) { - for (var i in plurals) { - if (plurals[i] === name) { - return i; - } - } - } - if (name.lastIndexOf('s') === name.length - 1) { - return name.substring(0, name.length - 1); - } else { - return name; - } - }, - - /** - @private - - Determines the singular root name for a particular type. - - This is an underscored, lowercase version of the model name. - For example, the type `App.UserGroup` will have the root - `user_group`. - - @param {DS.Model subclass} type - @returns {String} name of the root element - */ - rootForType: function(type) { - var typeString = type.toString(); - - Ember.assert("Your model must not be anonymous. It was " + type, typeString.charAt(0) !== '('); - - // use the last part of the name as the URL - var parts = typeString.split("."); - var name = parts[parts.length - 1]; - return name.replace(/([A-Z])/g, '_$1').toLowerCase().slice(1); - }, - - /** - @private - - Determines the root name mapped to a particular sideloaded type. - - @param {DS.Model subclass} type - @returns {String} name of the root element, if any is registered - */ - sideloadMappingForType: function(type) { - this.sideloadMapping.forEach(function(key, value) { - if (type === value) { - return key; - } - }); - }, - - /** - @private - - The default root name for a particular sideloaded type. - - @param {DS.Model subclass} type - @returns {String} name of the root element - */ - defaultSideloadRootForType: function(type) { - return this.pluralize(this.rootForType(type)); - } -}); - -})(); - - - -(function() { -function loaderFor(store) { - return { - load: function(type, data, prematerialized) { - return store.load(type, data, prematerialized); - }, - - loadMany: function(type, array) { - return store.loadMany(type, array); - }, - - updateId: function(record, data) { - return store.updateId(record, data); - }, - - populateArray: Ember.K, - - sideload: function(type, data) { - return store.load(type, data); - }, - - sideloadMany: function(type, array) { - return store.loadMany(type, array); - }, - - prematerialize: function(reference, prematerialized) { - store.prematerialize(reference, prematerialized); - }, - - sinceForType: function(type, since) { - store.sinceForType(type, since); - } - }; -} - -DS.loaderFor = loaderFor; - -/** - An adapter is an object that receives requests from a store and - translates them into the appropriate action to take against your - persistence layer. The persistence layer is usually an HTTP API, but may - be anything, such as the browser's local storage. - - ### Creating an Adapter - - First, create a new subclass of `DS.Adapter`: - - App.MyAdapter = DS.Adapter.extend({ - // ...your code here - }); - - To tell your store which adapter to use, set its `adapter` property: - - App.store = DS.Store.create({ - revision: 3, - adapter: App.MyAdapter.create() - }); - - `DS.Adapter` is an abstract base class that you should override in your - application to customize it for your backend. The minimum set of methods - that you should implement is: - - * `find()` - * `createRecord()` - * `updateRecord()` - * `deleteRecord()` - - To improve the network performance of your application, you can optimize - your adapter by overriding these lower-level methods: - - * `findMany()` - * `createRecords()` - * `updateRecords()` - * `deleteRecords()` - * `commit()` -*/ - -var get = Ember.get, set = Ember.set, merge = Ember.merge; - -DS.Adapter = Ember.Object.extend(DS._Mappable, { - - init: function() { - var serializer = get(this, 'serializer'); - - if (Ember.Object.detect(serializer)) { - serializer = serializer.create(); - set(this, 'serializer', serializer); - } - - this._attributesMap = this.createInstanceMapFor('attributes'); - this._configurationsMap = this.createInstanceMapFor('configurations'); - - this._outstandingOperations = new Ember.MapWithDefault({ - defaultValue: function() { return 0; } - }); - - this._dependencies = new Ember.MapWithDefault({ - defaultValue: function() { return new Ember.OrderedSet(); } - }); - - this.registerSerializerTransforms(this.constructor, serializer, {}); - this.registerSerializerMappings(serializer); - }, - - /** - Loads a payload for a record into the store. - - This method asks the serializer to break the payload into - constituent parts, and then loads them into the store. For example, - if you have a payload that contains embedded records, they will be - extracted by the serializer and loaded into the store. - - For example: - - ```javascript - adapter.load(store, App.Person, { - id: 123, - firstName: "Yehuda", - lastName: "Katz", - occupations: [{ - id: 345, - title: "Tricycle Mechanic" - }] - }); - ``` - - This will load the payload for the `App.Person` with ID `123` and - the embedded `App.Occupation` with ID `345`. - - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {any} payload - */ - load: function(store, type, payload) { - var loader = loaderFor(store); - get(this, 'serializer').extractRecordRepresentation(loader, type, payload); - }, - - /** - Acknowledges that the adapter has finished creating a record. - - Your adapter should call this method from `createRecord` when - it has saved a new record to its persistent storage and received - an acknowledgement. - - If the persistent storage returns a new payload in response to the - creation, and you want to update the existing record with the - new information, pass the payload as the fourth parameter. - - For example, the `RESTAdapter` saves newly created records by - making an Ajax request. When the server returns, the adapter - calls didCreateRecord. If the server returns a response body, - it is passed as the payload. - - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {DS.Model} record - @param {any} payload - */ - didCreateRecord: function(store, type, record, payload) { - store.didSaveRecord(record); - - if (payload) { - var loader = DS.loaderFor(store); - - loader.load = function(type, data, prematerialized) { - store.updateId(record, data); - return store.load(type, data, prematerialized); - }; - - get(this, 'serializer').extract(loader, payload, type); - } - }, - - /** - Acknowledges that the adapter has finished creating several records. - - Your adapter should call this method from `createRecords` when it - has saved multiple created records to its persistent storage - received an acknowledgement. - - If the persistent storage returns a new payload in response to the - creation, and you want to update the existing record with the - new information, pass the payload as the fourth parameter. - - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {DS.Model} record - @param {any} payload - */ - didCreateRecords: function(store, type, records, payload) { - records.forEach(function(record) { - store.didSaveRecord(record); - }, this); - - if (payload) { - var loader = DS.loaderFor(store); - get(this, 'serializer').extractMany(loader, payload, type, records); - } - }, - - /** - @private - - Acknowledges that the adapter has finished updating or deleting a record. - - Your adapter should call this method from `updateRecord` or `deleteRecord` - when it has updated or deleted a record to its persistent storage and - received an acknowledgement. - - If the persistent storage returns a new payload in response to the - update or delete, and you want to update the existing record with the - new information, pass the payload as the fourth parameter. - - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {DS.Model} record - @param {any} payload - */ - didSaveRecord: function(store, type, record, payload) { - store.didSaveRecord(record); - - var serializer = get(this, 'serializer'), - mappings = serializer.mappingForType(type); - - serializer.eachEmbeddedRecord(record, function(embeddedRecord, embeddedType) { - if (embeddedType === 'load') { return; } - - this.didSaveRecord(store, embeddedRecord.constructor, embeddedRecord); - }, this); - - if (payload) { - var loader = DS.loaderFor(store); - serializer.extract(loader, payload, type); - } - }, - - /** - Acknowledges that the adapter has finished updating a record. - - Your adapter should call this method from `updateRecord` when it - has updated a record to its persistent storage and received an - acknowledgement. - - If the persistent storage returns a new payload in response to the - update, pass the payload as the fourth parameter. - - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {DS.Model} record - @param {any} payload - */ - didUpdateRecord: function() { - this.didSaveRecord.apply(this, arguments); - }, - - /** - Acknowledges that the adapter has finished deleting a record. - - Your adapter should call this method from `deleteRecord` when it - has deleted a record from its persistent storage and received an - acknowledgement. - - If the persistent storage returns a new payload in response to the - deletion, pass the payload as the fourth parameter. - - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {DS.Model} record - @param {any} payload - */ - didDeleteRecord: function() { - this.didSaveRecord.apply(this, arguments); - }, - - /** - Acknowledges that the adapter has finished updating or deleting - multiple records. - - Your adapter should call this method from its `updateRecords` or - `deleteRecords` when it has updated or deleted multiple records - to its persistent storage and received an acknowledgement. - - If the persistent storage returns a new payload in response to the - creation, pass the payload as the fourth parameter. - - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {DS.Model} records - @param {any} payload - */ - didSaveRecords: function(store, type, records, payload) { - records.forEach(function(record) { - store.didSaveRecord(record); - }, this); - - if (payload) { - var loader = DS.loaderFor(store); - get(this, 'serializer').extractMany(loader, payload, type); - } - }, - - /** - Acknowledges that the adapter has finished updating multiple records. - - Your adapter should call this method from its `updateRecords` when - it has updated multiple records to its persistent storage and - received an acknowledgement. - - If the persistent storage returns a new payload in response to the - update, pass the payload as the fourth parameter. - - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {DS.Model} records - @param {any} payload - */ - didUpdateRecords: function() { - this.didSaveRecords.apply(this, arguments); - }, - - /** - Acknowledges that the adapter has finished updating multiple records. - - Your adapter should call this method from its `deleteRecords` when - it has deleted multiple records to its persistent storage and - received an acknowledgement. - - If the persistent storage returns a new payload in response to the - deletion, pass the payload as the fourth parameter. - - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {DS.Model} records - @param {any} payload - */ - didDeleteRecords: function() { - this.didSaveRecords.apply(this, arguments); - }, - - /** - Loads the response to a request for a record by ID. - - Your adapter should call this method from its `find` method - with the response from the backend. - - You should pass the same ID to this method that was given - to your find method so that the store knows which record - to associate the new data with. - - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {any} payload - @param {String} id - */ - didFindRecord: function(store, type, payload, id) { - var loader = DS.loaderFor(store); - - loader.load = function(type, data, prematerialized) { - prematerialized = prematerialized || {}; - prematerialized.id = id; - - return store.load(type, data, prematerialized); - }; - - get(this, 'serializer').extract(loader, payload, type); - }, - - /** - Loads the response to a request for all records by type. - - You adapter should call this method from its `findAll` - method with the response from the backend. - - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {any} payload - */ - didFindAll: function(store, type, payload) { - var loader = DS.loaderFor(store), - serializer = get(this, 'serializer'); - - store.didUpdateAll(type); - - serializer.extractMany(loader, payload, type); - }, - - /** - Loads the response to a request for records by query. - - Your adapter should call this method from its `findQuery` - method with the response from the backend. - - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {any} payload - @param {DS.AdapterPopulatedRecordArray} recordArray - */ - didFindQuery: function(store, type, payload, recordArray) { - var loader = DS.loaderFor(store); - - loader.populateArray = function(data) { - recordArray.load(data); - }; - - get(this, 'serializer').extractMany(loader, payload, type); - }, - - /** - Loads the response to a request for many records by ID. - - You adapter should call this method from its `findMany` - method with the response from the backend. - - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {any} payload - */ - didFindMany: function(store, type, payload) { - var loader = DS.loaderFor(store); - - get(this, 'serializer').extractMany(loader, payload, type); - }, - - /** - Notifies the store that a request to the backend returned - an error. - - Your adapter should call this method to indicate that the - backend returned an error for a request. - - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {DS.Model} record - */ - didError: function(store, type, record) { - store.recordWasError(record); - }, - - dirtyRecordsForAttributeChange: function(dirtySet, record, attributeName, newValue, oldValue) { - if (newValue !== oldValue) { - // If this record is embedded, add its parent - // to the dirty set. - this.dirtyRecordsForRecordChange(dirtySet, record); - } - }, - - dirtyRecordsForRecordChange: function(dirtySet, record) { - dirtySet.add(record); - }, - - dirtyRecordsForBelongsToChange: function(dirtySet, child) { - this.dirtyRecordsForRecordChange(dirtySet, child); - }, - - dirtyRecordsForHasManyChange: function(dirtySet, parent) { - this.dirtyRecordsForRecordChange(dirtySet, parent); - }, - - /** - @private - - This method recursively climbs the superclass hierarchy and - registers any class-registered transforms on the adapter's - serializer. - - Once it registers a transform for a given type, it ignores - subsequent transforms for the same attribute type. - - @param {Class} klass the DS.Adapter subclass to extract the - transforms from - @param {DS.Serializer} serializer the serializer to register - the transforms onto - @param {Object} seen a hash of attributes already seen - */ - registerSerializerTransforms: function(klass, serializer, seen) { - var transforms = klass._registeredTransforms, superclass, prop; - - for (prop in transforms) { - if (!transforms.hasOwnProperty(prop) || prop in seen) { continue; } - seen[prop] = true; - - serializer.registerTransform(prop, transforms[prop]); - } - - if (superclass = klass.superclass) { - this.registerSerializerTransforms(superclass, serializer, seen); - } - }, - - /** - @private - - This method recursively climbs the superclass hierarchy and - registers any class-registered mappings on the adapter's - serializer. - - @param {Class} klass the DS.Adapter subclass to extract the - transforms from - @param {DS.Serializer} serializer the serializer to register the - mappings onto - */ - registerSerializerMappings: function(serializer) { - var mappings = this._attributesMap, - configurations = this._configurationsMap; - - mappings.forEach(serializer.map, serializer); - configurations.forEach(serializer.configure, serializer); - }, - - /** - The `find()` method is invoked when the store is asked for a record that - has not previously been loaded. In response to `find()` being called, you - should query your persistence layer for a record with the given ID. Once - found, you can asynchronously call the store's `load()` method to load - the record. - - Here is an example `find` implementation: - - find: function(store, type, id) { - var url = type.url; - url = url.fmt(id); - - jQuery.getJSON(url, function(data) { - // data is a hash of key/value pairs. If your server returns a - // root, simply do something like: - // store.load(type, id, data.person) - store.load(type, id, data); - }); - } - */ - find: null, - - serializer: DS.JSONSerializer, - - registerTransform: function(attributeType, transform) { - get(this, 'serializer').registerTransform(attributeType, transform); - }, - - /** - A public method that allows you to register an enumerated - type on your adapter. This is useful if you want to utilize - a text representation of an integer value. - - Eg: Say you want to utilize "low","medium","high" text strings - in your app, but you want to persist those as 0,1,2 in your backend. - You would first register the transform on your adapter instance: - - adapter.registerEnumTransform('priority', ['low', 'medium', 'high']); - - You would then refer to the 'priority' DS.attr in your model: - App.Task = DS.Model.extend({ - priority: DS.attr('priority') - }); - - And lastly, you would set/get the text representation on your model instance, - but the transformed result will be the index number of the type. - - App: myTask.get('priority') => 'low' - Server Response / Load: { myTask: {priority: 0} } - - @param {String} type of the transform - @param {Array} array of String objects to use for the enumerated values. - This is an ordered list and the index values will be used for the transform. - */ - registerEnumTransform: function(attributeType, objects) { - get(this, 'serializer').registerEnumTransform(attributeType, objects); - }, - - /** - If the globally unique IDs for your records should be generated on the client, - implement the `generateIdForRecord()` method. This method will be invoked - each time you create a new record, and the value returned from it will be - assigned to the record's `primaryKey`. - - Most traditional REST-like HTTP APIs will not use this method. Instead, the ID - of the record will be set by the server, and your adapter will update the store - with the new ID when it calls `didCreateRecord()`. Only implement this method if - you intend to generate record IDs on the client-side. - - The `generateIdForRecord()` method will be invoked with the requesting store as - the first parameter and the newly created record as the second parameter: - - generateIdForRecord: function(store, record) { - var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision(); - return uuid; - } - */ - generateIdForRecord: null, - - materialize: function(record, data, prematerialized) { - get(this, 'serializer').materialize(record, data, prematerialized); - }, - - serialize: function(record, options) { - return get(this, 'serializer').serialize(record, options); - }, - - extractId: function(type, data) { - return get(this, 'serializer').extractId(type, data); - }, - - groupByType: function(enumerable) { - var map = Ember.MapWithDefault.create({ - defaultValue: function() { return Ember.OrderedSet.create(); } - }); - - enumerable.forEach(function(item) { - map.get(item.constructor).add(item); - }); - - return map; - }, - - commit: function(store, commitDetails) { - this.save(store, commitDetails); - }, - - save: function(store, commitDetails) { - var adapter = this; - - function filter(records) { - var filteredSet = Ember.OrderedSet.create(); - - records.forEach(function(record) { - if (adapter.shouldSave(record)) { - filteredSet.add(record); - } - }); - - return filteredSet; - } - - this.groupByType(commitDetails.created).forEach(function(type, set) { - this.createRecords(store, type, filter(set)); - }, this); - - this.groupByType(commitDetails.updated).forEach(function(type, set) { - this.updateRecords(store, type, filter(set)); - }, this); - - this.groupByType(commitDetails.deleted).forEach(function(type, set) { - this.deleteRecords(store, type, filter(set)); - }, this); - }, - - shouldSave: Ember.K, - - createRecords: function(store, type, records) { - records.forEach(function(record) { - this.createRecord(store, type, record); - }, this); - }, - - updateRecords: function(store, type, records) { - records.forEach(function(record) { - this.updateRecord(store, type, record); - }, this); - }, - - deleteRecords: function(store, type, records) { - records.forEach(function(record) { - this.deleteRecord(store, type, record); - }, this); - }, - - findMany: function(store, type, ids) { - ids.forEach(function(id) { - this.find(store, type, id); - }, this); - } -}); - -DS.Adapter.reopenClass({ - registerTransform: function(attributeType, transform) { - var registeredTransforms = this._registeredTransforms || {}; - - registeredTransforms[attributeType] = transform; - - this._registeredTransforms = registeredTransforms; - }, - - map: DS._Mappable.generateMapFunctionFor('attributes', function(key, newValue, map) { - var existingValue = map.get(key); - - merge(existingValue, newValue); - }), - - configure: DS._Mappable.generateMapFunctionFor('configurations', function(key, newValue, map) { - var existingValue = map.get(key); - - // If a mapping configuration is provided, peel it off and apply it - // using the DS.Adapter.map API. - var mappings = newValue && newValue.mappings; - if (mappings) { - this.map(key, mappings); - delete newValue.mappings; - } - - merge(existingValue, newValue); - }), - - resolveMapConflict: function(oldValue, newValue, mappingsKey) { - merge(newValue, oldValue); - - return newValue; - } -}); - -})(); - - - -(function() { -var get = Ember.get, set = Ember.set; - -DS.FixtureSerializer = DS.Serializer.extend({ - deserializeValue: function(value, attributeType) { - return value; - }, - - serializeValue: function(value, attributeType) { - return value; - }, - - addId: function(data, key, id) { - data[key] = id; - }, - - addAttribute: function(hash, key, value) { - hash[key] = value; - }, - - addBelongsTo: function(hash, record, key, relationship) { - var id = get(record, relationship.key+'.id'); - if (!Ember.isNone(id)) { hash[key] = id; } - }, - - addHasMany: function(hash, record, key, relationship) { - var ids = get(record, relationship.key).map(function(item) { - return item.get('id'); - }); - - hash[relationship.key] = ids; - }, - - /** - @private - - Creates an empty hash that will be filled in by the hooks called from the - `serialize()` method. - - @return {Object} - */ - createSerializedForm: function() { - return {}; - }, - - extract: function(loader, fixture, type, record) { - if (record) { loader.updateId(record, fixture); } - this.extractRecordRepresentation(loader, type, fixture); - }, - - extractMany: function(loader, fixtures, type, records) { - var objects = fixtures, references = []; - if (records) { records = records.toArray(); } - - for (var i = 0; i < objects.length; i++) { - if (records) { loader.updateId(records[i], objects[i]); } - var reference = this.extractRecordRepresentation(loader, type, objects[i]); - references.push(reference); - } - - loader.populateArray(references); - }, - - extractId: function(type, hash) { - var primaryKey = this._primaryKey(type); - - if (hash.hasOwnProperty(primaryKey)) { - // Ensure that we coerce IDs to strings so that record - // IDs remain consistent between application runs; especially - // if the ID is serialized and later deserialized from the URL, - // when type information will have been lost. - return hash[primaryKey]+''; - } else { - return null; - } - }, - - extractAttribute: function(type, hash, attributeName) { - var key = this._keyForAttributeName(type, attributeName); - return hash[key]; - }, - - extractHasMany: function(type, hash, key) { - return hash[key]; - }, - - extractBelongsTo: function(type, hash, key) { - return hash[key]; - } -}); - -})(); - - - -(function() { -var get = Ember.get, fmt = Ember.String.fmt; - -/** - `DS.FixtureAdapter` is an adapter that loads records from memory. - Its primarily used for development and testing. You can also use - `DS.FixtureAdapter` while working on the API but are not ready to - integrate yet. It is a fully functioning adapter. All CRUD methods - are implemented. You can also implement query logic that a remote - system would do. Its possible to do develop your entire application - with `DS.FixtureAdapter`. - -*/ -DS.FixtureAdapter = DS.Adapter.extend({ - - simulateRemoteResponse: true, - - latency: 50, - - serializer: DS.FixtureSerializer, - - /* - Implement this method in order to provide data associated with a type - */ - fixturesForType: function(type) { - if (type.FIXTURES) { - var fixtures = Ember.A(type.FIXTURES); - return fixtures.map(function(fixture){ - if(!fixture.id){ - throw new Error(fmt('the id property must be defined for fixture %@', [fixture])); - } - fixture.id = fixture.id + ''; - return fixture; - }); - } - return null; - }, - - /* - Implement this method in order to query fixtures data - */ - queryFixtures: function(fixtures, query, type) { - Ember.assert('Not implemented: You must override the DS.FixtureAdapter::queryFixtures method to support querying the fixture store.'); - }, - - updateFixtures: function(type, fixture) { - if(!type.FIXTURES) { - type.FIXTURES = []; - } - - var fixtures = type.FIXTURES; - - this.deleteLoadedFixture(type, fixture); - - fixtures.push(fixture); - }, - - /* - Implement this method in order to provide provide json for CRUD methods - */ - mockJSON: function(type, record) { - return this.serialize(record, { includeId: true }); - }, - - /* - Adapter methods - */ - generateIdForRecord: function(store, record) { - return Ember.guidFor(record); - }, - - find: function(store, type, id) { - var fixtures = this.fixturesForType(type), - fixture; - - Ember.warn("Unable to find fixtures for model type " + type.toString(), fixtures); - - if (fixtures) { - fixture = Ember.A(fixtures).findProperty('id', id); - } - - if (fixture) { - this.simulateRemoteCall(function() { - this.didFindRecord(store, type, fixture, id); - }, this); - } - }, - - findMany: function(store, type, ids) { - var fixtures = this.fixturesForType(type); - - Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures); - - if (fixtures) { - fixtures = fixtures.filter(function(item) { - return ids.indexOf(item.id) !== -1; - }); - } - - if (fixtures) { - this.simulateRemoteCall(function() { - this.didFindMany(store, type, fixtures); - }, this); - } - }, - - findAll: function(store, type) { - var fixtures = this.fixturesForType(type); - - Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures); - - this.simulateRemoteCall(function() { - this.didFindAll(store, type, fixtures); - }, this); - }, - - findQuery: function(store, type, query, array) { - var fixtures = this.fixturesForType(type); - - Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures); - - fixtures = this.queryFixtures(fixtures, query, type); - - if (fixtures) { - this.simulateRemoteCall(function() { - this.didFindQuery(store, type, fixtures, array); - }, this); - } - }, - - createRecord: function(store, type, record) { - var fixture = this.mockJSON(type, record); - - this.updateFixtures(type, fixture); - - this.simulateRemoteCall(function() { - this.didCreateRecord(store, type, record, fixture); - }, this); - }, - - updateRecord: function(store, type, record) { - var fixture = this.mockJSON(type, record); - - this.updateFixtures(type, fixture); - - this.simulateRemoteCall(function() { - this.didUpdateRecord(store, type, record, fixture); - }, this); - }, - - deleteRecord: function(store, type, record) { - var fixture = this.mockJSON(type, record); - - this.deleteLoadedFixture(type, fixture); - - this.simulateRemoteCall(function() { - this.didDeleteRecord(store, type, record); - }, this); - }, - - /* - @private - */ - deleteLoadedFixture: function(type, record) { - var id = this.extractId(type, record); - - var existingFixture = this.findExistingFixture(type, record); - - if(existingFixture) { - var index = type.FIXTURES.indexOf(existingFixture); - type.FIXTURES.splice(index, 1); - return true; - } - }, - - findExistingFixture: function(type, record) { - var fixtures = this.fixturesForType(type); - var id = this.extractId(type, record); - - return this.findFixtureById(fixtures, id); - }, - - findFixtureById: function(fixtures, id) { - var adapter = this; - - return Ember.A(fixtures).find(function(r) { - if(''+get(r, 'id') === ''+id) { - return true; - } else { - return false; - } - }); - }, - - simulateRemoteCall: function(callback, context) { - if (get(this, 'simulateRemoteResponse')) { - // Schedule with setTimeout - Ember.run.later(context, callback, get(this, 'latency')); - } else { - // Asynchronous, but at the of the runloop with zero latency - Ember.run.once(context, callback); - } - } -}); - -})(); - - - -(function() { -DS.RESTSerializer = DS.JSONSerializer.extend({ - keyForAttributeName: function(type, name) { - return Ember.String.decamelize(name); - }, - - keyForBelongsTo: function(type, name) { - var key = this.keyForAttributeName(type, name); - - if (this.embeddedType(type, name)) { - return key; - } - - return key + "_id"; - }, - - keyForHasMany: function(type, name) { - var key = this.keyForAttributeName(type, name); - - if (this.embeddedType(type, name)) { - return key; - } - - return this.singularize(key) + "_ids"; - } -}); - -})(); - - - -(function() { -/*global jQuery*/ - -var get = Ember.get, set = Ember.set, merge = Ember.merge; - -/** - The REST adapter allows your store to communicate with an HTTP server by - transmitting JSON via XHR. Most Ember.js apps that consume a JSON API - should use the REST adapter. - - This adapter is designed around the idea that the JSON exchanged with - the server should be conventional. - - ## JSON Structure - - The REST adapter expects the JSON returned from your server to follow - these conventions. - - ### Object Root - - The JSON payload should be an object that contains the record inside a - root property. For example, in response to a `GET` request for - `/posts/1`, the JSON should look like this: - - ```js - { - "post": { - title: "I'm Running to Reform the W3C's Tag", - author: "Yehuda Katz" - } - } - ``` - - ### Conventional Names - - Attribute names in your JSON payload should be the underscored versions of - the attributes in your Ember.js models. - - For example, if you have a `Person` model: - - ```js - App.Person = DS.Model.extend({ - firstName: DS.attr('string'), - lastName: DS.attr('string'), - occupation: DS.attr('string') - }); - ``` - - The JSON returned should look like this: - - ```js - { - "person": { - "first_name": "Barack", - "last_name": "Obama", - "occupation": "President" - } - } - ``` -*/ -DS.RESTAdapter = DS.Adapter.extend({ - bulkCommit: false, - since: 'since', - - serializer: DS.RESTSerializer, - - init: function() { - this._super.apply(this, arguments); - }, - - shouldSave: function(record) { - var reference = get(record, '_reference'); - - return !reference.parent; - }, - - createRecord: function(store, type, record) { - var root = this.rootForType(type); - - var data = {}; - data[root] = this.serialize(record, { includeId: true }); - - this.ajax(this.buildURL(root), "POST", { - data: data, - context: this, - success: function(json) { - Ember.run(this, function(){ - this.didCreateRecord(store, type, record, json); - }); - }, - error: function(xhr) { - this.didError(store, type, record, xhr); - } - }); - }, - - dirtyRecordsForRecordChange: function(dirtySet, record) { - this._dirtyTree(dirtySet, record); - }, - - dirtyRecordsForHasManyChange: function(dirtySet, record, relationship) { - var embeddedType = get(this, 'serializer').embeddedType(record.constructor, relationship.secondRecordName); - - if (embeddedType === 'always') { - relationship.childReference.parent = relationship.parentReference; - this._dirtyTree(dirtySet, record); - } - }, - - _dirtyTree: function(dirtySet, record) { - dirtySet.add(record); - - get(this, 'serializer').eachEmbeddedRecord(record, function(embeddedRecord, embeddedType) { - if (embeddedType !== 'always') { return; } - if (dirtySet.has(embeddedRecord)) { return; } - this._dirtyTree(dirtySet, embeddedRecord); - }, this); - - var reference = record.get('_reference'); - - if (reference.parent) { - var store = get(record, 'store'); - var parent = store.recordForReference(reference.parent); - this._dirtyTree(dirtySet, parent); - } - }, - - createRecords: function(store, type, records) { - if (get(this, 'bulkCommit') === false) { - return this._super(store, type, records); - } - - var root = this.rootForType(type), - plural = this.pluralize(root); - - var data = {}; - data[plural] = []; - records.forEach(function(record) { - data[plural].push(this.serialize(record, { includeId: true })); - }, this); - - this.ajax(this.buildURL(root), "POST", { - data: data, - context: this, - success: function(json) { - Ember.run(this, function(){ - this.didCreateRecords(store, type, records, json); - }); - } - }); - }, - - updateRecord: function(store, type, record) { - var id = get(record, 'id'); - var root = this.rootForType(type); - - var data = {}; - data[root] = this.serialize(record); - - this.ajax(this.buildURL(root, id), "PUT", { - data: data, - context: this, - success: function(json) { - Ember.run(this, function(){ - this.didSaveRecord(store, type, record, json); - }); - }, - error: function(xhr) { - this.didError(store, type, record, xhr); - } - }); - }, - - updateRecords: function(store, type, records) { - if (get(this, 'bulkCommit') === false) { - return this._super(store, type, records); - } - - var root = this.rootForType(type), - plural = this.pluralize(root); - - var data = {}; - data[plural] = []; - records.forEach(function(record) { - data[plural].push(this.serialize(record, { includeId: true })); - }, this); - - this.ajax(this.buildURL(root, "bulk"), "PUT", { - data: data, - context: this, - success: function(json) { - Ember.run(this, function(){ - this.didSaveRecords(store, type, records, json); - }); - } - }); - }, - - deleteRecord: function(store, type, record) { - var id = get(record, 'id'); - var root = this.rootForType(type); - - this.ajax(this.buildURL(root, id), "DELETE", { - context: this, - success: function(json) { - Ember.run(this, function(){ - this.didSaveRecord(store, type, record, json); - }); - } - }); - }, - - deleteRecords: function(store, type, records) { - if (get(this, 'bulkCommit') === false) { - return this._super(store, type, records); - } - - var root = this.rootForType(type), - plural = this.pluralize(root), - serializer = get(this, 'serializer'); - - var data = {}; - data[plural] = []; - records.forEach(function(record) { - data[plural].push(serializer.serializeId( get(record, 'id') )); - }); - - this.ajax(this.buildURL(root, 'bulk'), "DELETE", { - data: data, - context: this, - success: function(json) { - Ember.run(this, function(){ - this.didSaveRecords(store, type, records, json); - }); - } - }); - }, - - find: function(store, type, id) { - var root = this.rootForType(type); - - this.ajax(this.buildURL(root, id), "GET", { - success: function(json) { - Ember.run(this, function(){ - this.didFindRecord(store, type, json, id); - }); - } - }); - }, - - findAll: function(store, type, since) { - var root = this.rootForType(type); - - this.ajax(this.buildURL(root), "GET", { - data: this.sinceQuery(since), - success: function(json) { - Ember.run(this, function(){ - this.didFindAll(store, type, json); - }); - } - }); - }, - - findQuery: function(store, type, query, recordArray) { - var root = this.rootForType(type); - - this.ajax(this.buildURL(root), "GET", { - data: query, - success: function(json) { - Ember.run(this, function(){ - this.didFindQuery(store, type, json, recordArray); - }); - } - }); - }, - - findMany: function(store, type, ids, owner) { - var root = this.rootForType(type); - ids = this.serializeIds(ids); - - this.ajax(this.buildURL(root), "GET", { - data: {ids: ids}, - success: function(json) { - Ember.run(this, function(){ - this.didFindMany(store, type, json); - }); - } - }); - }, - - /** - @private - - This method serializes a list of IDs using `serializeId` - - @returns {Array} an array of serialized IDs - */ - serializeIds: function(ids) { - var serializer = get(this, 'serializer'); - - return Ember.EnumerableUtils.map(ids, function(id) { - return serializer.serializeId(id); - }); - }, - - didError: function(store, type, record, xhr) { - if (xhr.status === 422) { - var data = JSON.parse(xhr.responseText); - store.recordWasInvalid(record, data['errors']); - } else { - this._super.apply(this, arguments); - } - }, - - ajax: function(url, type, hash) { - hash.url = url; - hash.type = type; - hash.dataType = 'json'; - hash.contentType = 'application/json; charset=utf-8'; - hash.context = this; - - if (hash.data && type !== 'GET') { - hash.data = JSON.stringify(hash.data); - } - - jQuery.ajax(hash); - }, - - url: "", - - rootForType: function(type) { - var serializer = get(this, 'serializer'); - return serializer.rootForType(type); - }, - - pluralize: function(string) { - var serializer = get(this, 'serializer'); - return serializer.pluralize(string); - }, - - buildURL: function(record, suffix) { - var url = [this.url]; - - Ember.assert("Namespace URL (" + this.namespace + ") must not start with slash", !this.namespace || this.namespace.toString().charAt(0) !== "/"); - Ember.assert("Record URL (" + record + ") must not start with slash", !record || record.toString().charAt(0) !== "/"); - Ember.assert("URL suffix (" + suffix + ") must not start with slash", !suffix || suffix.toString().charAt(0) !== "/"); - - if (this.namespace !== undefined) { - url.push(this.namespace); - } - - url.push(this.pluralize(record)); - if (suffix !== undefined) { - url.push(suffix); - } - - return url.join("/"); - }, - - sinceQuery: function(since) { - var query = {}; - query[get(this, 'since')] = since; - return since ? query : null; - } -}); - - -})(); - - - -(function() { -var camelize = Ember.String.camelize, - get = Ember.get, - registeredTransforms; - -var passthruTransform = { - serialize: function(value) { return value; }, - deserialize: function(value) { return value; } -}; - -var defaultTransforms = { - string: passthruTransform, - boolean: passthruTransform, - number: passthruTransform -}; - -function camelizeKeys(json) { - var value; - - for (var prop in json) { - value = json[prop]; - delete json[prop]; - json[camelize(prop)] = value; - } -} - -function munge(json, callback) { - callback(json); -} - -function applyTransforms(json, type, transformType) { - var transforms = registeredTransforms[transformType]; - - Ember.assert("You are trying to apply the '" + transformType + "' transforms, but you didn't register any transforms with that name", transforms); - - get(type, 'attributes').forEach(function(name, attribute) { - var attributeType = attribute.type, - value = json[name]; - - var transform = transforms[attributeType] || defaultTransforms[attributeType]; - - Ember.assert("Your model specified the '" + attributeType + "' type for the '" + name + "' attribute, but no transform for that type was registered", transform); - - json[name] = transform.deserialize(value); - }); -} - -function ObjectProcessor(json, type, store) { - this.json = json; - this.type = type; - this.store = store; -} - -ObjectProcessor.prototype = { - load: function() { - this.store.load(this.type, {}, this.json); - }, - - camelizeKeys: function() { - camelizeKeys(this.json); - return this; - }, - - munge: function(callback) { - munge(this.json, callback); - return this; - }, - - applyTransforms: function(transformType) { - applyTransforms(this.json, this.type, transformType); - return this; - } -}; - -function processorFactory(store, type) { - return function(json) { - return new ObjectProcessor(json, type, store); - }; -} - -function ArrayProcessor(json, type, array, store) { - this.json = json; - this.type = type; - this.array = array; - this.store = store; -} - -ArrayProcessor.prototype = { - load: function() { - var store = this.store, - type = this.type; - - var references = this.json.map(function(object) { - return store.load(type, {}, object); - }); - - this.array.load(references); - }, - - camelizeKeys: function() { - this.json.forEach(camelizeKeys); - return this; - }, - - munge: function(callback) { - this.json.forEach(function(object) { - munge(object, callback); - }); - return this; - }, - - applyTransforms: function(transformType) { - var type = this.type; - - this.json.forEach(function(object) { - applyTransforms(object, type, transformType); - }); - - return this; - } -}; - -function arrayProcessorFactory(store, type, array) { - return function(json) { - return new ArrayProcessor(json, type, array, store); - }; -} - -DS.BasicAdapter = DS.Adapter.extend({ - find: function(store, type, id) { - var sync = type.sync; - - Ember.assert("You are trying to use the BasicAdapter to find id '" + id + "' of " + type + " but " + type + ".sync was not found", sync); - Ember.assert("The sync code on " + type + " does not implement find(), but you are trying to find id '" + id + "'.", sync.find); - - sync.find(id, processorFactory(store, type)); - }, - - findQuery: function(store, type, query, recordArray) { - var sync = type.sync; - - Ember.assert("You are trying to use the BasicAdapter to query " + type + " but " + type + ".sync was not found", sync); - Ember.assert("The sync code on " + type + " does not implement query(), but you are trying to query " + type + ".", sync.query); - - sync.query(query, arrayProcessorFactory(store, type, recordArray)); - } -}); - -DS.registerTransforms = function(kind, object) { - registeredTransforms[kind] = object; -}; - -DS.clearTransforms = function() { - registeredTransforms = {}; -}; - -DS.clearTransforms(); - -})(); - - - -(function() { - -})(); - - - -(function() { -//Copyright (C) 2011 by Living Social, Inc. - -//Permission is hereby granted, free of charge, to any person obtaining a copy of -//this software and associated documentation files (the "Software"), to deal in -//the Software without restriction, including without limitation the rights to -//use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -//of the Software, and to permit persons to whom the Software is furnished to do -//so, subject to the following conditions: - -//The above copyright notice and this permission notice shall be included in all -//copies or substantial portions of the Software. - -//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -//SOFTWARE. - -})(); - diff --git a/assets/scripts/vendor/ember-model.js b/assets/scripts/vendor/ember-model.js new file mode 100644 index 00000000..4bdef9c5 --- /dev/null +++ b/assets/scripts/vendor/ember-model.js @@ -0,0 +1,1259 @@ +(function() { + +Ember.Adapter = Ember.Object.extend({ + find: function(record, id) { + throw new Error('Ember.Adapter subclasses must implement find'); + }, + + findQuery: function(klass, records, params) { + throw new Error('Ember.Adapter subclasses must implement findQuery'); + }, + + findMany: function(klass, records, ids) { + throw new Error('Ember.Adapter subclasses must implement findMany'); + }, + + findAll: function(klass, records) { + throw new Error('Ember.Adapter subclasses must implement findAll'); + }, + + load: function(record, id, data) { + record.load(id, data); + }, + + createRecord: function(record) { + throw new Error('Ember.Adapter subclasses must implement createRecord'); + }, + + saveRecord: function(record) { + throw new Error('Ember.Adapter subclasses must implement saveRecord'); + }, + + deleteRecord: function(record) { + throw new Error('Ember.Adapter subclasses must implement deleteRecord'); + } +}); + +})(); + +(function() { + +var get = Ember.get; + +Ember.FixtureAdapter = Ember.Adapter.extend({ + _findData: function(klass, id) { + var fixtures = klass.FIXTURES, + primaryKey = get(klass, 'primaryKey'), + data = Ember.A(fixtures).find(function(el) { return el[primaryKey] === id; }); + + return data; + }, + + find: function(record, id) { + var data = this._findData(record.constructor, id); + + return new Ember.RSVP.Promise(function(resolve, reject) { + setTimeout(function() { + Ember.run(record, record.load, id, data); + resolve(record); + }); + }); + }, + + findMany: function(klass, records, ids) { + var fixtures = klass.FIXTURES, + requestedData = []; + + for (var i = 0, l = ids.length; i < l; i++) { + requestedData.push(this._findData(klass, ids[i])); + } + + return new Ember.RSVP.Promise(function(resolve, reject) { + setTimeout(function() { + Ember.run(records, records.load, klass, requestedData); + resolve(records); + }); + }); + }, + + findAll: function(klass, records) { + var fixtures = klass.FIXTURES; + + return new Ember.RSVP.Promise(function(resolve, reject) { + setTimeout(function() { + Ember.run(records, records.load, klass, fixtures); + resolve(records); + }); + }); + }, + + createRecord: function(record) { + var klass = record.constructor, + fixtures = klass.FIXTURES; + + return new Ember.RSVP.Promise(function(resolve, reject) { + setTimeout(function() { + fixtures.push(klass.findFromCacheOrLoad(record.toJSON())); + record.didCreateRecord(); + resolve(record); + }); + }); + }, + + saveRecord: function(record) { + return new Ember.RSVP.Promise(function(resolve, reject) { + setTimeout(function() { + record.didSaveRecord(); + resolve(record); + }); + }); + }, + + deleteRecord: function(record) { + return new Ember.RSVP.Promise(function(resolve, reject) { + setTimeout(function() { + record.didDeleteRecord(); + resolve(record); + }); + }); + } +}); + + +})(); + +(function() { + +var get = Ember.get, + set = Ember.set; + +Ember.RecordArray = Ember.ArrayProxy.extend(Ember.Evented, { + isLoaded: false, + isLoading: Ember.computed.not('isLoaded'), + + load: function(klass, data) { + set(this, 'content', this.materializeData(klass, data)); + this.notifyLoaded(); + }, + + loadForFindMany: function(klass) { + var content = get(this, '_ids').map(function(id) { return klass.cachedRecordForId(id); }); + set(this, 'content', Ember.A(content)); + this.notifyLoaded(); + }, + + notifyLoaded: function() { + set(this, 'isLoaded', true); + this.trigger('didLoad'); + }, + + materializeData: function(klass, data) { + return Ember.A(data.map(function(el) { + return klass.findFromCacheOrLoad(el); // FIXME + })); + } +}); + + +})(); + +(function() { + +var get = Ember.get; + +Ember.FilteredRecordArray = Ember.RecordArray.extend({ + init: function() { + if (!get(this, 'modelClass')) { + throw new Error('FilteredRecordArrays must be created with a modelClass'); + } + if (!get(this, 'filterFunction')) { + throw new Error('FilteredRecordArrays must be created with a filterFunction'); + } + if (!get(this, 'filterProperties')) { + throw new Error('FilteredRecordArrays must be created with filterProperties'); + } + + var modelClass = get(this, 'modelClass'); + modelClass.registerRecordArray(this); + + this.registerObservers(); + this.updateFilter(); + }, + + updateFilter: function() { + var self = this, + results = []; + get(this, 'modelClass').forEachCachedRecord(function(record) { + if (self.filterFunction(record)) { + results.push(record); + } + }); + this.set('content', Ember.A(results)); + }, + + updateFilterForRecord: function(record) { + var results = get(this, 'content'); + if (this.filterFunction(record)) { + results.pushObject(record); + } + }, + + registerObservers: function() { + var self = this; + get(this, 'modelClass').forEachCachedRecord(function(record) { + self.registerObserversOnRecord(record); + }); + }, + + registerObserversOnRecord: function(record) { + var self = this, + filterProperties = get(this, 'filterProperties'); + + for (var i = 0, l = get(filterProperties, 'length'); i < l; i++) { + record.addObserver(filterProperties[i], self, 'updateFilterForRecord'); + } + } +}); + +})(); + +(function() { + +var get = Ember.get; + +Ember.ManyArray = Ember.RecordArray.extend({ + _records: null, + + objectAtContent: function(idx) { + var content = get(this, 'content'); + + if (!content.length) { return; } + + // TODO: Create a LazilyMaterializedRecordArray class and test it + if (this._records && this._records[idx]) { return this._records[idx]; } + + var record = this.materializeRecord(idx); + + if (!this._records) { this._records = {}; } + this._records[idx] = record; + + return record; + }, + + save: function() { + // TODO: loop over dirty records only + return Ember.RSVP.all(this.map(function(record) { + return record.save(); + })); + }, + + replaceContent: function(index, removed, added) { + added = Ember.EnumerableUtils.map(added, function(record) { + return record._reference; + }, this); + + this._super(index, removed, added); + } +}); + +Ember.HasManyArray = Ember.ManyArray.extend({ + materializeRecord: function(idx) { + var klass = get(this, 'modelClass'), + content = get(this, 'content'), + reference = content.objectAt(idx), + record; + + if (reference.record) { + record = reference.record; + } else { + record = klass.findById(reference.id); + } + + return record; + }, + + toJSON: function() { + var ids = [], content = this.get('content'); + + content.forEach(function(reference) { + if (reference.id) { + ids.push(reference.id); + } + }); + + return ids; + } +}); + +Ember.EmbeddedHasManyArray = Ember.ManyArray.extend({ + create: function(attrs) { + var klass = get(this, 'modelClass'), + record = klass.create(attrs); + + this.pushObject(record); + + return record; // FIXME: inject parent's id + }, + + materializeRecord: function(idx) { + var klass = get(this, 'modelClass'), + primaryKey = get(klass, 'primaryKey'), + content = get(this, 'content'), + reference = content.objectAt(idx), + attrs = reference.data; + + if (reference.record) { + return reference.record; + } else { + var record = klass.create({ _reference: reference }); + if(attrs) { + record.load(attrs[primaryKey], attrs); + } + return record; + } + }, + + toJSON: function() { + return this.map(function(record) { + return record.toJSON(); + }); + } +}); + + +})(); + +(function() { + +var get = Ember.get, + set = Ember.set, + setProperties = Ember.setProperties, + meta = Ember.meta, + underscore = Ember.String.underscore; + +function contains(array, element) { + for (var i = 0, l = array.length; i < l; i++) { + if (array[i] === element) { return true; } + } + return false; +} + +function concatUnique(toArray, fromArray) { + var e; + for (var i = 0, l = fromArray.length; i < l; i++) { + e = fromArray[i]; + if (!contains(toArray, e)) { toArray.push(e); } + } + return toArray; +} + +function hasCachedValue(object, key) { + var objectMeta = meta(object, false); + if (objectMeta) { + return key in objectMeta.cache; + } +} + +Ember.run.queues.push('data'); + +Ember.Model = Ember.Object.extend(Ember.Evented, { + isLoaded: true, + isLoading: Ember.computed.not('isLoaded'), + isNew: true, + isDeleted: false, + _dirtyAttributes: null, + + /** + Called when attribute is accessed. + + @method getAttr + @param key {String} key which is being accessed + @param value {Object} value, which will be returned from getter by default + */ + getAttr: function(key, value) { + return value; + }, + + isDirty: Ember.computed(function() { + var attributes = this.attributes, + dirtyAttributes = Ember.A(), // just for removeObject + key, cachedValue, dataValue, desc, descMeta, type, isDirty; + + for (var i = 0, l = attributes.length; i < l; i++) { + key = attributes[i]; + if (!hasCachedValue(this, key)) { continue; } + cachedValue = this.cacheFor(key); + dataValue = get(this, 'data.'+this.dataKey(key)); + desc = meta(this).descs[key]; + descMeta = desc && desc.meta(); + type = descMeta.type; + + if (type && type.isEqual) { + isDirty = !type.isEqual(dataValue, cachedValue); + } else if (dataValue !== cachedValue) { + isDirty = true; + } else { + isDirty = false; + } + + if (isDirty) { + dirtyAttributes.push(key); + } + } + + if (dirtyAttributes.length) { + this._dirtyAttributes = dirtyAttributes; + return true; + } else { + this._dirtyAttributes = []; + return false; + } + }).property().volatile(), + + dataKey: function(key) { + var camelizeKeys = get(this.constructor, 'camelizeKeys'); + return camelizeKeys ? underscore(key) : key; + }, + + init: function() { + this._createReference(); + this._super(); + }, + + _createReference: function() { + var reference = this._reference, + id = this.getPrimaryKey(); + + if (!reference) { + reference = this.constructor._referenceForId(id); + reference.record = this; + this._reference = reference; + } + + if (!reference.id) { + reference.id = id; + } + + return reference; + }, + + getPrimaryKey: function() { + return get(this, get(this.constructor, 'primaryKey')); + }, + + load: function(id, hash) { + var data = {}; + data[get(this.constructor, 'primaryKey')] = id; + set(this, 'data', Ember.merge(data, hash)); + set(this, 'isLoaded', true); + set(this, 'isNew', false); + this._createReference(); + this.trigger('didLoad'); + }, + + didDefineProperty: function(proto, key, value) { + if (value instanceof Ember.Descriptor) { + var meta = value.meta(); + + if (meta.isAttribute) { + if (!proto.attributes) { proto.attributes = []; } + proto.attributes.push(key); + } else if (meta.isRelationship) { + if (!proto.relationships) { proto.relationships = []; } + proto.relationships.push(key); + } + } + }, + + serializeHasMany: function(key, meta) { + return this.get(key).toJSON(); + }, + + serializeBelongsTo: function(key, meta) { + if (meta.options.embedded) { + var record = this.get(key); + if (record) { + return record.toJSON(); + } + } else { + var primaryKey = get(meta.type, 'primaryKey'); + return this.get(key + '.' + primaryKey); + } + }, + + toJSON: function() { + var key, meta, + properties = this.getProperties(this.attributes); + + for (key in properties) { + meta = this.constructor.metaForProperty(key); + if (meta.type && meta.type.serialize) { + properties[key] = meta.type.serialize(properties[key]); + } else if (meta.type && Ember.Model.dataTypes[meta.type]) { + properties[key] = Ember.Model.dataTypes[meta.type].serialize(properties[key]); + } + } + + if (this.relationships) { + var data; + for(var i = 0; i < this.relationships.length; i++) { + key = this.relationships[i]; + meta = this.constructor.metaForProperty(key); + + if (meta.kind === 'belongsTo') { + data = this.serializeBelongsTo(key, meta); + } else { + data = this.serializeHasMany(key, meta); + } + + if (data) { + properties[key] = data; + } + } + } + + if (this.constructor.rootKey) { + var json = {}; + json[this.constructor.rootKey] = properties; + + return json; + } else { + return properties; + } + }, + + save: function() { + var adapter = this.constructor.adapter; + set(this, 'isSaving', true); + if (get(this, 'isNew')) { + return adapter.createRecord(this); + } else if (get(this, 'isDirty')) { + return adapter.saveRecord(this); + } else { // noop, return a resolved promise + var self = this, + promise = new Ember.RSVP.Promise(function(resolve, reject) { + resolve(self); + }); + set(this, 'isSaving', false); + return promise; + } + }, + + reload: function() { + return this.constructor.reload(this.get(get(this.constructor, 'primaryKey'))); + }, + + revert: function() { + if (this.get('isDirty')) { + var data = get(this, 'data'), + reverts = {}; + for (var i = 0; i < this._dirtyAttributes.length; i++) { + var attr = this._dirtyAttributes[i]; + reverts[attr] = data[attr]; + } + setProperties(this, reverts); + } + }, + + didCreateRecord: function() { + var primaryKey = get(this.constructor, 'primaryKey'), + id = get(this, primaryKey); + + set(this, 'isNew', false); + + if (!this.constructor.recordCache) this.constructor.recordCache = {}; + this.constructor.recordCache[id] = this; + + this.load(id, this.getProperties(this.attributes)); + this.constructor.addToRecordArrays(this); + this.trigger('didCreateRecord'); + this.didSaveRecord(); + }, + + didSaveRecord: function() { + set(this, 'isSaving', false); + this.trigger('didSaveRecord'); + if (this.get('isDirty')) { this._copyDirtyAttributesToData(); } + }, + + deleteRecord: function() { + return this.constructor.adapter.deleteRecord(this); + }, + + didDeleteRecord: function() { + this.constructor.removeFromRecordArrays(this); + set(this, 'isDeleted', true); + this.trigger('didDeleteRecord'); + }, + + _copyDirtyAttributesToData: function() { + if (!this._dirtyAttributes) { return; } + var dirtyAttributes = this._dirtyAttributes, + data = get(this, 'data'), + key; + + if (!data) { + data = {}; + set(this, 'data', data); + } + for (var i = 0, l = dirtyAttributes.length; i < l; i++) { + // TODO: merge Object.create'd object into prototype + key = dirtyAttributes[i]; + data[this.dataKey(key)] = this.cacheFor(key); + } + this._dirtyAttributes = []; + }, + + dataDidChange: Ember.observer(function() { + this._reloadHasManys(); + }, 'data'), + + _registerHasManyArray: function(array) { + if (!this._hasManyArrays) { this._hasManyArrays = Ember.A([]); } + + this._hasManyArrays.pushObject(array); + }, + + _reloadHasManys: function() { + if (!this._hasManyArrays) { return; } + + var i; + for(i = 0; i < this._hasManyArrays.length; i++) { + var array = this._hasManyArrays[i]; + set(array, 'content', this._getHasManyContent(get(array, 'key'), get(array, 'modelClass'), get(array, 'embedded'))); + } + }, + + _getHasManyContent: function(key, type, embedded) { + var content = get(this, 'data.' + key); + + if (content) { + var mapFunction, primaryKey, reference; + if (embedded) { + primaryKey = get(type, 'primaryKey'); + mapFunction = function(attrs) { + reference = type._referenceForId(attrs[primaryKey]); + reference.data = attrs; + return reference; + }; + } else { + mapFunction = function(id) { return type._referenceForId(id); }; + } + content = Ember.EnumerableUtils.map(content, mapFunction); + } + + return Ember.A(content || []); + } +}); + +Ember.Model.reopenClass({ + primaryKey: 'id', + + adapter: Ember.Adapter.create(), + + _clientIdCounter: 1, + + fetch: function() { + return Ember.loadPromise(this.find.apply(this, arguments)); + }, + + find: function(id) { + if (!arguments.length) { + return this.findAll(); + } else if (Ember.isArray(id)) { + return this.findMany(id); + } else if (typeof id === 'object') { + return this.findQuery(id); + } else { + return this.findById(id); + } + }, + + findMany: function(ids) { + Ember.assert("findMany requires an array", Ember.isArray(ids)); + + var records = Ember.RecordArray.create({_ids: ids}); + + if (!this.recordArrays) { this.recordArrays = []; } + this.recordArrays.push(records); + + if (this._currentBatchIds) { + concatUnique(this._currentBatchIds, ids); + this._currentBatchRecordArrays.push(records); + } else { + this._currentBatchIds = concatUnique([], ids); + this._currentBatchRecordArrays = [records]; + } + + Ember.run.scheduleOnce('data', this, this._executeBatch); + + return records; + }, + + findAll: function() { + if (this._findAllRecordArray) { return this._findAllRecordArray; } + + var records = this._findAllRecordArray = Ember.RecordArray.create(); + + this.adapter.findAll(this, records); + + return records; + }, + + _currentBatchIds: null, + _currentBatchRecordArrays: null, + + findById: function(id) { + var record = this.cachedRecordForId(id); + + if (!get(record, 'isLoaded')) { + this._fetchById(record, id); + } + return record; + }, + + reload: function(id) { + var record = this.cachedRecordForId(id); + + this._fetchById(record, id); + + return record; + }, + + _fetchById: function(record, id) { + var adapter = get(this, 'adapter'); + + if (adapter.findMany) { + if (this._currentBatchIds) { + if (!contains(this._currentBatchIds, id)) { this._currentBatchIds.push(id); } + } else { + this._currentBatchIds = [id]; + this._currentBatchRecordArrays = []; + } + + Ember.run.scheduleOnce('data', this, this._executeBatch); + // TODO: return a promise here + } else { + return adapter.find(record, id); + } + }, + + _executeBatch: function() { + var batchIds = this._currentBatchIds, + batchRecordArrays = this._currentBatchRecordArrays, + self = this, + requestIds = [], + promise, + i; + + this._currentBatchIds = null; + this._currentBatchRecordArrays = null; + + for (i = 0; i < batchIds.length; i++) { + if (!this.cachedRecordForId(batchIds[i]).get('isLoaded')) { + requestIds.push(batchIds[i]); + } + } + + if (batchIds.length === 1) { + promise = get(this, 'adapter').find(this.cachedRecordForId(batchIds[0]), batchIds[0]); + } else { + var recordArray = Ember.RecordArray.create({_ids: batchIds}); + if (requestIds.length === 0) { + promise = new Ember.RSVP.Promise(function(resolve, reject) { resolve(recordArray); }); + recordArray.notifyLoaded(); + } else { + promise = get(this, 'adapter').findMany(this, recordArray, requestIds); + } + } + + promise.then(function() { + for (var i = 0, l = batchRecordArrays.length; i < l; i++) { + batchRecordArrays[i].loadForFindMany(self); + } + }); + }, + + findQuery: function(params) { + var records = Ember.RecordArray.create(); + + this.adapter.findQuery(this, records, params); + + return records; + }, + + cachedRecordForId: function(id) { + if (!this.recordCache) { this.recordCache = {}; } + var record; + + if (this.recordCache[id]) { + record = this.recordCache[id]; + } else { + var primaryKey = get(this, 'primaryKey'), + attrs = {isLoaded: false}; + attrs[primaryKey] = id; + record = this.create(attrs); + var sideloadedData = this.sideloadedData && this.sideloadedData[id]; + if (sideloadedData) { + record.load(id, sideloadedData); + } + this.recordCache[id] = record; + } + + return record; + }, + + addToRecordArrays: function(record) { + if (this._findAllRecordArray) { + this._findAllRecordArray.pushObject(record); + } + if (this.recordArrays) { + this.recordArrays.forEach(function(recordArray) { + if (recordArray instanceof Ember.FilteredRecordArray) { + recordArray.registerObserversOnRecord(record); + recordArray.updateFilter(); + } else { + recordArray.pushObject(record); + } + }); + } + }, + + removeFromRecordArrays: function(record) { + if (this._findAllRecordArray) { + this._findAllRecordArray.removeObject(record); + } + if (this.recordArrays) { + this.recordArrays.forEach(function(recordArray) { + recordArray.removeObject(record); + }); + } + }, + + // FIXME + findFromCacheOrLoad: function(data) { + var record; + if (!data[get(this, 'primaryKey')]) { + record = this.create({isLoaded: false}); + } else { + record = this.cachedRecordForId(data[get(this, 'primaryKey')]); + } + // set(record, 'data', data); + record.load(data[get(this, 'primaryKey')], data); + return record; + }, + + registerRecordArray: function(recordArray) { + if (!this.recordArrays) { this.recordArrays = []; } + this.recordArrays.push(recordArray); + }, + + unregisterRecordArray: function(recordArray) { + if (!this.recordArrays) { return; } + Ember.A(this.recordArrays).removeObject(recordArray); + }, + + forEachCachedRecord: function(callback) { + if (!this.recordCache) { return Ember.A([]); } + var ids = Object.keys(this.recordCache); + ids.map(function(id) { + return this.recordCache[id]; + }, this).forEach(callback); + }, + + load: function(hashes) { + if (!this.sideloadedData) { this.sideloadedData = {}; } + for (var i = 0, l = hashes.length; i < l; i++) { + var hash = hashes[i]; + this.sideloadedData[hash[get(this, 'primaryKey')]] = hash; + } + }, + + _referenceForId: function(id) { + if (!this._idToReference) { this._idToReference = {}; } + + var reference = this._idToReference[id]; + if (!reference) { + reference = this._createReference(id); + } + + return reference; + }, + + _createReference: function(id) { + if (!this._idToReference) { this._idToReference = {}; } + + Ember.assert('The id ' + id + ' has alread been used with another record of type ' + this.toString() + '.', !id || !this._idToReference[id]); + + var reference = { + id: id, + clientId: this._clientIdCounter++ + }; + + // if we're creating an item, this process will be done + // later, once the object has been persisted. + if (id) { + this._idToReference[id] = reference; + } + + return reference; + } +}); + + +})(); + +(function() { + +var get = Ember.get; + +Ember.hasMany = function(type, options) { + options = options || {}; + + var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany' }, + key = options.key; + + return Ember.computed(function() { + if (typeof type === "string") { + type = Ember.get(Ember.lookup, type); + } + + return this.getHasMany(key, type, meta); + }).property().meta(meta); +}; + +Ember.Model.reopen({ + getHasMany: function(key, type, meta) { + var embedded = meta.options.embedded, + collectionClass = embedded ? Ember.EmbeddedHasManyArray : Ember.HasManyArray; + + var collection = collectionClass.create({ + parent: this, + modelClass: type, + content: this._getHasManyContent(key, type, embedded), + embedded: embedded, + key: key + }); + + this._registerHasManyArray(collection); + + return collection; + } +}); + + +})(); + +(function() { + +var get = Ember.get; + +Ember.belongsTo = function(type, options) { + options = options || {}; + + var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo' }, + key = options.key; + + return Ember.computed(function() { + if (typeof type === "string") { + type = Ember.get(Ember.lookup, type); + } + + return this.getBelongsTo(key, type, meta); + }).property('data').meta(meta); +}; + +Ember.Model.reopen({ + getBelongsTo: function(key, type, meta) { + var idOrAttrs = get(this, 'data.' + key), + record; + + if(Ember.isNone(idOrAttrs)) { + return null; + } + + if(meta.options.embedded) { + var primaryKey = get(type, 'primaryKey'); + record = type.create({ isLoaded: false }); + record.load(idOrAttrs[primaryKey], idOrAttrs); + } else { + record = type.findById(idOrAttrs); + } + + return record; + } +}); + + +})(); + +(function() { + +var get = Ember.get, + set = Ember.set, + meta = Ember.meta; + +function wrapObject(value) { + if (Ember.isArray(value)) { + var clonedArray = value.slice(); + + // TODO: write test for recursive cloning + for (var i = 0, l = clonedArray.length; i < l; i++) { + clonedArray[i] = wrapObject(clonedArray[i]); + } + + return Ember.A(clonedArray); + } else if (value && value.constructor === Date) { + return new Date(value.toISOString()); + } else if (value && typeof value === "object") { + var clone = Ember.create(value), property; + + for (property in value) { + if (value.hasOwnProperty(property) && typeof value[property] === "object") { + clone[property] = wrapObject(value[property]); + } + } + return clone; + } else { + return value; + } +} + +Ember.Model.dataTypes = {}; + +Ember.Model.dataTypes[Date] = { + deserialize: function(string) { + if(!string) { return null; } + return new Date(string); + }, + serialize: function (date) { + if(!date) { return null; } + return date.toISOString(); + } +}; + +Ember.Model.dataTypes[Number] = { + deserialize: function(string) { + if (!string && string !== 0) { return null; } + return Number(string); + }, + serialize: function (number) { + if (!number && number !== 0) { return null; } + return Number(number); + } +}; + +function deserialize(value, type) { + if (type && type.deserialize) { + return type.deserialize(value); + } else if (type && Ember.Model.dataTypes[type]) { + return Ember.Model.dataTypes[type].deserialize(value); + } else { + return wrapObject(value); + } +} + + +Ember.attr = function(type) { + return Ember.computed(function(key, value) { + var data = get(this, 'data'), + dataKey = this.dataKey(key), + dataValue = data && get(data, dataKey), + beingCreated = meta(this).proto === this; + + if (arguments.length === 2) { + if (beingCreated && !data) { + data = {}; + set(this, 'data', data); + data[dataKey] = value; + } + return wrapObject(value); + } + + return this.getAttr(key, deserialize(dataValue, type)); + }).property('data').meta({isAttribute: true, type: type}); +}; + + +})(); + +(function() { + +var get = Ember.get; + +Ember.RESTAdapter = Ember.Adapter.extend({ + find: function(record, id) { + var url = this.buildURL(record.constructor, id), + self = this; + + return this.ajax(url).then(function(data) { + self.didFind(record, id, data); + }); + }, + + didFind: function(record, id, data) { + var rootKey = get(record.constructor, 'rootKey'), + dataToLoad = rootKey ? data[rootKey] : data; + + record.load(id, dataToLoad); + }, + + findAll: function(klass, records) { + var url = this.buildURL(klass), + self = this; + + return this.ajax(url).then(function(data) { + self.didFindAll(klass, records, data); + }); + }, + + didFindAll: function(klass, records, data) { + var collectionKey = get(klass, 'collectionKey'), + dataToLoad = collectionKey ? data[collectionKey] : data; + + records.load(klass, dataToLoad); + }, + + findQuery: function(klass, records, params) { + var url = this.buildURL(klass), + self = this; + + return this.ajax(url, params).then(function(data) { + self.didFindQuery(klass, records, params, data); + }); + }, + + didFindQuery: function(klass, records, params, data) { + var collectionKey = get(klass, 'collectionKey'), + dataToLoad = collectionKey ? data[collectionKey] : data; + + records.load(klass, dataToLoad); + }, + + createRecord: function(record) { + var url = this.buildURL(record.constructor), + self = this; + + return this.ajax(url, record.toJSON(), "POST").then(function(data) { + self.didCreateRecord(record, data); + }); + }, + + didCreateRecord: function(record, data) { + var rootKey = get(record.constructor, 'rootKey'), + primaryKey = get(record.constructor, 'primaryKey'), + dataToLoad = rootKey ? data[rootKey] : data; + + record.load(dataToLoad[primaryKey], dataToLoad); + record.didCreateRecord(); + }, + + saveRecord: function(record) { + var primaryKey = get(record.constructor, 'primaryKey'), + url = this.buildURL(record.constructor, get(record, primaryKey)), + self = this; + + return this.ajax(url, record.toJSON(), "PUT").then(function(data) { // TODO: Some APIs may or may not return data + self.didSaveRecord(record, data); + }); + }, + + didSaveRecord: function(record, data) { + record.didSaveRecord(); + }, + + deleteRecord: function(record) { + var primaryKey = get(record.constructor, 'primaryKey'), + url = this.buildURL(record.constructor, get(record, primaryKey)), + self = this; + + return this.ajax(url, record.toJSON(), "DELETE").then(function(data) { // TODO: Some APIs may or may not return data + self.didDeleteRecord(record, data); + }); + }, + + didDeleteRecord: function(record, data) { + record.didDeleteRecord(); + }, + + ajax: function(url, params, method) { + return this._ajax(url, params, method || "GET"); + }, + + buildURL: function(klass, id) { + var urlRoot = get(klass, 'url'); + if (!urlRoot) { throw new Error('Ember.RESTAdapter requires a `url` property to be specified'); } + + if (id) { + return urlRoot + "/" + id + ".json"; + } else { + return urlRoot + ".json"; + } + }, + + _ajax: function(url, params, method) { + var settings = { + url: url, + type: method, + dataType: "json" + }; + + return new Ember.RSVP.Promise(function(resolve, reject) { + if (params) { + if (method === "GET") { + settings.data = params; + } else { + settings.contentType = "application/json; charset=utf-8"; + settings.data = JSON.stringify(params); + } + } + + settings.success = function(json) { + Ember.run(null, resolve, json); + }; + + settings.error = function(jqXHR, textStatus, errorThrown) { + Ember.run(null, reject, jqXHR); + }; + + + Ember.$.ajax(settings); + }); + } +}); + + +})(); + +(function() { + +var get = Ember.get; + +Ember.LoadPromise = Ember.Object.extend(Ember.DeferredMixin, { + init: function() { + this._super.apply(this, arguments); + + var target = get(this, 'target'); + + if (get(target, 'isLoaded') && !get(target, 'isNew')) { + this.resolve(target); + } else { + target.one('didLoad', this, function() { + this.resolve(target); + }); + } + } +}); + +Ember.loadPromise = function(target) { + if (Ember.isNone(target)) { + return null; + } else if (target.then) { + return target; + } else { + return Ember.LoadPromise.create({target: target}); + } +}; + + +})(); \ No newline at end of file diff --git a/assets/scripts/vendor/ember.js b/assets/scripts/vendor/ember.js index d658dfdf..5268555a 100644 --- a/assets/scripts/vendor/ember.js +++ b/assets/scripts/vendor/ember.js @@ -1,5 +1,5 @@ -// Version: v1.0.0-rc.3-206-gc9bbf8e -// Last commit: c9bbf8e (2013-05-13 16:35:33 +0200) +// Version: v1.0.0-rc.6-102-gf20bf05 +// Last commit: f20bf05 (2013-07-08 20:53:58 -0700) (function() { @@ -49,7 +49,12 @@ if (!('MANDATORY_SETTER' in Ember.ENV)) { falsy, an exception will be thrown. */ Ember.assert = function(desc, test) { - if (!test) throw new Error("assertion failed: "+desc); + Ember.Logger.assert(test, desc); + + if (Ember.testing && !test) { + // when testing, ensure test failures when assertions fail + throw new Error("Assertion Failed: " + desc); + } }; @@ -95,12 +100,12 @@ Ember.debug = function(message) { will be displayed. */ Ember.deprecate = function(message, test) { - if (Ember && Ember.TESTING_DEPRECATION) { return; } + if (Ember.TESTING_DEPRECATION) { return; } if (arguments.length === 1) { test = false; } if (test) { return; } - if (Ember && Ember.ENV.RAISE_ON_DEPRECATION) { throw new Error(message); } + if (Ember.ENV.RAISE_ON_DEPRECATION) { throw new Error(message); } var error; @@ -151,8 +156,8 @@ Ember.deprecateFunc = function(message, func) { })(); -// Version: v1.0.0-rc.3-206-gc9bbf8e -// Last commit: c9bbf8e (2013-05-13 16:35:33 +0200) +// Version: v1.0.0-rc.6-102-gf20bf05 +// Last commit: f20bf05 (2013-07-08 20:53:58 -0700) (function() { @@ -169,11 +174,18 @@ var define, requireModule; if (seen[name]) { return seen[name]; } seen[name] = {}; - var mod = registry[name], - deps = mod.deps, - callback = mod.callback, - reified = [], - exports; + var mod, deps, callback, reified, exports; + + mod = registry[name]; + + if (!mod) { + throw new Error("Module '" + name + "' not found."); + } + + deps = mod.deps; + callback = mod.callback; + reified = []; + exports; for (var i=0, l=deps.length; i -1) { - list.splice(index, 1); - } - }, - - /** - @method isEmpty - @return {Boolean} - */ - isEmpty: function() { - return this.list.length === 0; - }, - - /** - @method has - @param obj - @return {Boolean} - */ - has: function(obj) { - var guid = guidFor(obj), - presenceSet = this.presenceSet; - - return guid in presenceSet; - }, - - /** - @method forEach - @param {Function} fn - @param self - */ - forEach: function(fn, self) { - // allow mutation during iteration - var list = this.toArray(); - - for (var i = 0, j = list.length; i < j; i++) { - fn.call(self, list[i]); - } - }, - - /** - @method toArray - @return {Array} - */ - toArray: function() { - return this.list.slice(); - }, - - /** - @method copy - @return {Ember.OrderedSet} - */ - copy: function() { - var set = new OrderedSet(); - - set.presenceSet = copy(this.presenceSet); - set.list = this.toArray(); - - return set; - } -}; - -/** - A Map stores values indexed by keys. Unlike JavaScript's - default Objects, the keys of a Map can be any JavaScript - object. - - Internally, a Map has two data structures: - - 1. `keys`: an OrderedSet of all of the existing keys - 2. `values`: a JavaScript Object indexed by the `Ember.guidFor(key)` - - When a key/value pair is added for the first time, we - add the key to the `keys` OrderedSet, and create or - replace an entry in `values`. When an entry is deleted, - we delete its entry in `keys` and `values`. - - @class Map - @namespace Ember - @private - @constructor -*/ -var Map = Ember.Map = function() { - this.keys = Ember.OrderedSet.create(); - this.values = {}; -}; - -/** - @method create - @static -*/ -Map.create = function() { - return new Map(); -}; - -Map.prototype = { - /** - Retrieve the value associated with a given key. - - @method get - @param {*} key - @return {*} the value associated with the key, or `undefined` - */ - get: function(key) { - var values = this.values, - guid = guidFor(key); - - return values[guid]; - }, - - /** - Adds a value to the map. If a value for the given key has already been - provided, the new value will replace the old value. - - @method set - @param {*} key - @param {*} value - */ - set: function(key, value) { - var keys = this.keys, - values = this.values, - guid = guidFor(key); - - keys.add(key); - values[guid] = value; - }, - - /** - Removes a value from the map for an associated key. - - @method remove - @param {*} key - @return {Boolean} true if an item was removed, false otherwise - */ - remove: function(key) { - // don't use ES6 "delete" because it will be annoying - // to use in browsers that are not ES6 friendly; - var keys = this.keys, - values = this.values, - guid = guidFor(key); - - if (values.hasOwnProperty(guid)) { - keys.remove(key); - delete values[guid]; - return true; - } else { - return false; - } - }, - - /** - Check whether a key is present. - - @method has - @param {*} key - @return {Boolean} true if the item was present, false otherwise - */ - has: function(key) { - var values = this.values, - guid = guidFor(key); - - return values.hasOwnProperty(guid); - }, - - /** - Iterate over all the keys and values. Calls the function once - for each key, passing in the key and value, in that order. - - The keys are guaranteed to be iterated over in insertion order. - - @method forEach - @param {Function} callback - @param {*} self if passed, the `this` value inside the - callback. By default, `this` is the map. - */ - forEach: function(callback, self) { - var keys = this.keys, - values = this.values; - - keys.forEach(function(key) { - var guid = guidFor(key); - callback.call(self, key, values[guid]); - }); - }, - - /** - @method copy - @return {Ember.Map} - */ - copy: function() { - return copyMap(this, new Map()); - } -}; - -/** - @class MapWithDefault - @namespace Ember - @extends Ember.Map - @private - @constructor - @param [options] - @param {*} [options.defaultValue] -*/ -var MapWithDefault = Ember.MapWithDefault = function(options) { - Map.call(this); - this.defaultValue = options.defaultValue; -}; - -/** - @method create - @static - @param [options] - @param {*} [options.defaultValue] - @return {Ember.MapWithDefault|Ember.Map} If options are passed, returns - `Ember.MapWithDefault` otherwise returns `Ember.Map` -*/ -MapWithDefault.create = function(options) { - if (options) { - return new MapWithDefault(options); - } else { - return new Map(); - } -}; - -MapWithDefault.prototype = Ember.create(Map.prototype); - -/** - Retrieve the value associated with a given key. - - @method get - @param {*} key - @return {*} the value associated with the key, or the default value -*/ -MapWithDefault.prototype.get = function(key) { - var hasValue = this.has(key); - - if (hasValue) { - return Map.prototype.get.call(this, key); - } else { - var defaultValue = this.defaultValue(key); - this.set(key, defaultValue); - return defaultValue; - } -}; - -/** - @method copy - @return {Ember.MapWithDefault} -*/ -MapWithDefault.prototype.copy = function() { - return copyMap(this, new MapWithDefault({ - defaultValue: this.defaultValue - })); -}; - -})(); - - - (function() { /** @module ember-metal @@ -1999,6 +1666,7 @@ get = function get(obj, keyName) { obj = null; } + Ember.assert("Cannot call get with "+ keyName +" key.", !!keyName); Ember.assert("Cannot call get with '"+ keyName +"' on an undefined object.", obj !== undefined); if (obj === null || keyName.indexOf('.') !== -1) { @@ -2031,12 +1699,21 @@ if (Ember.config.overrideAccessors) { get = Ember.get; } -function firstKey(path) { - return path.match(FIRST_KEY)[0]; -} +/** + @private -// assumes path is already normalized -function normalizeTuple(target, path) { + Normalizes a target/path pair to reflect that actual target/path that should + be observed, etc. This takes into account passing in global property + paths (i.e. a path beginning with a captial letter not defined on the + target) and * separators. + + @method normalizeTuple + @for Ember + @param {Object} target The current target. May be `null`. + @param {String} path A path on the target or a global property path. + @return {Array} a temporary array with the normalized target/path pair. +*/ +var normalizeTuple = Ember.normalizeTuple = function(target, path) { var hasThis = HAS_THIS.test(path), isGlobal = !hasThis && IS_GLOBAL_PATH.test(path), key; @@ -2045,7 +1722,7 @@ function normalizeTuple(target, path) { if (hasThis) path = path.slice(5); if (target === Ember.lookup) { - key = firstKey(path); + key = path.match(FIRST_KEY)[0]; target = get(target, key); path = path.slice(key.length+1); } @@ -2054,7 +1731,7 @@ function normalizeTuple(target, path) { if (!path || path.length===0) throw new Error('Invalid Path'); return [ target, path ]; -} +}; var getPath = Ember._getPath = function(root, path) { var hasThis, parts, tuple, idx, len; @@ -2076,31 +1753,13 @@ var getPath = Ember._getPath = function(root, path) { parts = path.split("."); len = parts.length; - for (idx=0; root !== undefined && root !== null && idx -1) { + list.splice(index, 1); + } + }, + + /** + @method isEmpty + @return {Boolean} + */ + isEmpty: function() { + return this.list.length === 0; + }, + + /** + @method has + @param obj + @return {Boolean} + */ + has: function(obj) { + var guid = guidFor(obj), + presenceSet = this.presenceSet; + + return guid in presenceSet; + }, + + /** + @method forEach + @param {Function} fn + @param self + */ + forEach: function(fn, self) { + // allow mutation during iteration + var list = this.toArray(); + + for (var i = 0, j = list.length; i < j; i++) { + fn.call(self, list[i]); + } + }, + + /** + @method toArray + @return {Array} + */ + toArray: function() { + return this.list.slice(); + }, + + /** + @method copy + @return {Ember.OrderedSet} + */ + copy: function() { + var set = new OrderedSet(); + + set.presenceSet = copy(this.presenceSet); + set.list = this.toArray(); + + return set; + } +}; + +/** + A Map stores values indexed by keys. Unlike JavaScript's + default Objects, the keys of a Map can be any JavaScript + object. + + Internally, a Map has two data structures: + + 1. `keys`: an OrderedSet of all of the existing keys + 2. `values`: a JavaScript Object indexed by the `Ember.guidFor(key)` + + When a key/value pair is added for the first time, we + add the key to the `keys` OrderedSet, and create or + replace an entry in `values`. When an entry is deleted, + we delete its entry in `keys` and `values`. + + @class Map + @namespace Ember + @private + @constructor +*/ +var Map = Ember.Map = function() { + this.keys = Ember.OrderedSet.create(); + this.values = {}; +}; + +/** + @method create + @static +*/ +Map.create = function() { + return new Map(); +}; + +Map.prototype = { + /** + This property will change as the number of objects in the map changes. + + @property length + @type number + @default 0 + */ + length: 0, + + + /** + Retrieve the value associated with a given key. + + @method get + @param {*} key + @return {*} the value associated with the key, or `undefined` + */ + get: function(key) { + var values = this.values, + guid = guidFor(key); + + return values[guid]; + }, + + /** + Adds a value to the map. If a value for the given key has already been + provided, the new value will replace the old value. + + @method set + @param {*} key + @param {*} value + */ + set: function(key, value) { + var keys = this.keys, + values = this.values, + guid = guidFor(key); + + keys.add(key); + values[guid] = value; + set(this, 'length', keys.list.length); + }, + + /** + Removes a value from the map for an associated key. + + @method remove + @param {*} key + @return {Boolean} true if an item was removed, false otherwise + */ + remove: function(key) { + // don't use ES6 "delete" because it will be annoying + // to use in browsers that are not ES6 friendly; + var keys = this.keys, + values = this.values, + guid = guidFor(key); + + if (values.hasOwnProperty(guid)) { + keys.remove(key); + delete values[guid]; + set(this, 'length', keys.list.length); + return true; + } else { + return false; + } + }, + + /** + Check whether a key is present. + + @method has + @param {*} key + @return {Boolean} true if the item was present, false otherwise + */ + has: function(key) { + var values = this.values, + guid = guidFor(key); + + return values.hasOwnProperty(guid); + }, + + /** + Iterate over all the keys and values. Calls the function once + for each key, passing in the key and value, in that order. + + The keys are guaranteed to be iterated over in insertion order. + + @method forEach + @param {Function} callback + @param {*} self if passed, the `this` value inside the + callback. By default, `this` is the map. + */ + forEach: function(callback, self) { + var keys = this.keys, + values = this.values; + + keys.forEach(function(key) { + var guid = guidFor(key); + callback.call(self, key, values[guid]); + }); + }, + + /** + @method copy + @return {Ember.Map} + */ + copy: function() { + return copyMap(this, new Map()); + } +}; + +/** + @class MapWithDefault + @namespace Ember + @extends Ember.Map + @private + @constructor + @param [options] + @param {*} [options.defaultValue] +*/ +var MapWithDefault = Ember.MapWithDefault = function(options) { + Map.call(this); + this.defaultValue = options.defaultValue; +}; + +/** + @method create + @static + @param [options] + @param {*} [options.defaultValue] + @return {Ember.MapWithDefault|Ember.Map} If options are passed, returns + `Ember.MapWithDefault` otherwise returns `Ember.Map` +*/ +MapWithDefault.create = function(options) { + if (options) { + return new MapWithDefault(options); + } else { + return new Map(); + } +}; + +MapWithDefault.prototype = Ember.create(Map.prototype); + +/** + Retrieve the value associated with a given key. + + @method get + @param {*} key + @return {*} the value associated with the key, or the default value +*/ +MapWithDefault.prototype.get = function(key) { + var hasValue = this.has(key); + + if (hasValue) { + return Map.prototype.get.call(this, key); + } else { + var defaultValue = this.defaultValue(key); + this.set(key, defaultValue); + return defaultValue; + } +}; + +/** + @method copy + @return {Ember.MapWithDefault} +*/ +MapWithDefault.prototype.copy = function() { + return copyMap(this, new MapWithDefault({ + defaultValue: this.defaultValue + })); +}; + +})(); + + + (function() { /** @module ember-metal @@ -3090,9 +3132,9 @@ var changeProperties = Ember.changeProperties, observers will be buffered. @method setProperties - @param target - @param {Hash} properties - @return target + @param self + @param {Object} hash + @return self */ Ember.setProperties = function(self, hash) { changeProperties(function(){ @@ -3773,27 +3815,14 @@ ComputedProperty.prototype = new Ember.Descriptor(); var ComputedPropertyPrototype = ComputedProperty.prototype; /* - Call on a computed property to explicitly change it's cacheable mode. + Properties are cacheable by default. Computed property will automatically + cache the return value of your function until one of the dependent keys changes. - Please use `.volatile` over this method. + Call `volatile()` to set it into non-cached mode. When in this mode + the computed property will not automatically cache the return value. - ```javascript - MyApp.president = Ember.Object.create({ - fullName: function() { - return this.get('firstName') + ' ' + this.get('lastName'); - - // By default, Ember will return the value of this property - // without re-executing this function. - }.property('firstName', 'lastName') - - initials: function() { - return this.get('firstName')[0] + this.get('lastName')[0]; - - // This function will be executed every time this property - // is requested. - }.property('firstName', 'lastName').cacheable(false) - }); - ``` + However, if a property is properly observable, there is no reason to disable + caching. @method cacheable @param {Boolean} aFlag optional set to `false` to disable caching @@ -4057,7 +4086,6 @@ ComputedPropertyPrototype.teardown = function(obj, keyName) { The function should accept two parameters, key and value. If value is not undefined you should set the value first. In either case return the current value of the property. - @method computed @for Ember @param {Function} func The computed property function. @@ -4299,7 +4327,7 @@ registerComputedWithProperties('or', function(properties) { @for Ember @param {String} dependentKey, [dependentKey...] @return {Ember.ComputedProperty} computed property which returns - the first trouthy value of given list of properties. + the first truthy value of given list of properties. */ registerComputedWithProperties('any', function(properties) { for (var key in properties) { @@ -4349,6 +4377,48 @@ Ember.computed.alias = function(dependentKey) { }); }; +/** + @method computed.oneWay + @for Ember + @param {String} dependentKey + @return {Ember.ComputedProperty} computed property which creates an + one way computed property to the original value for property. + + Where `computed.alias` aliases `get` and `set`, and allows for bidirectional + data flow, `computed.oneWay` only provides an aliased `get`. The `set` will + not mutate the upstream property, rather causes the current property to + become the value set. This causes the downstream property to permentantly + diverge from the upstream property. + + ```javascript + User = Ember.Object.extend({ + firstName: null, + lastName: null, + nickName: Ember.computed.oneWay('firstName') + }); + + user = User.create({ + firstName: 'Teddy', + lastName: 'Zeenny' + }); + + user.get('nickName'); + # 'Teddy' + + user.set('nickName', 'TeddyBear'); + # 'TeddyBear' + + user.get('firstName'); + # 'Teddy' + ``` +*/ +Ember.computed.oneWay = function(dependentKey) { + return Ember.computed(dependentKey, function() { + return get(this, dependentKey); + }); +}; + + /** @method computed.defaultTo @for Ember @@ -4474,183 +4544,597 @@ Ember.removeBeforeObserver = function(obj, path, target, method) { (function() { -// Ember.Logger -// Ember.watch.flushPending -// Ember.beginPropertyChanges, Ember.endPropertyChanges -// Ember.guidFor, Ember.tryFinally - -/** -@module ember-metal -*/ - -// .......................................................... -// HELPERS -// - -var slice = [].slice, - forEach = Ember.ArrayPolyfills.forEach; - -// invokes passed params - normalizing so you can pass target/func, -// target/string or just func -function invoke(target, method, args, ignore) { - - if (method === undefined) { - method = target; - target = undefined; - } - - if ('string' === typeof method) { method = target[method]; } - if (args && ignore > 0) { - args = args.length > ignore ? slice.call(args, ignore) : null; - } - - return Ember.handleErrors(function() { - // IE8's Function.prototype.apply doesn't accept undefined/null arguments. - return method.apply(target || this, args || []); - }, this); -} - - -// .......................................................... -// RUNLOOP -// - -/** -Ember RunLoop (Private) - -@class RunLoop -@namespace Ember -@private -@constructor -*/ -var RunLoop = function(prev) { - this._prev = prev || null; - this.onceTimers = {}; -}; - -RunLoop.prototype = { - /** - @method end - */ - end: function() { - this.flush(); - }, - - /** - @method prev - */ - prev: function() { - return this._prev; - }, - - // .......................................................... - // Delayed Actions - // - - /** - @method schedule - @param {String} queueName - @param target - @param method - */ - schedule: function(queueName, target, method) { - var queues = this._queues, queue; - if (!queues) { queues = this._queues = {}; } - queue = queues[queueName]; - if (!queue) { queue = queues[queueName] = []; } - - var args = arguments.length > 3 ? slice.call(arguments, 3) : null; - queue.push({ target: target, method: method, args: args }); - return this; - }, - - /** - @method flush - @param {String} queueName - */ - flush: function(queueName) { - var queueNames, idx, len, queue, log; - - if (!this._queues) { return this; } // nothing to do - - function iter(item) { - invoke(item.target, item.method, item.args); +define("backburner/queue", + ["exports"], + function(__exports__) { + "use strict"; + function Queue(daq, name, options) { + this.daq = daq; + this.name = name; + this.options = options; + this._queue = []; } - function tryable() { - forEach.call(queue, iter); - } + Queue.prototype = { + daq: null, + name: null, + options: null, + _queue: null, - Ember.watch.flushPending(); // make sure all chained watchers are setup + push: function(target, method, args, stack) { + var queue = this._queue; + queue.push(target, method, args, stack); + return {queue: this, target: target, method: method}; + }, - if (queueName) { - while (this._queues && (queue = this._queues[queueName])) { - this._queues[queueName] = null; + pushUnique: function(target, method, args, stack) { + var queue = this._queue, currentTarget, currentMethod, i, l; - // the sync phase is to allow property changes to propagate. don't - // invoke observers until that is finished. - if (queueName === 'sync') { - log = Ember.LOG_BINDINGS; - if (log) { Ember.Logger.log('Begin: Flush Sync Queue'); } + for (i = 0, l = queue.length; i < l; i += 4) { + currentTarget = queue[i]; + currentMethod = queue[i+1]; - Ember.beginPropertyChanges(); - - Ember.tryFinally(tryable, Ember.endPropertyChanges); - - if (log) { Ember.Logger.log('End: Flush Sync Queue'); } - - } else { - forEach.call(queue, iter); - } - } - - } else { - queueNames = Ember.run.queues; - len = queueNames.length; - idx = 0; - - outerloop: - while (idx < len) { - queueName = queueNames[idx]; - queue = this._queues && this._queues[queueName]; - delete this._queues[queueName]; - - if (queue) { - // the sync phase is to allow property changes to propagate. don't - // invoke observers until that is finished. - if (queueName === 'sync') { - log = Ember.LOG_BINDINGS; - if (log) { Ember.Logger.log('Begin: Flush Sync Queue'); } - - Ember.beginPropertyChanges(); - - Ember.tryFinally(tryable, Ember.endPropertyChanges); - - if (log) { Ember.Logger.log('End: Flush Sync Queue'); } - } else { - forEach.call(queue, iter); + if (currentTarget === target && currentMethod === method) { + queue[i+2] = args; // replace args + queue[i+3] = stack; // replace stack + return {queue: this, target: target, method: method}; // TODO: test this code path } } - // Loop through prior queues - for (var i = 0; i <= idx; i++) { - if (this._queues && this._queues[queueNames[i]]) { - // Start over at the first queue with contents - idx = i; + this._queue.push(target, method, args, stack); + return {queue: this, target: target, method: method}; + }, + + // TODO: remove me, only being used for Ember.run.sync + flush: function() { + var queue = this._queue, + options = this.options, + before = options && options.before, + after = options && options.after, + target, method, args, stack, i, l = queue.length; + + if (l && before) { before(); } + for (i = 0; i < l; i += 4) { + target = queue[i]; + method = queue[i+1]; + args = queue[i+2]; + stack = queue[i+3]; // Debugging assistance + + // TODO: error handling + if (args && args.length > 0) { + method.apply(target, args); + } else { + method.call(target); + } + } + if (l && after) { after(); } + + // check if new items have been added + if (queue.length > l) { + this._queue = queue.slice(l); + this.flush(); + } else { + this._queue.length = 0; + } + }, + + cancel: function(actionToCancel) { + var queue = this._queue, currentTarget, currentMethod, i, l; + + for (i = 0, l = queue.length; i < l; i += 4) { + currentTarget = queue[i]; + currentMethod = queue[i+1]; + + if (currentTarget === actionToCancel.target && currentMethod === actionToCancel.method) { + queue.splice(i, 4); + return true; + } + } + + // if not found in current queue + // could be in the queue that is being flushed + queue = this._queueBeingFlushed; + if (!queue) { + return; + } + for (i = 0, l = queue.length; i < l; i += 4) { + currentTarget = queue[i]; + currentMethod = queue[i+1]; + + if (currentTarget === actionToCancel.target && currentMethod === actionToCancel.method) { + // don't mess with array during flush + // just nullify the method + queue[i+1] = null; + return true; + } + } + } + }; + + + __exports__.Queue = Queue; + }); + +define("backburner/deferred_action_queues", + ["backburner/queue","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var Queue = __dependency1__.Queue; + + function DeferredActionQueues(queueNames, options) { + var queues = this.queues = {}; + this.queueNames = queueNames = queueNames || []; + + var queueName; + for (var i = 0, l = queueNames.length; i < l; i++) { + queueName = queueNames[i]; + queues[queueName] = new Queue(this, queueName, options[queueName]); + } + } + + DeferredActionQueues.prototype = { + queueNames: null, + queues: null, + + schedule: function(queueName, target, method, args, onceFlag, stack) { + var queues = this.queues, + queue = queues[queueName]; + + if (!queue) { throw new Error("You attempted to schedule an action in a queue (" + queueName + ") that doesn't exist"); } + + if (onceFlag) { + return queue.pushUnique(target, method, args, stack); + } else { + return queue.push(target, method, args, stack); + } + }, + + flush: function() { + var queues = this.queues, + queueNames = this.queueNames, + queueName, queue, queueItems, priorQueueNameIndex, + queueNameIndex = 0, numberOfQueues = queueNames.length; + + outerloop: + while (queueNameIndex < numberOfQueues) { + queueName = queueNames[queueNameIndex]; + queue = queues[queueName]; + queueItems = queue._queueBeingFlushed = queue._queue.slice(); + queue._queue = []; + + var options = queue.options, + before = options && options.before, + after = options && options.after, + target, method, args, stack, + queueIndex = 0, numberOfQueueItems = queueItems.length; + + if (numberOfQueueItems && before) { before(); } + while (queueIndex < numberOfQueueItems) { + target = queueItems[queueIndex]; + method = queueItems[queueIndex+1]; + args = queueItems[queueIndex+2]; + stack = queueItems[queueIndex+3]; // Debugging assistance + + if (typeof method === 'string') { method = target[method]; } + + // method could have been nullified / canceled during flush + if (method) { + // TODO: error handling + if (args && args.length > 0) { + method.apply(target, args); + } else { + method.call(target); + } + } + + queueIndex += 4; + } + queue._queueBeingFlushed = null; + if (numberOfQueueItems && after) { after(); } + + if ((priorQueueNameIndex = indexOfPriorQueueWithActions(this, queueNameIndex)) !== -1) { + queueNameIndex = priorQueueNameIndex; continue outerloop; } + + queueNameIndex++; + } + } + }; + + function indexOfPriorQueueWithActions(daq, currentQueueIndex) { + var queueName, queue; + + for (var i = 0, l = currentQueueIndex; i <= l; i++) { + queueName = daq.queueNames[i]; + queue = daq.queues[queueName]; + if (queue._queue.length) { return i; } + } + + return -1; + } + + + __exports__.DeferredActionQueues = DeferredActionQueues; + }); + +define("backburner", + ["backburner/deferred_action_queues","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var DeferredActionQueues = __dependency1__.DeferredActionQueues; + + var slice = [].slice, + pop = [].pop, + throttlers = [], + debouncees = [], + timers = [], + autorun, laterTimer, laterTimerExpiresAt, + global = this; + + function Backburner(queueNames, options) { + this.queueNames = queueNames; + this.options = options || {}; + if (!this.options.defaultQueue) { + this.options.defaultQueue = queueNames[0]; + } + this.instanceStack = []; + } + + Backburner.prototype = { + queueNames: null, + options: null, + currentInstance: null, + instanceStack: null, + + begin: function() { + var onBegin = this.options && this.options.onBegin, + previousInstance = this.currentInstance; + + if (previousInstance) { + this.instanceStack.push(previousInstance); } - idx++; + this.currentInstance = new DeferredActionQueues(this.queueNames, this.options); + if (onBegin) { + onBegin(this.currentInstance, previousInstance); + } + }, + + end: function() { + var onEnd = this.options && this.options.onEnd, + currentInstance = this.currentInstance, + nextInstance = null; + + try { + currentInstance.flush(); + } finally { + this.currentInstance = null; + + if (this.instanceStack.length) { + nextInstance = this.instanceStack.pop(); + this.currentInstance = nextInstance; + } + + if (onEnd) { + onEnd(currentInstance, nextInstance); + } + } + }, + + run: function(target, method /*, args */) { + var ret; + this.begin(); + + if (!method) { + method = target; + target = null; + } + + if (typeof method === 'string') { + method = target[method]; + } + + // Prevent Safari double-finally. + var finallyAlreadyCalled = false; + try { + if (arguments.length > 2) { + ret = method.apply(target, slice.call(arguments, 2)); + } else { + ret = method.call(target); + } + } finally { + if (!finallyAlreadyCalled) { + finallyAlreadyCalled = true; + this.end(); + } + } + return ret; + }, + + defer: function(queueName, target, method /* , args */) { + if (!method) { + method = target; + target = null; + } + + if (typeof method === 'string') { + method = target[method]; + } + + var stack = this.DEBUG ? new Error().stack : undefined, + args = arguments.length > 3 ? slice.call(arguments, 3) : undefined; + if (!this.currentInstance) { createAutorun(this); } + return this.currentInstance.schedule(queueName, target, method, args, false, stack); + }, + + deferOnce: function(queueName, target, method /* , args */) { + if (!method) { + method = target; + target = null; + } + + if (typeof method === 'string') { + method = target[method]; + } + + var stack = this.DEBUG ? new Error().stack : undefined, + args = arguments.length > 3 ? slice.call(arguments, 3) : undefined; + if (!this.currentInstance) { createAutorun(this); } + return this.currentInstance.schedule(queueName, target, method, args, true, stack); + }, + + setTimeout: function() { + var self = this, + wait = pop.call(arguments), + target = arguments[0], + method = arguments[1], + executeAt = (+new Date()) + wait; + + if (!method) { + method = target; + target = null; + } + + if (typeof method === 'string') { + method = target[method]; + } + + var fn, args; + if (arguments.length > 2) { + args = slice.call(arguments, 2); + + fn = function() { + method.apply(target, args); + }; + } else { + fn = function() { + method.call(target); + }; + } + + // find position to insert - TODO: binary search + var i, l; + for (i = 0, l = timers.length; i < l; i += 2) { + if (executeAt < timers[i]) { break; } + } + + timers.splice(i, 0, executeAt, fn); + + if (laterTimer && laterTimerExpiresAt < executeAt) { return fn; } + + if (laterTimer) { + clearTimeout(laterTimer); + laterTimer = null; + } + laterTimer = global.setTimeout(function() { + executeTimers(self); + laterTimer = null; + laterTimerExpiresAt = null; + }, wait); + laterTimerExpiresAt = executeAt; + + return fn; + }, + + throttle: function(target, method /* , args, wait */) { + var self = this, + args = arguments, + wait = pop.call(args), + throttler; + + for (var i = 0, l = throttlers.length; i < l; i++) { + throttler = throttlers[i]; + if (throttler[0] === target && throttler[1] === method) { return; } // do nothing + } + + var timer = global.setTimeout(function() { + self.run.apply(self, args); + + // remove throttler + var index = -1; + for (var i = 0, l = throttlers.length; i < l; i++) { + throttler = throttlers[i]; + if (throttler[0] === target && throttler[1] === method) { + index = i; + break; + } + } + + if (index > -1) { throttlers.splice(index, 1); } + }, wait); + + throttlers.push([target, method, timer]); + }, + + debounce: function(target, method /* , args, wait, [immediate] */) { + var self = this, + args = arguments, + immediate = pop.call(args), + wait, + index, + debouncee; + + if (typeof immediate === "number") { + wait = immediate; + immediate = false; + } else { + wait = pop.call(args); + } + + // Remove debouncee + index = findDebouncee(target, method); + + if (index !== -1) { + debouncee = debouncees[index]; + debouncees.splice(index, 1); + clearTimeout(debouncee[2]); + } + + var timer = window.setTimeout(function() { + if (!immediate) { + self.run.apply(self, args); + } + index = findDebouncee(target, method); + if (index) { + debouncees.splice(index, 1); + } + }, wait); + + if (immediate && index === -1) { + self.run.apply(self, args); + } + + debouncees.push([target, method, timer]); + }, + + cancelTimers: function() { + var i, len; + + for (i = 0, len = throttlers.length; i < len; i++) { + clearTimeout(throttlers[i][2]); + } + throttlers = []; + + for (i = 0, len = debouncees.length; i < len; i++) { + clearTimeout(debouncees[i][2]); + } + debouncees = []; + + if (laterTimer) { + clearTimeout(laterTimer); + laterTimer = null; + } + timers = []; + + if (autorun) { + clearTimeout(autorun); + autorun = null; + } + }, + + hasTimers: function() { + return !!timers.length || autorun; + }, + + cancel: function(timer) { + if (timer && typeof timer === 'object' && timer.queue && timer.method) { // we're cancelling a deferOnce + return timer.queue.cancel(timer); + } else if (typeof timer === 'function') { // we're cancelling a setTimeout + for (var i = 0, l = timers.length; i < l; i += 2) { + if (timers[i + 1] === timer) { + timers.splice(i, 2); // remove the two elements + return true; + } + } + } else { + return; // timer was null or not a timer + } + } + }; + + Backburner.prototype.schedule = Backburner.prototype.defer; + Backburner.prototype.scheduleOnce = Backburner.prototype.deferOnce; + Backburner.prototype.later = Backburner.prototype.setTimeout; + + function createAutorun(backburner) { + backburner.begin(); + autorun = global.setTimeout(function() { + backburner.end(); + autorun = null; + }); + } + + function executeTimers(self) { + var now = +new Date(), + time, fns, i, l; + + self.run(function() { + // TODO: binary search + for (i = 0, l = timers.length; i < l; i += 2) { + time = timers[i]; + if (time > now) { break; } + } + + fns = timers.splice(0, i); + + for (i = 1, l = fns.length; i < l; i += 2) { + self.schedule(self.options.defaultQueue, null, fns[i]); + } + }); + + if (timers.length) { + laterTimer = global.setTimeout(function() { + executeTimers(self); + laterTimer = null; + laterTimerExpiresAt = null; + }, timers[0] - now); + laterTimerExpiresAt = timers[0]; } } - return this; - } + function findDebouncee(target, method) { + var debouncee, + index = -1; + for (var i = 0, l = debouncees.length; i < l; i++) { + debouncee = debouncees[i]; + if (debouncee[0] === target && debouncee[1] === method) { + index = i; + break; + } + } + + return index; + } + + + __exports__.Backburner = Backburner; + }); +})(); + + + +(function() { +var onBegin = function(current) { + Ember.run.currentRunLoop = current; }; -Ember.RunLoop = RunLoop; +var onEnd = function(current, next) { + Ember.run.currentRunLoop = next; +}; + +var Backburner = requireModule('backburner').Backburner, + backburner = new Backburner(['sync', 'actions', 'destroy'], { + sync: { + before: Ember.beginPropertyChanges, + after: Ember.endPropertyChanges + }, + defaultQueue: 'actions', + onBegin: onBegin, + onEnd: onEnd + }), + slice = [].slice; // .......................................................... // Ember.run - this is ideally the only public API the dev sees @@ -4684,20 +5168,76 @@ Ember.RunLoop = RunLoop; @return {Object} return value from invoking the passed function. */ Ember.run = function(target, method) { - var args = arguments; - run.begin(); + var ret; - function tryable() { - if (target || method) { - return invoke(target, method, args, 2); + if (Ember.onerror) { + try { + ret = backburner.run.apply(backburner, arguments); + } catch (e) { + Ember.onerror(e); } + } else { + ret = backburner.run.apply(backburner, arguments); } - return Ember.tryFinally(tryable, run.end); + return ret; }; +/** + + If no run-loop is present, it creates a new one. If a run loop is + present it will queue itself to run on the existing run-loops action + queue. + + Please note: This is not for normal usage, and should be used sparingly. + + If invoked when not within a run loop: + + ```javascript + Ember.run.join(function(){ + // creates a new run-loop + }); + ``` + + Alternatively, if called within an existing run loop: + + ```javascript + Ember.run(function(){ + // creates a new run-loop + Ember.run.join(function(){ + // joins with the existing run-loop, and queues for invocation on + // the existing run-loops action queue. + }); + }); + ``` + + @method join + @namespace Ember + @param {Object} [target] target of method to call + @param {Function|String} method Method to invoke. + May be a function or a string. If you pass a string + then it will be looked up on the passed target. + @param {Object} [args*] Any additional arguments you wish to pass to the method. + @return {Object} return value from invoking the passed function. Please note, + when called within an existing loop, no return value is possible. +*/ +Ember.run.join = function(target, method) { + if (!Ember.run.currentRunLoop) { + return Ember.run.apply(Ember.run, arguments); + } + + var args = slice.call(arguments); + args.unshift('actions'); + Ember.run.schedule.apply(Ember.run, args); +}; + +Ember.run.backburner = backburner; + var run = Ember.run; +Ember.run.currentRunLoop = null; + +Ember.run.queues = backburner.queueNames; /** Begins a new RunLoop. Any deferred actions invoked after the begin will @@ -4714,7 +5254,7 @@ var run = Ember.run; @return {void} */ Ember.run.begin = function() { - run.currentRunLoop = new RunLoop(run.currentRunLoop); + backburner.begin(); }; /** @@ -4732,12 +5272,7 @@ Ember.run.begin = function() { @return {void} */ Ember.run.end = function() { - Ember.assert('must have a current run loop', run.currentRunLoop); - - function tryable() { run.currentRunLoop.end(); } - function finalizer() { run.currentRunLoop = run.currentRunLoop.prev(); } - - Ember.tryFinally(tryable, finalizer); + backburner.end(); }; /** @@ -4750,7 +5285,6 @@ Ember.run.end = function() { @type Array @default ['sync', 'actions', 'destroy'] */ -Ember.run.queues = ['sync', 'actions', 'destroy']; /** Adds the passed target/method and any optional arguments to the named @@ -4789,57 +5323,18 @@ Ember.run.queues = ['sync', 'actions', 'destroy']; @return {void} */ Ember.run.schedule = function(queue, target, method) { - var loop = run.autorun(); - loop.schedule.apply(loop, arguments); + checkAutoRun(); + backburner.schedule.apply(backburner, arguments); }; -var scheduledAutorun; -function autorun() { - scheduledAutorun = null; - if (run.currentRunLoop) { run.end(); } -} - // Used by global test teardown Ember.run.hasScheduledTimers = function() { - return !!(scheduledAutorun || scheduledLater); + return backburner.hasTimers(); }; // Used by global test teardown Ember.run.cancelTimers = function () { - if (scheduledAutorun) { - clearTimeout(scheduledAutorun); - scheduledAutorun = null; - } - if (scheduledLater) { - clearTimeout(scheduledLater); - scheduledLater = null; - } - timers = {}; -}; - -/** - Begins a new RunLoop if necessary and schedules a timer to flush the - RunLoop at a later time. This method is used by parts of Ember to - ensure the RunLoop always finishes. You normally do not need to call this - method directly. Instead use `Ember.run()` - - @method autorun - @example - Ember.run.autorun(); - @return {Ember.RunLoop} the new current RunLoop -*/ -Ember.run.autorun = function() { - if (!run.currentRunLoop) { - Ember.assert("You have turned on testing mode, which disabled the run-loop's autorun. You will need to wrap any code with asynchronous side-effects in an Ember.run", !Ember.testing); - - run.begin(); - - if (!scheduledAutorun) { - scheduledAutorun = setTimeout(autorun, 1); - } - } - - return run.currentRunLoop; + backburner.cancelTimers(); }; /** @@ -4859,59 +5354,11 @@ Ember.run.autorun = function() { @return {void} */ Ember.run.sync = function() { - run.autorun(); - run.currentRunLoop.flush('sync'); + if (backburner.currentInstance) { + backburner.currentInstance.queues.sync.flush(); + } }; -// .......................................................... -// TIMERS -// - -var timers = {}; // active timers... - -function sortByExpires(timerA, timerB) { - var a = timerA.expires, - b = timerB.expires; - - if (a > b) { return 1; } - if (a < b) { return -1; } - return 0; -} - -var scheduledLater, scheduledLaterExpires; -function invokeLaterTimers() { - scheduledLater = null; - run(function() { - var now = (+ new Date()), earliest = -1; - var timersToBeInvoked = []; - for (var key in timers) { - if (!timers.hasOwnProperty(key)) { continue; } - var timer = timers[key]; - if (timer && timer.expires) { - if (now >= timer.expires) { - delete timers[key]; - timersToBeInvoked.push(timer); - } else { - if (earliest < 0 || (timer.expires < earliest)) { earliest = timer.expires; } - } - } - } - - forEach.call(timersToBeInvoked.sort(sortByExpires), function(timer) { - invoke(timer.target, timer.method, timer.args, 2); - }); - - // schedule next timeout to fire when the earliest timer expires - if (earliest > 0) { - // To allow overwrite `setTimeout` as stub from test code. - // The assignment to `window.setTimeout` doesn't equal to `setTimeout` in older IE. - // So `window` is required. - scheduledLater = window.setTimeout(invokeLaterTimers, earliest - now); - scheduledLaterExpires = earliest; - } - }); -} - /** Invokes the passed target/method and optional arguments after a specified period if time. The last parameter of this method must always be a number @@ -4936,77 +5383,12 @@ function invokeLaterTimers() { @param {Object} [args*] Optional arguments to pass to the timeout. @param {Number} wait Number of milliseconds to wait. @return {String} a string you can use to cancel the timer in - {{#crossLink "Ember/run.cancel"}}{{/crossLink}} later. + `Ember.run.cancel` later. */ Ember.run.later = function(target, method) { - var args, expires, timer, guid, wait; - - // setTimeout compatibility... - if (arguments.length===2 && 'function' === typeof target) { - wait = method; - method = target; - target = undefined; - args = [target, method]; - } else { - args = slice.call(arguments); - wait = args.pop(); - } - - expires = (+ new Date()) + wait; - timer = { target: target, method: method, expires: expires, args: args }; - guid = Ember.guidFor(timer); - timers[guid] = timer; - - if(scheduledLater && expires < scheduledLaterExpires) { - // Cancel later timer (then reschedule earlier timer below) - clearTimeout(scheduledLater); - scheduledLater = null; - } - - if (!scheduledLater) { - // Schedule later timers to be run. - scheduledLater = setTimeout(invokeLaterTimers, wait); - scheduledLaterExpires = expires; - } - - return guid; + return backburner.later.apply(backburner, arguments); }; -function invokeOnceTimer(guid, onceTimers) { - if (onceTimers[this.tguid]) { delete onceTimers[this.tguid][this.mguid]; } - if (timers[guid]) { invoke(this.target, this.method, this.args); } - delete timers[guid]; -} - -function scheduleOnce(queue, target, method, args) { - var tguid = Ember.guidFor(target), - mguid = Ember.guidFor(method), - onceTimers = run.autorun().onceTimers, - guid = onceTimers[tguid] && onceTimers[tguid][mguid], - timer; - - if (guid && timers[guid]) { - timers[guid].args = args; // replace args - } else { - timer = { - target: target, - method: method, - args: args, - tguid: tguid, - mguid: mguid - }; - - guid = Ember.guidFor(timer); - timers[guid] = timer; - if (!onceTimers[tguid]) { onceTimers[tguid] = {}; } - onceTimers[tguid][mguid] = guid; // so it isn't scheduled more than once - - run.schedule(queue, timer, invokeOnceTimer, guid, onceTimers); - } - - return guid; -} - /** Schedule a function to run one time during the current RunLoop. This is equivalent to calling `scheduleOnce` with the "actions" queue. @@ -5020,7 +5402,10 @@ function scheduleOnce(queue, target, method, args) { @return {Object} timer */ Ember.run.once = function(target, method) { - return scheduleOnce('actions', target, method, slice.call(arguments, 2)); + checkAutoRun(); + var args = slice.call(arguments); + args.unshift('actions'); + return backburner.scheduleOnce.apply(backburner, args); }; /** @@ -5037,7 +5422,7 @@ Ember.run.once = function(target, method) { var sayHi = function() { console.log('hi'); } Ember.run.scheduleOnce('afterRender', myContext, sayHi); Ember.run.scheduleOnce('afterRender', myContext, sayHi); - // doFoo will only be executed once, in the afterRender queue of the RunLoop + // sayHi will only be executed once, in the afterRender queue of the RunLoop }); ``` @@ -5068,12 +5453,13 @@ Ember.run.once = function(target, method) { @return {Object} timer */ Ember.run.scheduleOnce = function(queue, target, method) { - return scheduleOnce(queue, target, method, slice.call(arguments, 3)); + checkAutoRun(); + return backburner.scheduleOnce.apply(backburner, arguments); }; /** - Schedules an item to run from within a separate run loop, after - control has been returned to the system. This is equivalent to calling + Schedules an item to run from within a separate run loop, after + control has been returned to the system. This is equivalent to calling `Ember.run.later` with a wait time of 1ms. ```javascript @@ -5085,7 +5471,7 @@ Ember.run.scheduleOnce = function(queue, target, method) { Multiple operations scheduled with `Ember.run.next` will coalesce into the same later run loop, along with any other operations scheduled by `Ember.run.later` that expire right around the same - time that `Ember.run.next` operations will fire. + time that `Ember.run.next` operations will fire. Note that there are often alternatives to using `Ember.run.next`. For instance, if you'd like to schedule an operation to happen @@ -5111,13 +5497,13 @@ Ember.run.scheduleOnce = function(queue, target, method) { One benefit of the above approach compared to using `Ember.run.next` is that you will be able to perform DOM/CSS operations before unprocessed - elements are rendered to the screen, which may prevent flickering or + elements are rendered to the screen, which may prevent flickering or other artifacts caused by delaying processing until after rendering. - The other major benefit to the above approach is that `Ember.run.next` - introduces an element of non-determinism, which can make things much - harder to test, due to its reliance on `setTimeout`; it's much harder - to guarantee the order of scheduled operations when they are scheduled + The other major benefit to the above approach is that `Ember.run.next` + introduces an element of non-determinism, which can make things much + harder to test, due to its reliance on `setTimeout`; it's much harder + to guarantee the order of scheduled operations when they are scheduled outside of the current run loop, i.e. with `Ember.run.next`. @method next @@ -5130,8 +5516,8 @@ Ember.run.scheduleOnce = function(queue, target, method) { */ Ember.run.next = function() { var args = slice.call(arguments); - args.push(1); // 1 millisecond wait - return run.later.apply(this, args); + args.push(1); + return backburner.later.apply(backburner, args); }; /** @@ -5160,9 +5546,93 @@ Ember.run.next = function() { @return {void} */ Ember.run.cancel = function(timer) { - delete timers[timer]; + return backburner.cancel(timer); }; +/** + Delay calling the target method until the debounce period has elapsed + with no additional debounce calls. If `debounce` is called again before + the specified time has elapsed, the timer is reset and the entire period + must pass again before the target method is called. + + This method should be used when an event may be called multiple times + but the action should only be called once when the event is done firing. + A common example is for scroll events where you only want updates to + happen once scrolling has ceased. + + ```javascript + var myFunc = function() { console.log(this.name + ' ran.'); }; + var myContext = {name: 'debounce'}; + + Ember.run.debounce(myContext, myFunc, 150); + + // less than 150ms passes + + Ember.run.debounce(myContext, myFunc, 150); + + // 150ms passes + // myFunc is invoked with context myContext + // console logs 'debounce ran.' one time. + ``` + + @method debounce + @param {Object} [target] target of method to invoke + @param {Function|String} method The method to invoke. + May be a function or a string. If you pass a string + then it will be looked up on the passed target. + @param {Object} [args*] Optional arguments to pass to the timeout. + @param {Number} wait Number of milliseconds to wait. + @param {Boolean} immediate Trigger the function on the leading instead of the trailing edge of the wait interval. + @return {void} +*/ +Ember.run.debounce = function() { + return backburner.debounce.apply(backburner, arguments); +}; + +/** + Ensure that the target method is never called more frequently than + the specified spacing period. + + ```javascript + var myFunc = function() { console.log(this.name + ' ran.'); }; + var myContext = {name: 'throttle'}; + + Ember.run.throttle(myContext, myFunc, 150); + + // 50ms passes + Ember.run.throttle(myContext, myFunc, 150); + + // 50ms passes + Ember.run.throttle(myContext, myFunc, 150); + + // 50ms passes + Ember.run.throttle(myContext, myFunc, 150); + + // 150ms passes + // myFunc is invoked with context myContext + // console logs 'throttle ran.' twice, 150ms apart. + ``` + + @method throttle + @param {Object} [target] target of method to invoke + @param {Function|String} method The method to invoke. + May be a function or a string. If you pass a string + then it will be looked up on the passed target. + @param {Object} [args*] Optional arguments to pass to the timeout. + @param {Number} spacing Number of milliseconds to space out requests. + @return {void} +*/ +Ember.run.throttle = function() { + return backburner.throttle.apply(backburner, arguments); +}; + +// Make sure it's not an autorun during testing +function checkAutoRun() { + if (!Ember.run.currentRunLoop) { + Ember.assert("You have turned on testing mode, which disabled the run-loop's autorun. You will need to wrap any code with asynchronous side-effects in an Ember.run", !Ember.testing); + } +} + })(); @@ -5447,7 +5917,7 @@ function mixinProperties(to, from) { mixinProperties(Binding, { /** - See {{#crossLink "Ember.Binding/from"}}{{/crossLink}} + See `Ember.Binding.from`. @method from @static @@ -5458,7 +5928,7 @@ mixinProperties(Binding, { }, /** - See {{#crossLink "Ember.Binding/to"}}{{/crossLink}} + See `Ember.Binding.to`. @method to @static @@ -5475,7 +5945,7 @@ mixinProperties(Binding, { This means that if you change the "to" side directly, the "from" side may have a different value. - See {{#crossLink "Binding/oneWay"}}{{/crossLink}} + See `Binding.oneWay`. @method oneWay @param {String} from from path. @@ -5536,7 +6006,7 @@ mixinProperties(Binding, { You should consider using one way bindings anytime you have an object that may be created frequently and you do not intend to change a property; only - to monitor it for changes. (such as in the example above). + to monitor it for changes (such as in the example above). ## Adding Bindings Manually @@ -6295,6 +6765,29 @@ Ember.immediateObserver = function() { }; /** + When observers fire, they are called with the arguments `obj`, `keyName` + and `value`. In a typical observer, value is the new, post-change value. + + A `beforeObserver` fires before a property changes. The `value` argument contains + the pre-change value. + + A `beforeObserver` is an alternative form of `.observesBefore()`. + + ```javascript + App.PersonView = Ember.View.extend({ + valueWillChange: function (obj, keyName, value) { + this.changingFrom = value; + }.observesBefore('content.value'), + valueDidChange: function(obj, keyName, value) { + // only run if updating a value already in the DOM + if(this.get('state') === 'inDOM') { + var color = value > this.changingFrom ? 'green' : 'red'; + // logic + } + }.observes('content.value') + }); + ``` + @method beforeObserver @for Ember @param {Function} func @@ -6922,6 +7415,8 @@ define("rsvp", __exports__.reject = reject; }); + + })(); (function() { @@ -6929,12 +7424,43 @@ define("container", [], function() { + /** + A safe and simple inheriting object. + + @class InheritingDict + */ function InheritingDict(parent) { this.parent = parent; this.dict = {}; } InheritingDict.prototype = { + + /** + @property parent + @type InheritingDict + @default null + */ + + parent: null, + + /** + Object used to store the current nodes data. + + @property dict + @type Object + @default Object + */ + dict: null, + + /** + Retrieve the value given a key, if the value is present at the current + level use it, otherwise walk up the parent hierarchy and try again. If + no matching key is found, return undefined. + + @method get + @return {any} + */ get: function(key) { var dict = this.dict; @@ -6947,10 +7473,36 @@ define("container", } }, + /** + Set the given value for the given key, at the current level. + + @method set + @param {String} key + @param {Any} value + */ set: function(key, value) { this.dict[key] = value; }, + /** + Delete the given key + + @method remove + @param {String} key + */ + remove: function(key) { + delete this.dict[key]; + }, + + /** + Check for the existence of given a key, if the key is present at the current + level return true, otherwise walk up the parent hierarchy and try again. If + no matching key is found, return false. + + @method has + @param {String} key + @returns {Boolean} + */ has: function(key) { var dict = this.dict; @@ -6965,6 +7517,13 @@ define("container", return false; }, + /** + Iterate and invoke a callback for each local key-value pair. + + @method eachLocal + @param {Function} callback + @param {Object} binding + */ eachLocal: function(callback, binding) { var dict = this.dict; @@ -6976,6 +7535,11 @@ define("container", } }; + /** + A lightweight container that helps to assemble and decouple components. + + @class Container + */ function Container(parent) { this.parent = parent; this.children = []; @@ -6990,16 +7554,115 @@ define("container", } Container.prototype = { + + /** + @property parent + @type Container + @default null + */ + parent: null, + + /** + @property children + @type Array + @default [] + */ + children: null, + + /** + @property resolver + @type function + */ + resolver: null, + + /** + @property registry + @type InheritingDict + */ + registry: null, + + /** + @property cache + @type InheritingDict + */ + cache: null, + + /** + @property typeInjections + @type InheritingDict + */ + typeInjections: null, + + /** + @property injections + @type Object + @default {} + */ + injections: null, + + /** + @private + + @property _options + @type InheritingDict + @default null + */ + _options: null, + + /** + @private + + @property _typeOptions + @type InheritingDict + */ + _typeOptions: null, + + /** + Returns a new child of the current container. These children are configured + to correctly inherit from the current container. + + @method child + @returns {Container} + */ child: function() { var container = new Container(this); this.children.push(container); return container; }, + /** + Sets a key-value pair on the current container. If a parent container, + has the same key, once set on a child, the parent and child will diverge + as expected. + + @method set + @param {Object} obkect + @param {String} key + @param {any} value + */ set: function(object, key, value) { object[key] = value; }, + /** + Registers a factory for later injection. + + Example: + + ```javascript + var container = new Container(); + + container.register('model:user', Person, {singleton: false }); + container.register('fruit:favorite', Orange); + container.register('communication:main', Email, {singleton: false}); + ``` + + @method register + @param {String} type + @param {String} name + @param {Function} factory + @param {Object} options + */ register: function(type, name, factory, options) { var fullName; @@ -7018,14 +7681,115 @@ define("container", this._options.set(normalizedName, options || {}); }, + /** + Unregister a fullName + + ```javascript + var container = new Container(); + container.register('model:user', User); + + container.lookup('model:user') instanceof User //=> true + + container.unregister('model:user') + container.lookup('model:user') === undefined //=> true + + @method unregister + @param {String} fullName + */ + unregister: function(fullName) { + var normalizedName = this.normalize(fullName); + + this.registry.remove(normalizedName); + this.cache.remove(normalizedName); + this._options.remove(normalizedName); + }, + + /** + Given a fullName return the corresponding factory. + + By default `resolve` will retrieve the factory from + its container's registry. + + ```javascript + var container = new Container(); + container.register('api:twitter', Twitter); + + container.resolve('api:twitter') // => Twitter + ``` + + Optionally the container can be provided with a custom resolver. + If provided, `resolve` will first provide the custom resolver + the oppertunity to resolve the fullName, otherwise it will fallback + to the registry. + + ```javascript + var container = new Container(); + container.resolver = function(fullName) { + // lookup via the module system of choice + }; + + // the twitter factory is added to the module system + container.resolve('api:twitter') // => Twitter + ``` + + @method resolve + @param {String} fullName + @returns {Function} fullName's factory + */ resolve: function(fullName) { return this.resolver(fullName) || this.registry.get(fullName); }, + /** + A hook to enable custom fullName normalization behaviour + + @method normalize + @param {String} fullName + @return {string} normalized fullName + */ normalize: function(fullName) { return fullName; }, + /** + Given a fullName return a corresponding instance. + + The default behaviour is for lookup to return a singleton instance. + The singleton is scoped to the container, allowing multiple containers + to all have there own locally scoped singletons. + + ```javascript + var container = new Container(); + container.register('api:twitter', Twitter); + + var twitter = container.lookup('api:twitter'); + + twitter instanceof Twitter; // => true + + // by default the container will return singletons + twitter2 = container.lookup('api:twitter'); + twitter instanceof Twitter; // => true + + twitter === twitter2; //=> true + ``` + + If singletons are not wanted an optional flag can be provided at lookup. + + ```javascript + var container = new Container(); + container.register('api:twitter', Twitter); + + var twitter = container.lookup('api:twitter', { singleton: false }); + var twitter2 = container.lookup('api:twitter', { singleton: false }); + + twitter === twitter2; //=> false + ``` + + @method lookup + @param {String} fullName + @param {Object} options + @return {any} + */ lookup: function(fullName, options) { fullName = this.normalize(fullName); @@ -7046,6 +7810,25 @@ define("container", return value; }, + /** + Given a fullName return the corresponding factory. + + @method lookupFactory + @param {String} fullName + @return {any} + */ + lookupFactory: function(fullName) { + return factoryFor(this, fullName); + }, + + /** + Given a fullName check if the container is aware of its factory + or singleton instance. + + @method has + @param {String} fullName + @return {Boolean} + */ has: function(fullName) { if (this.cache.has(fullName)) { return true; @@ -7054,27 +7837,144 @@ define("container", return !!factoryFor(this, fullName); }, + /** + Allow registerying options for all factories of a type. + + ```javascript + var container = new Container(); + + // if all of type `connection` must not be singletons + container.optionsForType('connection', { singleton: false }); + + container.register('connection:twitter', TwitterConnection); + container.register('connection:facebook', FacebookConnection); + + var twitter = container.lookup('connection:twitter'); + var twitter2 = container.lookup('connection:twitter'); + + twitter === twitter2; // => false + + var facebook = container.lookup('connection:facebook'); + var facebook2 = container.lookup('connection:facebook'); + + facebook === facebook2; // => false + ``` + + @method optionsForType + @param {String} type + @param {Object} options + */ optionsForType: function(type, options) { if (this.parent) { illegalChildOperation('optionsForType'); } this._typeOptions.set(type, options); }, + /** + @method options + @param {String} type + @param {Object} options + */ options: function(type, options) { this.optionsForType(type, options); }, + /* + @private + + Used only via `injection`. + + Provides a specialized form of injection, specifically enabling + all objects of one type to be injected with a reference to another + object. + + For example, provided each object of type `controller` needed a `router`. + one would do the following: + + ```javascript + var container = new Container(); + + container.register('router:main', Router); + container.register('controller:user', UserController); + container.register('controller:post', PostController); + + container.typeInjection('controller', 'router', 'router:main'); + + var user = container.lookup('controller:user'); + var post = container.lookup('controller:post'); + + user.router instanceof Router; //=> true + post.router instanceof Router; //=> true + + // both controllers share the same router + user.router === post.router; //=> true + ``` + + @method typeInjection + @param {String} type + @param {String} property + @param {String} fullName + */ typeInjection: function(type, property, fullName) { if (this.parent) { illegalChildOperation('typeInjection'); } var injections = this.typeInjections.get(type); + if (!injections) { injections = []; this.typeInjections.set(type, injections); } - injections.push({ property: property, fullName: fullName }); + + injections.push({ + property: property, + fullName: fullName + }); }, + /* + Defines injection rules. + + These rules are used to inject dependencies onto objects when they + are instantiated. + + Two forms of injections are possible: + + * Injecting one fullName on another fullName + * Injecting one fullName on a type + + Example: + + ```javascript + var container = new Container(); + + container.register('source:main', Source); + container.register('model:user', User); + container.register('model:post', PostController); + + // injecting one fullName on another fullName + // eg. each user model gets a post model + container.injection('model:user', 'post', 'model:post'); + + // injecting one fullName on another type + container.injection('model', 'source', 'source:main'); + + var user = container.lookup('model:user'); + var post = container.lookup('model:post'); + + user.source instanceof Source; //=> true + post.source instanceof Source; //=> true + + user.post instanceof Post; //=> true + + // and both models share the same source + user.source === post.source; //=> true + ``` + + @method injection + @param {String} factoryName + @param {String} property + @param {String} injectionName + */ injection: function(factoryName, property, injectionName) { if (this.parent) { illegalChildOperation('injection'); } @@ -7086,6 +7986,12 @@ define("container", injections.push({ property: property, fullName: injectionName }); }, + /** + A depth first traversal, destroying the container, its descendant containers and all + their managed objects. + + @method destroy + */ destroy: function() { this.isDestroyed = true; @@ -7095,10 +8001,6 @@ define("container", this.children = []; - eachDestroyable(this, function(item) { - item.isDestroying = true; - }); - eachDestroyable(this, function(item) { item.destroy(); }); @@ -7107,6 +8009,9 @@ define("container", this.isDestroyed = true; }, + /** + @method reset + */ reset: function() { for (var i=0, l=this.children.length; i1) args = a_slice.call(arguments, 1); this.forEach(function(x, idx) { @@ -8678,7 +9591,7 @@ Ember.Enumerable = Ember.Mixin.create({ @return {Array} the enumerable as an array. */ toArray: function() { - var ret = Ember.A([]); + var ret = Ember.A(); this.forEach(function(o, idx) { ret[idx] = o; }); return ret ; }, @@ -8714,7 +9627,7 @@ Ember.Enumerable = Ember.Mixin.create({ */ without: function(value) { if (!this.contains(value)) return this; // nothing to do - var ret = Ember.A([]); + var ret = Ember.A(); this.forEach(function(k) { if (k !== value) ret[ret.length] = k; }) ; @@ -8734,7 +9647,7 @@ Ember.Enumerable = Ember.Mixin.create({ @return {Ember.Enumerable} */ uniq: function() { - var ret = Ember.A([]); + var ret = Ember.A(); this.forEach(function(k){ if (a_indexOf(ret, k)<0) ret.push(k); }); @@ -8928,7 +9841,7 @@ var get = Ember.get, set = Ember.set, isNone = Ember.isNone, map = Ember.Enumera You can use the methods defined in this module to access and modify array contents in a KVO-friendly way. You can also be notified whenever the - membership if an array changes by changing the syntax of the property to + membership of an array changes by changing the syntax of the property to `.observes('*myProperty.[]')`. To support `Ember.Array` in your own class, you must override two @@ -8945,9 +9858,6 @@ var get = Ember.get, set = Ember.set, isNone = Ember.isNone, map = Ember.Enumera */ Ember.Array = Ember.Mixin.create(Ember.Enumerable, /** @scope Ember.Array.prototype */ { - // compatibility - isSCArray: true, - /** Your array must support the `length` property. Your replace methods should set this property whenever it changes. @@ -9053,7 +9963,7 @@ Ember.Array = Ember.Mixin.create(Ember.Enumerable, /** @scope Ember.Array.protot @return {Array} New array with specified slice */ slice: function(beginIndex, endIndex) { - var ret = Ember.A([]); + var ret = Ember.A(); var length = get(this, 'length') ; if (isNone(beginIndex)) beginIndex = 0 ; if (isNone(endIndex) || (endIndex > length)) endIndex = length ; @@ -9141,15 +10051,15 @@ Ember.Array = Ember.Mixin.create(Ember.Enumerable, /** @scope Ember.Array.protot Adds an array observer to the receiving array. The array observer object normally must implement two methods: - * `arrayWillChange(start, removeCount, addCount)` - This method will be + * `arrayWillChange(observedObj, start, removeCount, addCount)` - This method will be called just before the array is modified. - * `arrayDidChange(start, removeCount, addCount)` - This method will be + * `arrayDidChange(observedObj, start, removeCount, addCount)` - This method will be called just after the array is modified. - Both callbacks will be passed the starting index of the change as well a - a count of the items to be removed and added. You can use these callbacks - to optionally inspect the array during the change, clear caches, or do - any other bookkeeping necessary. + Both callbacks will be passed the observed object, starting index of the + change as well a a count of the items to be removed and added. You can use + these callbacks to optionally inspect the array during the change, clear + caches, or do any other bookkeeping necessary. In addition to passing a target, you can also include an options hash which you can use to override the method names that will be invoked on the @@ -9404,8 +10314,7 @@ var get = Ember.get, set = Ember.set; @extends Ember.Mixin @since Ember 0.9 */ -Ember.Copyable = Ember.Mixin.create( -/** @scope Ember.Copyable.prototype */ { +Ember.Copyable = Ember.Mixin.create(/** @scope Ember.Copyable.prototype */ { /** Override to return a copy of the receiver. Default implementation raises @@ -9510,8 +10419,7 @@ var get = Ember.get, set = Ember.set; @extends Ember.Mixin @since Ember 0.9 */ -Ember.Freezable = Ember.Mixin.create( -/** @scope Ember.Freezable.prototype */ { +Ember.Freezable = Ember.Mixin.create(/** @scope Ember.Freezable.prototype */ { /** Set to `true` when the object is frozen. Use this property to detect @@ -9692,8 +10600,7 @@ var get = Ember.get, set = Ember.set; @uses Ember.Array @uses Ember.MutableEnumerable */ -Ember.MutableArray = Ember.Mixin.create(Ember.Array, Ember.MutableEnumerable, - /** @scope Ember.MutableArray.prototype */ { +Ember.MutableArray = Ember.Mixin.create(Ember.Array, Ember.MutableEnumerable,/** @scope Ember.MutableArray.prototype */ { /** __Required.__ You must implement this method to apply this mixin. @@ -9813,7 +10720,7 @@ Ember.MutableArray = Ember.Mixin.create(Ember.Array, Ember.MutableEnumerable, ```javascript var colors = ["red", "green", "blue"]; - colors.pushObjects("black"); // ["red", "green", "blue", "black"] + colors.pushObjects(["black"]); // ["red", "green", "blue", "black"] colors.pushObjects(["yellow", "orange"]); // ["red", "green", "blue", "black", "yellow", "orange"] ``` @@ -9822,6 +10729,9 @@ Ember.MutableArray = Ember.Mixin.create(Ember.Array, Ember.MutableEnumerable, @return {Ember.Array} receiver */ pushObjects: function(objects) { + if(!(Ember.Enumerable.detect(objects) || Ember.isArray(objects))) { + throw new TypeError("Must pass Ember.Enumerable to Ember.MutableArray#pushObjects"); + } this.replace(get(this, 'length'), 0, objects); return this; }, @@ -9964,7 +10874,6 @@ Ember.MutableArray = Ember.Mixin.create(Ember.Array, Ember.MutableEnumerable, }); - })(); @@ -10292,8 +11201,8 @@ Ember.Observable = Ember.Mixin.create(/** @scope Ember.Observable.prototype */ { This is the core method used to register an observer for a property. - Once you call this method, anytime the key's value is set, your observer - will be notified. Note that the observers are triggered anytime the + Once you call this method, any time the key's value is set, your observer + will be notified. Note that the observers are triggered any time the value is set, regardless of whether it has actually changed. Your observer should be prepared to handle that. @@ -10483,7 +11392,6 @@ Ember.Observable = Ember.Mixin.create(/** @scope Ember.Observable.prototype */ { } }); - })(); @@ -10746,7 +11654,7 @@ Ember.Evented = Ember.Mixin.create({ }, /** - Cancels subscription for give name, target, and method. + Cancels subscription for given name, target, and method. @method off @param {String} name The name of the event @@ -10809,15 +11717,15 @@ Ember.DeferredMixin = Ember.Mixin.create({ deferred = get(this, '_deferred'); promise = deferred.promise; - return promise.then(function(fulfillment) { + function fulfillmentHandler(fulfillment) { if (fulfillment === promise) { return resolve(entity); } else { return resolve(fulfillment); } - }, function(reason) { - return reject(reason); - }); + } + + return promise.then(resolve && fulfillmentHandler, reject); }, /** @@ -11161,21 +12069,23 @@ CoreObject.PrototypeMixin = Mixin.create({ raised. Note that destruction is scheduled for the end of the run loop and does not - happen immediately. + happen immediately. It will set an isDestroying flag immediately. @method destroy @return {Ember.Object} receiver */ destroy: function() { - if (this._didCallDestroy) { return; } - + if (this.isDestroying) { return; } this.isDestroying = true; - this._didCallDestroy = true; + schedule('actions', this, this.willDestroy); schedule('destroy', this, this._scheduledDestroy); return this; }, + /** + Override to implement teardown. + */ willDestroy: Ember.K, /** @@ -11187,10 +12097,9 @@ CoreObject.PrototypeMixin = Mixin.create({ @method _scheduledDestroy */ _scheduledDestroy: function() { - if (this.willDestroy) { this.willDestroy(); } + if (this.isDestroyed) { return; } destroy(this); this.isDestroyed = true; - if (this.didDestroy) { this.didDestroy(); } }, bind: function(to, from) { @@ -11681,8 +12590,7 @@ var get = Ember.get, set = Ember.set; @extends Ember.Object @uses Ember.MutableArray */ -Ember.ArrayProxy = Ember.Object.extend(Ember.MutableArray, -/** @scope Ember.ArrayProxy.prototype */ { +Ember.ArrayProxy = Ember.Object.extend(Ember.MutableArray,/** @scope Ember.ArrayProxy.prototype */ { /** The content array. Must be an object that implements `Ember.Array` and/or @@ -11911,6 +12819,9 @@ Ember.ArrayProxy = Ember.Object.extend(Ember.MutableArray, }, pushObjects: function(objects) { + if(!(Ember.Enumerable.detect(objects) || Ember.isArray(objects))) { + throw new TypeError("Must pass Ember.Enumerable to Ember.MutableArray#pushObjects"); + } this._replace(get(this, 'length'), 0, objects); return this; }, @@ -11958,7 +12869,6 @@ Ember.ArrayProxy = Ember.Object.extend(Ember.MutableArray, } }); - })(); @@ -12058,8 +12968,7 @@ function contentPropertyDidChange(content, contentKey) { @namespace Ember @extends Ember.Object */ -Ember.ObjectProxy = Ember.Object.extend( -/** @scope Ember.ObjectProxy.prototype */ { +Ember.ObjectProxy = Ember.Object.extend(/** @scope Ember.ObjectProxy.prototype */ { /** The object whose properties will be forwarded. @@ -13164,17 +14073,40 @@ Ember.SortableMixin = Ember.Mixin.create(Ember.MutableEnumerable, { @property {Boolean} sortAscending */ sortAscending: true, + + /** + The function used to compare two values. You can override this if you + want to do custom comparisons.Functions must be of the type expected by + Array#sort, i.e. + return 0 if the two parameters are equal, + return a negative value if the first parameter is smaller than the second or + return a positive value otherwise: + ```javascript + function(x,y){ // These are assumed to be integers + if(x === y) + return 0; + return x < y ? -1 : 1; + } + ``` + + @property sortFunction + @type {Function} + @default Ember.compare + */ + sortFunction: Ember.compare, + orderBy: function(item1, item2) { var result = 0, sortProperties = get(this, 'sortProperties'), - sortAscending = get(this, 'sortAscending'); + sortAscending = get(this, 'sortAscending'), + sortFunction = get(this, 'sortFunction'); Ember.assert("you need to define `sortProperties`", !!sortProperties); forEach(sortProperties, function(propertyName) { if (result === 0) { - result = Ember.compare(get(item1, propertyName), get(item2, propertyName)); + result = sortFunction(get(item1, propertyName), get(item2, propertyName)); if ((result !== 0) && !sortAscending) { result = (-1) * result; } @@ -13612,7 +14544,7 @@ Ember Runtime */ var jQuery = Ember.imports.jQuery; -Ember.assert("Ember Views require jQuery 1.8, 1.9 or 2.0", jQuery && (jQuery().jquery.match(/^((1\.(8|9))|2.0)(\.\d+)?(pre|rc\d?)?/) || Ember.ENV.FORCE_JQUERY)); +Ember.assert("Ember Views require jQuery 1.7, 1.8, 1.9, 1.10, or 2.0", jQuery && (jQuery().jquery.match(/^((1\.(7|8|9|10))|2.0)(\.\d+)?(pre|rc\d?)?/) || Ember.ENV.FORCE_JQUERY)); /** Alias for jQuery @@ -13652,7 +14584,7 @@ if (Ember.$) { @submodule ember-views */ -/*** BEGIN METAMORPH HELPERS ***/ +/* BEGIN METAMORPH HELPERS */ // Internet Explorer prior to 9 does not allow setting innerHTML if the first element // is a "zero-scope" element. This problem can be worked around by making @@ -13725,7 +14657,7 @@ var setInnerHTMLWithoutFix = function(element, html) { } }; -/*** END METAMORPH HELPERS */ +/* END METAMORPH HELPERS */ var innerHTMLTags = {}; @@ -14308,8 +15240,48 @@ var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt; @private @extends Ember.Object */ -Ember.EventDispatcher = Ember.Object.extend( -/** @scope Ember.EventDispatcher.prototype */{ +Ember.EventDispatcher = Ember.Object.extend(/** @scope Ember.EventDispatcher.prototype */{ + + /** + The set of events names (and associated handler function names) to be setup + and dispatched by the `EventDispatcher`. Custom events can added to this list at setup + time, generally via the `Ember.Application.customEvents` hash. Only override this + default set to prevent the EventDispatcher from listening on some events all together. + + This set will be modified by `setup` to also include any events added at that time. + + @property events + @type Object + */ + events: { + touchstart : 'touchStart', + touchmove : 'touchMove', + touchend : 'touchEnd', + touchcancel : 'touchCancel', + keydown : 'keyDown', + keyup : 'keyUp', + keypress : 'keyPress', + mousedown : 'mouseDown', + mouseup : 'mouseUp', + contextmenu : 'contextMenu', + click : 'click', + dblclick : 'doubleClick', + mousemove : 'mouseMove', + focusin : 'focusIn', + focusout : 'focusOut', + mouseenter : 'mouseEnter', + mouseleave : 'mouseLeave', + submit : 'submit', + input : 'input', + change : 'change', + dragstart : 'dragStart', + drag : 'drag', + dragenter : 'dragEnter', + dragleave : 'dragLeave', + dragover : 'dragOver', + drop : 'drop', + dragend : 'dragEnd' + }, /** @private @@ -14342,35 +15314,7 @@ Ember.EventDispatcher = Ember.Object.extend( @param addedEvents {Hash} */ setup: function(addedEvents, rootElement) { - var event, events = { - touchstart : 'touchStart', - touchmove : 'touchMove', - touchend : 'touchEnd', - touchcancel : 'touchCancel', - keydown : 'keyDown', - keyup : 'keyUp', - keypress : 'keyPress', - mousedown : 'mouseDown', - mouseup : 'mouseUp', - contextmenu : 'contextMenu', - click : 'click', - dblclick : 'doubleClick', - mousemove : 'mouseMove', - focusin : 'focusIn', - focusout : 'focusOut', - mouseenter : 'mouseEnter', - mouseleave : 'mouseLeave', - submit : 'submit', - input : 'input', - change : 'change', - dragstart : 'dragStart', - drag : 'drag', - dragenter : 'dragEnter', - dragleave : 'dragLeave', - dragover : 'dragOver', - drop : 'drop', - dragend : 'dragEnd' - }; + var event, events = get(this, 'events'); Ember.$.extend(events, addedEvents || {}); @@ -14617,6 +15561,15 @@ Ember.warn("The VIEW_PRESERVES_CONTEXT flag has been removed and the functionali */ Ember.TEMPLATES = {}; +/** + `Ember.CoreView` is + + @class CoreView + @namespace Ember + @extends Ember.Object + @uses Ember.Evented +*/ + Ember.CoreView = Ember.Object.extend(Ember.Evented, { isView: true, @@ -15295,7 +16248,7 @@ class: eventManager: Ember.Object.create({ mouseEnter: function(event, view){ // view might be instance of either - // OutsideView or InnerView depending on + // OuterView or InnerView depending on // where on the page the user interaction occured } }) @@ -15320,8 +16273,10 @@ class: ### Event Names - Possible events names for any of the responding approaches described above - are: + All of the event handling approaches described above respond to the same set + of events. The names of the built-in events are listed below. (The hash of + built-in events exists in `Ember.EventDispatcher`.) Additional, custom events + can be registered by using `Ember.Application.customEvents`. Touch events: @@ -15374,8 +16329,7 @@ class: @class View @namespace Ember - @extends Ember.Object - @uses Ember.Evented + @extends Ember.CoreView */ Ember.View = Ember.CoreView.extend( /** @scope Ember.View.prototype */ { @@ -15556,7 +16510,7 @@ Ember.View = Ember.CoreView.extend( If a value that affects template rendering changes, the view should be re-rendered to reflect the new value. - @method _displayPropertyDidChange + @method _contextDidChange */ _contextDidChange: Ember.observer(function() { this.rerender(); @@ -15686,6 +16640,8 @@ Ember.View = Ember.CoreView.extend( _parentViewDidChange: Ember.observer(function() { if (this.isDestroying) { return; } + this.trigger('parentViewDidChange'); + if (get(this, 'parentView.controller') && !get(this, 'controller')) { this.notifyPropertyChange('controller'); } @@ -15957,9 +16913,9 @@ Ember.View = Ember.CoreView.extend( For example, calling `view.$('li')` will return a jQuery object containing all of the `li` elements inside the DOM element of this view. - @property $ + @method $ @param {String} [selector] a jQuery-compatible selector string - @return {jQuery} the CoreQuery object for the DOM node + @return {jQuery} the jQuery object for the DOM node */ $: function(sel) { return this.currentState.$(this, sel); @@ -16640,31 +17596,32 @@ Ember.View = Ember.CoreView.extend( @return {Ember.View} new instance */ createChildView: function(view, attrs) { - if (view.isView && view._parentView === this) { return view; } + if (view.isView && view._parentView === this && view.container === this.container) { + return view; + } + + attrs = attrs || {}; + attrs._parentView = this; + attrs.container = this.container; if (Ember.CoreView.detect(view)) { - attrs = attrs || {}; - attrs._parentView = this; - attrs.container = this.container; attrs.templateData = attrs.templateData || get(this, 'templateData'); view = view.create(attrs); // don't set the property on a virtual view, as they are invisible to // consumers of the view API - if (view.viewName) { set(get(this, 'concreteView'), view.viewName, view); } + if (view.viewName) { + set(get(this, 'concreteView'), view.viewName, view); + } } else { Ember.assert('You must pass instance or subclass of View', view.isView); - if (attrs) { - view.setProperties(attrs); - } + Ember.setProperties(view, attrs); if (!get(view, 'templateData')) { set(view, 'templateData', get(this, 'templateData')); } - - set(view, '_parentView', this); } return view; @@ -16961,7 +17918,7 @@ Ember.View.reopenClass({ // If the value is not false, undefined, or null, return the current // value of the property. - } else if (val !== false && val !== undefined && val !== null) { + } else if (val !== false && val != null) { return val; // Nothing to display. Return null so that the old class is removed @@ -17011,8 +17968,8 @@ Ember.View.applyAttributeBindings = function(elem, name, value) { elem.attr(name, value); } } else if (name === 'value' || type === 'boolean') { - // We can't set properties to undefined - if (value === undefined) { value = null; } + // We can't set properties to undefined or null + if (Ember.isNone(value)) { value = ''; } if (value !== elem.prop(name)) { // value and booleans should always be properties @@ -17609,6 +18566,8 @@ Ember.ContainerView = Ember.View.extend(Ember.MutableArray, { replace: function(idx, removedCount, addedViews) { var addedCount = addedViews ? get(addedViews, 'length') : 0; + var self = this; + Ember.assert("You can't add a child to a container that is already a child of another view", Ember.A(addedViews).every(function(item) { return !get(item, '_parentView') || get(item, '_parentView') === self; })); this.arrayContentWillChange(idx, removedCount, addedCount); this.childViewsWillChange(this._childViews, idx, removedCount); @@ -17710,6 +18669,7 @@ Ember.ContainerView = Ember.View.extend(Ember.MutableArray, { initializeViews: function(views, parentView, templateData) { forEach(views, function(view) { set(view, '_parentView', parentView); + set(view, 'container', parentView && parentView.container); if (!get(view, 'templateData')) { set(view, 'templateData', templateData); @@ -17729,6 +18689,7 @@ Ember.ContainerView = Ember.View.extend(Ember.MutableArray, { _currentViewDidChange: Ember.observer(function() { var currentView = get(this, 'currentView'); if (currentView) { + Ember.assert("You tried to set a current view that already has a parent. Make sure you don't have multiple outlets in the same view.", !get(currentView, '_parentView')); this.pushObject(currentView); } }, 'currentView'), @@ -17818,7 +18779,7 @@ var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt; /** `Ember.CollectionView` is an `Ember.View` descendent responsible for managing - a collection (an array or array-like object) by maintaing a child view object + a collection (an array or array-like object) by maintaining a child view object and associated DOM representation for each item in the array and ensuring that child views and their associated rendered HTML are updated when items in the array are added, removed, or replaced. @@ -17969,8 +18930,7 @@ var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt; @extends Ember.ContainerView @since Ember 0.9 */ -Ember.CollectionView = Ember.ContainerView.extend( -/** @scope Ember.CollectionView.prototype */ { +Ember.CollectionView = Ember.ContainerView.extend(/** @scope Ember.CollectionView.prototype */ { /** A list of items to be displayed by the `Ember.CollectionView`. @@ -18175,6 +19135,102 @@ Ember.CollectionView.CONTAINER_MAP = { +(function() { +/** +@module ember +@submodule ember-views +*/ + +/** + An `Ember.Component` is a view that is completely + isolated. Property access in its templates go + to the view object and actions are targeted at + the view object. There is no access to the + surrounding context or outer controller; all + contextual information is passed in. + + The easiest way to create an `Ember.Component` is via + a template. If you name a template + `components/my-foo`, you will be able to use + `{{my-foo}}` in other templates, which will make + an instance of the isolated component. + + ```html + {{app-profile person=currentUser}} + ``` + + ```html + +

{{person.title}}

+ +

{{person.signature}}

+ ``` + + You can also use `yield` inside a template to + include the **contents** of the custom tag: + + ```html + {{#app-profile person=currentUser}} +

Admin mode

+ {{/app-profile}} + ``` + + ```html + +

{{person.title}}

+ {{yield}} + ``` + + If you want to customize the component, in order to + handle events or actions, you implement a subclass + of `Ember.Component` named after the name of the + component. + + For example, you could implement the action + `hello` for the `app-profile` component: + + ```js + App.AppProfileComponent = Ember.Component.extend({ + hello: function(name) { + console.log("Hello", name) + } + }); + ``` + + And then use it in the component's template: + + ```html + + +

{{person.title}}

+ {{yield}} + + + ``` + + Components must have a `-` in their name to avoid + conflicts with built-in controls that wrap HTML + elements. This is consistent with the same + requirement in web components. + + @class Component + @namespace Ember + @extends Ember.View +*/ +Ember.Component = Ember.View.extend({ + init: function() { + this._super(); + this.set('context', this); + this.set('controller', this); + } +}); + +})(); + + + (function() { })(); @@ -18245,7 +19301,6 @@ Ember.ViewTargetActionSupport = Ember.Mixin.create(Ember.TargetActionSupport, { (function() { -/*globals jQuery*/ /** Ember Views @@ -18737,8 +19792,8 @@ if(!Handlebars && typeof require === 'function') { Handlebars = require('handlebars'); } -Ember.assert("Ember Handlebars requires Handlebars version 1.0.0-rc.3. Include a SCRIPT tag in the HTML HEAD linking to the Handlebars file before you link to Ember.", Handlebars) -Ember.assert("Ember Handlebars requires Handlebars version 1.0.0-rc.3, COMPILER_REVISION 2. Builds of master may have other COMPILER_REVISION values.", Handlebars.COMPILER_REVISION === 2); +Ember.assert("Ember Handlebars requires Handlebars version 1.0.0. Include a SCRIPT tag in the HTML HEAD linking to the Handlebars file before you link to Ember.", Handlebars) +Ember.assert("Ember Handlebars requires Handlebars version 1.0.0, COMPILER_REVISION expected: 4, got: " + Handlebars.COMPILER_REVISION + " - Please note: Builds of master may have other COMPILER_REVISION values.", Handlebars.COMPILER_REVISION === 4); /** Prepares the Handlebars templating library for use inside Ember's view @@ -18770,10 +19825,74 @@ function makeBindings(options) { } } +/** + Register a bound helper or custom view helper. + + ## Simple bound helper example + + ```javascript + Ember.Handlebars.helper('capitalize', function(value) { + return value.toUpperCase(); + }); + ``` + + The above bound helper can be used inside of templates as follows: + + ```handlebars + {{capitalize name}} + ``` + + In this case, when the `name` property of the template's context changes, + the rendered value of the helper will update to reflect this change. + + For more examples of bound helpers, see documentation for + `Ember.Handlebars.registerBoundHelper`. + + ## Custom view helper example + + Assuming a view subclass named `App.CalenderView` were defined, a helper + for rendering instances of this view could be registered as follows: + + ```javascript + Ember.Handlebars.helper('calendar', App.CalendarView): + ``` + + The above bound helper can be used inside of templates as follows: + + ```handlebars + {{calendar}} + ``` + + Which is functionally equivalent to: + + ```handlebars + {{view App.CalendarView}} + ``` + + Options in the helper will be passed to the view in exactly the same + manner as with the `view` helper. + + @method helper + @for Ember.Handlebars + @param {String} name + @param {Function|Ember.View} function or view class constructor + @param {String} dependentKeys* +*/ Ember.Handlebars.helper = function(name, value) { + if (Ember.Component.detect(value)) { + Ember.assert("You tried to register a component named '" + name + "', but component names must include a '-'", name.match(/-/)); + + var proto = value.proto(); + if (!proto.layoutName && !proto.templateName) { + value.reopen({ + layoutName: 'components/' + name + }); + } + } + if (Ember.View.detect(value)) { Ember.Handlebars.registerHelper(name, function(options) { - Ember.assert("You can only pass attributes as parameters to a application-defined helper", arguments.length < 3); + Ember.assert("You can only pass attributes as parameters (not values) to a application-defined helper", arguments.length < 2); makeBindings(options); return Ember.Handlebars.helpers.view.call(this, value, options); }); @@ -18861,7 +19980,7 @@ Ember.Handlebars.Compiler.prototype.mustache = function(mustache) { } else if (mustache.params.length || mustache.hash) { // no changes required } else { - var id = new Handlebars.AST.IdNode(['_triageMustache']); + var id = new Handlebars.AST.IdNode([{ part: '_triageMustache' }]); // Update the mustache node to include a hash value indicating whether the original node // was escaped. This will allow us to properly escape values when the underlying value @@ -19150,15 +20269,15 @@ Ember.Handlebars.registerHelper('helperMissing', function(path, options) { }); ``` - Which allows for template syntax such as {{concatenate prop1 prop2}} or - {{concatenate prop1 prop2 prop3}}. If any of the properties change, + Which allows for template syntax such as `{{concatenate prop1 prop2}}` or + `{{concatenate prop1 prop2 prop3}}`. If any of the properties change, the helpr will re-render. Note that dependency keys cannot be using in conjunction with multi-property helpers, since it is ambiguous which property the dependent keys would belong to. ## Use with unbound helper - The {{unbound}} helper can be used with bound helper invocations + The `{{unbound}}` helper can be used with bound helper invocations to render them in their unbound form, e.g. ```handlebars @@ -19168,6 +20287,10 @@ Ember.Handlebars.registerHelper('helperMissing', function(path, options) { In this example, if the name property changes, the helper will not re-render. + ## Use with blocks not supported + + Bound helpers do not support use with Handlebars blocks or + the addition of child views of any kind. @method registerBoundHelper @for Ember.Handlebars @@ -19191,6 +20314,8 @@ Ember.Handlebars.registerBoundHelper = function(name, fn) { pathRoot, path, loc, hashOption; + Ember.assert("registerBoundHelper-generated helpers do not support use with Handlebars blocks.", !options.fn); + // Detect bound options (e.g. countBinding="otherCount") hash.boundOptions = {}; for (hashOption in hash) { @@ -19291,7 +20416,7 @@ function evaluateMultiPropertyBoundHelper(context, fn, normalizedProperties, opt view.appendChild(bindView); - // Assemble liast of watched properties that'll re-render this helper. + // Assemble list of watched properties that'll re-render this helper. watchedProperties = []; for (boundOption in boundOptions) { if (boundOptions.hasOwnProperty(boundOption)) { @@ -19351,7 +20476,6 @@ Ember.Handlebars.template = function(spec){ return t; }; - })(); @@ -19371,7 +20495,7 @@ var htmlSafe = Ember.String.htmlSafe; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { /** - See {{#crossLink "Ember.String/htmlSafe"}}{{/crossLink}} + See `Ember.String.htmlSafe`. @method htmlSafe @for String @@ -19526,7 +20650,7 @@ Ember._MetamorphView = Ember.View.extend(Ember._Metamorph); /** @class _SimpleMetamorphView @namespace Ember - @extends Ember.View + @extends Ember.CoreView @uses Ember._Metamorph @private */ @@ -20313,7 +21437,7 @@ EmberHandlebars.registerHelper('bindAttr', function(options) { // Handle classes differently, as we can bind multiple classes var classBindings = attrs['class']; - if (classBindings !== null && classBindings !== undefined) { + if (classBindings != null) { var classResults = EmberHandlebars.bindClasses(this, classBindings, view, dataId, options); ret.push('class="' + Handlebars.Utils.escapeExpression(classResults.join(' ')) + '"'); @@ -20514,6 +21638,8 @@ EmberHandlebars.bindClasses = function(context, classBindings, view, bindAttrId, var get = Ember.get, set = Ember.set; var EmberHandlebars = Ember.Handlebars; +var LOWERCASE_A_Z = /^[a-z]/; +var VIEW_PREFIX = /^view\./; EmberHandlebars.ViewHelper = Ember.Object.create({ @@ -20625,7 +21751,18 @@ EmberHandlebars.ViewHelper = Ember.Object.create({ newView; if ('string' === typeof path) { - newView = EmberHandlebars.get(thisContext, path, options); + + // TODO: this is a lame conditional, this should likely change + // but something along these lines will likely need to be added + // as deprecation warnings + // + if (options.types[0] === 'STRING' && LOWERCASE_A_Z.test(path) && !VIEW_PREFIX.test(path)) { + Ember.assert("View requires a container", !!data.view.container); + newView = data.view.container.lookupFactory('view:' + path); + } else { + newView = EmberHandlebars.get(thisContext, path, options); + } + Ember.assert("Unable to find view at path '" + path + "'", !!newView); } else { newView = path; @@ -20994,11 +22131,25 @@ Ember.Handlebars.registerHelper('collection', function(path, options) { var hash = options.hash, itemHash = {}, match; // Extract item view class if provided else default to the standard class - var itemViewClass, itemViewPath = hash.itemViewClass; - var collectionPrototype = collectionClass.proto(); + var collectionPrototype = collectionClass.proto(), + itemViewClass; + + if (hash.itemView) { + var controller = data.keywords.controller; + Ember.assert('itemView given, but no container is available', controller && controller.container); + var container = controller.container; + itemViewClass = container.resolve('view:' + Ember.String.camelize(hash.itemView)); + Ember.assert('itemView not found in container', !!itemViewClass); + } else if (hash.itemViewClass) { + itemViewClass = handlebarsGet(collectionPrototype, hash.itemViewClass, options); + } else { + itemViewClass = collectionPrototype.itemViewClass; + } + + Ember.assert(fmt("%@ #collection: Could not find itemViewClass %@", [data.view, itemViewClass]), !!itemViewClass); + delete hash.itemViewClass; - itemViewClass = itemViewPath ? handlebarsGet(collectionPrototype, itemViewPath, options) : collectionPrototype.itemViewClass; - Ember.assert(fmt("%@ #collection: Could not find itemViewClass %@", [data.view, itemViewPath]), !!itemViewClass); + delete hash.itemView; // Go through options passed to the {{collection}} helper and extract options // that configure item views instead of the collection itself. @@ -21463,6 +22614,11 @@ Ember.Handlebars.registerHelper('each', function(path, options) { options.hash.keyword = keywordName; } + if (arguments.length === 1) { + options = path; + path = 'this'; + } + options.hash.dataSourceBinding = path; // Set up emptyView as a metamorph with no tag //options.hash.emptyViewClass = Ember._MetamorphView; @@ -21581,7 +22737,7 @@ Ember.Handlebars.registerHelper('partial', function(name, options) { var view = options.data.view, underscoredName = nameParts.join("/"), template = view.templateForName(underscoredName), - deprecatedTemplate = view.templateForName(name); + deprecatedTemplate = !template && view.templateForName(name); Ember.deprecate("You tried to render the partial " + name + ", which should be at '" + underscoredName + "', but Ember found '" + name + "'. Please use a leading underscore in your partials", template); Ember.assert("Unable to find partial with name '"+name+"'.", template || deprecatedTemplate); @@ -22188,6 +23344,7 @@ var set = Ember.set, get = Ember.get, indexOf = Ember.EnumerableUtils.indexOf, indexesOf = Ember.EnumerableUtils.indexesOf, + forEach = Ember.EnumerableUtils.forEach, replace = Ember.EnumerableUtils.replace, isArray = Ember.isArray, precompileTemplate = Ember.Handlebars.compile; @@ -22241,6 +23398,18 @@ Ember.SelectOption = Ember.View.extend({ }, 'parentView.optionValuePath') }); +Ember.SelectOptgroup = Ember.CollectionView.extend({ + tagName: 'optgroup', + attributeBindings: ['label'], + + selectionBinding: 'parentView.selection', + multipleBinding: 'parentView.multiple', + optionLabelPathBinding: 'parentView.optionLabelPath', + optionValuePathBinding: 'parentView.optionValuePath', + + itemViewClassBinding: 'parentView.optionView' +}); + /** The `Ember.Select` view class renders a [select](https://developer.mozilla.org/en/HTML/Element/select) HTML element, @@ -22337,7 +23506,6 @@ Ember.SelectOption = Ember.View.extend({ ```html @@ -22370,7 +23538,6 @@ Ember.SelectOption = Ember.View.extend({ ```html @@ -22408,7 +23575,6 @@ Ember.SelectOption = Ember.View.extend({ ```html @@ -22494,34 +23660,67 @@ Ember.Select = Ember.View.extend( tagName: 'select', classNames: ['ember-select'], defaultTemplate: Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) { -this.compilerInfo = [2,'>= 1.0.0-rc.3']; -helpers = helpers || Ember.Handlebars.helpers; data = data || {}; - var buffer = '', stack1, hashTypes, escapeExpression=this.escapeExpression, self=this; +this.compilerInfo = [4,'>= 1.0.0']; +helpers = this.merge(helpers, Ember.Handlebars.helpers); data = data || {}; + var buffer = '', stack1, hashTypes, hashContexts, escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { - var buffer = '', hashTypes; + var buffer = '', hashTypes, hashContexts; data.buffer.push(""); return buffer; } function program3(depth0,data) { - var hashTypes; + var stack1, hashTypes, hashContexts; + hashTypes = {}; + hashContexts = {}; + stack1 = helpers.each.call(depth0, "view.groupedContent", {hash:{},inverse:self.noop,fn:self.program(4, program4, data),contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data}); + if(stack1 || stack1 === 0) { data.buffer.push(stack1); } + else { data.buffer.push(''); } + } +function program4(depth0,data) { + + var hashContexts, hashTypes; + hashContexts = {'contentBinding': depth0,'labelBinding': depth0}; + hashTypes = {'contentBinding': "ID",'labelBinding': "ID"}; + data.buffer.push(escapeExpression(helpers.view.call(depth0, "view.groupView", {hash:{ + 'contentBinding': ("content"), + 'labelBinding': ("label") + },contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data}))); + } + +function program6(depth0,data) { + + var stack1, hashTypes, hashContexts; + hashTypes = {}; + hashContexts = {}; + stack1 = helpers.each.call(depth0, "view.content", {hash:{},inverse:self.noop,fn:self.program(7, program7, data),contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data}); + if(stack1 || stack1 === 0) { data.buffer.push(stack1); } + else { data.buffer.push(''); } + } +function program7(depth0,data) { + + var hashContexts, hashTypes; + hashContexts = {'contentBinding': depth0}; hashTypes = {'contentBinding': "STRING"}; data.buffer.push(escapeExpression(helpers.view.call(depth0, "view.optionView", {hash:{ 'contentBinding': ("this") - },contexts:[depth0],types:["ID"],hashTypes:hashTypes,data:data}))); + },contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data}))); } hashTypes = {}; - stack1 = helpers['if'].call(depth0, "view.prompt", {hash:{},inverse:self.noop,fn:self.program(1, program1, data),contexts:[depth0],types:["ID"],hashTypes:hashTypes,data:data}); + hashContexts = {}; + stack1 = helpers['if'].call(depth0, "view.prompt", {hash:{},inverse:self.noop,fn:self.program(1, program1, data),contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data}); if(stack1 || stack1 === 0) { data.buffer.push(stack1); } hashTypes = {}; - stack1 = helpers.each.call(depth0, "view.content", {hash:{},inverse:self.noop,fn:self.program(3, program3, data),contexts:[depth0],types:["ID"],hashTypes:hashTypes,data:data}); + hashContexts = {}; + stack1 = helpers['if'].call(depth0, "view.optionGroupPath", {hash:{},inverse:self.program(6, program6, data),fn:self.program(3, program3, data),contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data}); if(stack1 || stack1 === 0) { data.buffer.push(stack1); } return buffer; @@ -22621,6 +23820,45 @@ function program3(depth0,data) { */ optionValuePath: 'content', + /** + The path of the option group. + When this property is used, `content` should be sorted by `optionGroupPath`. + + @property optionGroupPath + @type String + @default null + */ + optionGroupPath: null, + + /** + The view class for optgroup. + + @property groupView + @type Ember.View + @default Ember.SelectOptgroup + */ + groupView: Ember.SelectOptgroup, + + groupedContent: Ember.computed(function() { + var groupPath = get(this, 'optionGroupPath'); + var groupedContent = Ember.A(); + + forEach(get(this, 'content'), function(item) { + var label = get(item, groupPath); + + if (get(groupedContent, 'lastObject.label') !== label) { + groupedContent.pushObject({ + label: label, + content: Ember.A() + }); + } + + get(groupedContent, 'lastObject.content').push(item); + }); + + return groupedContent; + }).property('optionGroupPath', 'content.@each'), + /** The view class for option. @@ -22672,8 +23910,8 @@ function program3(depth0,data) { var selection = get(this, 'selection'); var value = get(this, 'value'); - if (selection) { this.selectionDidChange(); } - if (value) { this.valueDidChange(); } + if (!Ember.isNone(selection)) { this.selectionDidChange(); } + if (!Ember.isNone(value)) { this.valueDidChange(); } this._change(); }, @@ -22789,7 +24027,7 @@ Ember.Handlebars.registerHelper('input', function(options) { if (inputType === 'checkbox') { return Ember.Handlebars.helpers.view.call(this, Ember.Checkbox, options); } else { - hash.type = inputType || 'text'; + hash.type = inputType; hash.onEvent = onEvent || 'enter'; return Ember.Handlebars.helpers.view.call(this, Ember.TextField, options); } @@ -22870,6 +24108,31 @@ function bootstrap() { Ember.Handlebars.bootstrap( Ember.$(document) ); } +function registerComponents(container) { + var templates = Ember.TEMPLATES, match; + if (!templates) { return; } + + for (var prop in templates) { + if (match = prop.match(/^components\/(.*)$/)) { + registerComponent(container, match[1]); + } + } +} + +function registerComponent(container, name) { + Ember.assert("You provided a template named 'components/" + name + "', but custom components must include a '-'", name.match(/-/)); + + var className = name.replace(/-/g, '_'); + var Component = container.lookupFactory('component:' + className) || container.lookupFactory('component:' + name); + var View = Component || Ember.Component.extend(); + + View.reopen({ + layoutName: 'components/' + name + }); + + Ember.Handlebars.helper(name, View); +} + /* We tie this to application.load to ensure that we've at least attempted to bootstrap at the point that the application is loaded. @@ -22881,7 +24144,23 @@ function bootstrap() { from the DOM after processing. */ -Ember.onLoad('application', bootstrap); +Ember.onLoad('Ember.Application', function(Application) { + if (Application.initializer) { + Application.initializer({ + name: 'domTemplates', + initialize: bootstrap + }); + + Application.initializer({ + name: 'registerComponents', + after: 'domTemplates', + initialize: registerComponents + }); + } else { + // for ember-old-router + Ember.onLoad('application', bootstrap); + } +}); })(); @@ -23416,8 +24695,8 @@ define("route-recognizer", (function() { define("router", - ["route-recognizer"], - function(RouteRecognizer) { + ["route-recognizer", "rsvp"], + function(RouteRecognizer, RSVP) { "use strict"; /** @private @@ -23438,11 +24717,148 @@ define("router", */ + var slice = Array.prototype.slice; + + + + /** + @private + + A Transition is a thennable (a promise-like object) that represents + an attempt to transition to another route. It can be aborted, either + explicitly via `abort` or by attempting another transition while a + previous one is still underway. An aborted transition can also + be `retry()`d later. + */ + + function Transition(router, promise) { + this.router = router; + this.promise = promise; + this.data = {}; + this.resolvedModels = {}; + this.providedModels = {}; + this.providedModelsArray = []; + this.sequence = ++Transition.currentSequence; + this.params = {}; + } + + Transition.currentSequence = 0; + + Transition.prototype = { + targetName: null, + urlMethod: 'update', + providedModels: null, + resolvedModels: null, + params: null, + + /** + The Transition's internal promise. Calling `.then` on this property + is that same as calling `.then` on the Transition object itself, but + this property is exposed for when you want to pass around a + Transition's promise, but not the Transition object itself, since + Transition object can be externally `abort`ed, while the promise + cannot. + */ + promise: null, + + /** + Custom state can be stored on a Transition's `data` object. + This can be useful for decorating a Transition within an earlier + hook and shared with a later hook. Properties set on `data` will + be copied to new transitions generated by calling `retry` on this + transition. + */ + data: null, + + /** + A standard promise hook that resolves if the transition + succeeds and rejects if it fails/redirects/aborts. + + Forwards to the internal `promise` property which you can + use in situations where you want to pass around a thennable, + but not the Transition itself. + + @param {Function} success + @param {Function} failure + */ + then: function(success, failure) { + return this.promise.then(success, failure); + }, + + /** + Aborts the Transition. Note you can also implicitly abort a transition + by initiating another transition while a previous one is underway. + */ + abort: function() { + if (this.isAborted) { return this; } + log(this.router, this.sequence, this.targetName + ": transition was aborted"); + this.isAborted = true; + this.router.activeTransition = null; + return this; + }, + + /** + Retries a previously-aborted transition (making sure to abort the + transition if it's still active). Returns a new transition that + represents the new attempt to transition. + */ + retry: function() { + this.abort(); + + var recogHandlers = this.router.recognizer.handlersFor(this.targetName), + newTransition = performTransition(this.router, recogHandlers, this.providedModelsArray, this.params, this.data); + + return newTransition; + }, + + /** + Sets the URL-changing method to be employed at the end of a + successful transition. By default, a new Transition will just + use `updateURL`, but passing 'replace' to this method will + cause the URL to update using 'replaceWith' instead. Omitting + a parameter will disable the URL change, allowing for transitions + that don't update the URL at completion (this is also used for + handleURL, since the URL has already changed before the + transition took place). + + @param {String} method the type of URL-changing method to use + at the end of a transition. Accepted values are 'replace', + falsy values, or any other non-falsy value (which is + interpreted as an updateURL transition). + + @return {Transition} this transition + */ + method: function(method) { + this.urlMethod = method; + return this; + } + }; + function Router() { this.recognizer = new RouteRecognizer(); } + + /** + Promise reject reasons passed to promise rejection + handlers for failed transitions. + */ + Router.UnrecognizedURLError = function(message) { + this.message = (message || "UnrecognizedURLError"); + this.name = "UnrecognizedURLError"; + }; + + Router.TransitionAborted = function(message) { + this.message = (message || "TransitionAborted"); + this.name = "TransitionAborted"; + }; + + function errorTransition(router, reason) { + return new Transition(router, RSVP.reject(reason)); + } + + Router.prototype = { /** The main entry point into the router. The API is essentially @@ -23468,6 +24884,25 @@ define("router", }, /** + Clears the current and target route handlers and triggers exit + on each of them starting at the leaf and traversing up through + its ancestors. + */ + reset: function() { + eachHandler(this.currentHandlerInfos || [], function(handlerInfo) { + var handler = handlerInfo.handler; + if (handler.exit) { + handler.exit(); + } + }); + this.currentHandlerInfos = null; + this.targetHandlerInfos = null; + }, + + activeTransition: null, + + /** + var handler = handlerInfo.handler; The entry point for handling a change to the URL (usually via the back and forward button). @@ -23479,13 +24914,11 @@ define("router", @return {Array} an Array of `[handler, parameter]` tuples */ handleURL: function(url) { - var results = this.recognizer.recognize(url); - - if (!results) { - throw new Error("No route matched the URL '" + url + "'"); - } - - collectObjects(this, results, 0, []); + // Perform a URL-based transition, but don't change + // the URL afterward, since it already happened. + var args = slice.call(arguments); + if (url.charAt(0) !== '/') { args[0] = '/' + url; } + return doTransition(this, args).method(null); }, /** @@ -23494,7 +24927,7 @@ define("router", @param {String} url a URL to update to */ updateURL: function() { - throw "updateURL is not implemented"; + throw new Error("updateURL is not implemented"); }, /** @@ -23517,8 +24950,7 @@ define("router", @param {String} name the name of the route */ transitionTo: function(name) { - var args = Array.prototype.slice.call(arguments, 1); - doTransition(this, name, this.updateURL, args); + return doTransition(this, arguments); }, /** @@ -23530,8 +24962,7 @@ define("router", @param {String} name the name of the route */ replaceWith: function(name) { - var args = Array.prototype.slice.call(arguments, 1); - doTransition(this, name, this.replaceURL, args); + return doTransition(this, arguments).method('replace'); }, /** @@ -23545,8 +24976,7 @@ define("router", @return {Object} a serialized parameter hash */ paramsForHandler: function(handlerName, callback) { - var output = this._paramsForHandler(handlerName, [].slice.call(arguments, 1)); - return output.params; + return paramsForHandler(this, handlerName, slice.call(arguments, 1)); }, /** @@ -23560,109 +24990,17 @@ define("router", @return {String} a URL */ generate: function(handlerName) { - var params = this.paramsForHandler.apply(this, arguments); + var params = paramsForHandler(this, handlerName, slice.call(arguments, 1)); return this.recognizer.generate(handlerName, params); }, - /** - @private - - Used internally by `generate` and `transitionTo`. - */ - _paramsForHandler: function(handlerName, objects, doUpdate) { - var handlers = this.recognizer.handlersFor(handlerName), - params = {}, - toSetup = [], - startIdx = handlers.length, - objectsToMatch = objects.length, - object, objectChanged, handlerObj, handler, names, i; - - // Find out which handler to start matching at - for (i=handlers.length-1; i>=0 && objectsToMatch>0; i--) { - if (handlers[i].names.length) { - objectsToMatch--; - startIdx = i; - } - } - - if (objectsToMatch > 0) { - throw "More context objects were passed than there are dynamic segments for the route: "+handlerName; - } - - // Connect the objects to the routes - for (i=0; i= startIdx) { - object = objects.shift(); - objectChanged = true; - // Otherwise use existing context - } else { - object = handler.context; - } - - // Serialize to generate params - if (handler.serialize) { - merge(params, handler.serialize(object, names)); - } - // If it's not a dynamic segment and we're updating - } else if (doUpdate) { - // If we've passed the match point we need to deserialize again - // or if we never had a context - if (i > startIdx || !handler.hasOwnProperty('context')) { - if (handler.deserialize) { - object = handler.deserialize({}); - objectChanged = true; - } - // Otherwise use existing context - } else { - object = handler.context; - } - } - - // Make sure that we update the context here so it's available to - // subsequent deserialize calls - if (doUpdate && objectChanged) { - // TODO: It's a bit awkward to set the context twice, see if we can DRY things up - setContext(handler, object); - } - - toSetup.push({ - isDynamic: !!handlerObj.names.length, - name: handlerObj.handler, - handler: handler, - context: object - }); - - if (i === handlers.length - 1) { - var lastHandler = toSetup[toSetup.length - 1], - additionalHandler; - - if (additionalHandler = lastHandler.handler.additionalHandler) { - handlers.push({ - handler: additionalHandler.call(lastHandler.handler), - names: [] - }); - } - } - } - - return { params: params, toSetup: toSetup }; - }, - isActive: function(handlerName) { - var contexts = [].slice.call(arguments, 1); + var contexts = slice.call(arguments, 1); var targetHandlerInfos = this.targetHandlerInfos, found = false, names, object, handlerInfo, handlerObj; - if (!targetHandlerInfos) { return; } + if (!targetHandlerInfos) { return false; } for (var i=targetHandlerInfos.length-1; i>=0; i--) { handlerInfo = targetHandlerInfos[i]; @@ -23682,164 +25020,187 @@ define("router", }, trigger: function(name) { - var args = [].slice.call(arguments); - trigger(this, args); - } + var args = slice.call(arguments); + trigger(this.currentHandlerInfos, false, args); + }, + + /** + Hook point for logging transition status updates. + + @param {String} message The message to log. + */ + log: null }; + /** + @private + + Used internally for both URL and named transition to determine + a shared pivot parent route and other data necessary to perform + a transition. + */ + function getMatchPoint(router, handlers, objects, inputParams) { + + var matchPoint = handlers.length, + providedModels = {}, i, + currentHandlerInfos = router.currentHandlerInfos || [], + params = {}, + oldParams = router.currentParams || {}, + activeTransition = router.activeTransition, + handlerParams = {}, + obj; + + objects = slice.call(objects); + merge(params, inputParams); + + for (i = handlers.length - 1; i >= 0; i--) { + var handlerObj = handlers[i], + handlerName = handlerObj.handler, + oldHandlerInfo = currentHandlerInfos[i], + hasChanged = false; + + // Check if handler names have changed. + if (!oldHandlerInfo || oldHandlerInfo.name !== handlerObj.handler) { hasChanged = true; } + + if (handlerObj.isDynamic) { + // URL transition. + + if (obj = getMatchPointObject(objects, handlerName, activeTransition, true, params)) { + hasChanged = true; + providedModels[handlerName] = obj; + } else { + handlerParams[handlerName] = {}; + for (var prop in handlerObj.params) { + if (!handlerObj.params.hasOwnProperty(prop)) { continue; } + var newParam = handlerObj.params[prop]; + if (oldParams[prop] !== newParam) { hasChanged = true; } + handlerParams[handlerName][prop] = params[prop] = newParam; + } + } + } else if (handlerObj.hasOwnProperty('names')) { + // Named transition. + + if (objects.length) { hasChanged = true; } + + if (obj = getMatchPointObject(objects, handlerName, activeTransition, handlerObj.names[0], params)) { + providedModels[handlerName] = obj; + } else { + var names = handlerObj.names; + handlerParams[handlerName] = {}; + for (var j = 0, len = names.length; j < len; ++j) { + var name = names[j]; + handlerParams[handlerName][name] = params[name] = params[name] || oldParams[name]; + } + } + } + + if (hasChanged) { matchPoint = i; } + } + + if (objects.length > 0) { + throw new Error("More context objects were passed than there are dynamic segments for the route: " + handlers[handlers.length - 1].handler); + } + + return { matchPoint: matchPoint, providedModels: providedModels, params: params, handlerParams: handlerParams }; + } + + function getMatchPointObject(objects, handlerName, activeTransition, paramName, params) { + + if (objects.length && paramName) { + + var object = objects.pop(); + + // If provided object is string or number, treat as param. + if (isParam(object)) { + params[paramName] = object.toString(); + } else { + return object; + } + } else if (activeTransition) { + // Use model from previous transition attempt, preferably the resolved one. + return (paramName && activeTransition.providedModels[handlerName]) || + activeTransition.resolvedModels[handlerName]; + } + } + + function isParam(object) { + return object && (typeof object === "string" || object instanceof String || !isNaN(object)); + } + + /** + @private + + This method takes a handler name and a list of contexts and returns + a serialized parameter hash suitable to pass to `recognizer.generate()`. + + @param {Router} router + @param {String} handlerName + @param {Array[Object]} objects + @return {Object} a serialized parameter hash + */ + function paramsForHandler(router, handlerName, objects) { + + var handlers = router.recognizer.handlersFor(handlerName), + params = {}, + matchPoint = getMatchPoint(router, handlers, objects).matchPoint, + object, handlerObj, handler, names, i; + + for (i=0; i= matchPoint) { + object = objects.shift(); + // Otherwise use existing context + } else { + object = handler.context; + } + + // Serialize to generate params + merge(params, serialize(handler, object, names)); + } + } + return params; + } + function merge(hash, other) { for (var prop in other) { if (other.hasOwnProperty(prop)) { hash[prop] = other[prop]; } } } - function isCurrent(currentHandlerInfos, handlerName) { - return currentHandlerInfos[currentHandlerInfos.length - 1].name === handlerName; - } - /** @private - - This function is called the first time the `collectObjects` - function encounters a promise while converting URL parameters - into objects. - - It triggers the `enter` and `setup` methods on the `loading` - handler. - - @param {Router} router */ - function loading(router) { - if (!router.isLoading) { - router.isLoading = true; - var handler = router.getHandler('loading'); + function createNamedTransition(router, args) { + var handlers = router.recognizer.handlersFor(args[0]); - if (handler) { - if (handler.enter) { handler.enter(); } - if (handler.setup) { handler.setup(); } - } - } - } + log(router, "Attempting transition to " + args[0]); - /** - @private - - This function is called if a promise was previously - encountered once all promises are resolved. - - It triggers the `exit` method on the `loading` handler. - - @param {Router} router - */ - function loaded(router) { - router.isLoading = false; - var handler = router.getHandler('loading'); - if (handler && handler.exit) { handler.exit(); } - } - - /** - @private - - This function is called if any encountered promise - is rejected. - - It triggers the `exit` method on the `loading` handler, - the `enter` method on the `failure` handler, and the - `setup` method on the `failure` handler with the - `error`. - - @param {Router} router - @param {Object} error the reason for the promise - rejection, to pass into the failure handler's - `setup` method. - */ - function failure(router, error) { - loaded(router); - var handler = router.getHandler('failure'); - if (handler) { - if (handler.enter) { handler.enter(); } - if (handler.setup) { handler.setup(error); } - } + return performTransition(router, handlers, slice.call(args, 1), router.currentParams); } /** @private */ - function doTransition(router, name, method, args) { - var output = router._paramsForHandler(name, args, true); - var params = output.params, toSetup = output.toSetup; + function createURLTransition(router, url) { - var url = router.recognizer.generate(name, params); - method.call(router, url); + var results = router.recognizer.recognize(url), + currentHandlerInfos = router.currentHandlerInfos; - setupContexts(router, toSetup); + log(router, "Attempting URL transition to " + url); + + if (!results) { + return errorTransition(router, new Router.UnrecognizedURLError(url)); + } + + return performTransition(router, results, [], {}); } - /** - @private - - This function is called after a URL change has been handled - by `router.handleURL`. - - Takes an Array of `RecognizedHandler`s, and converts the raw - params hashes into deserialized objects by calling deserialize - on the handlers. This process builds up an Array of - `HandlerInfo`s. It then calls `setupContexts` with the Array. - - If the `deserialize` method on a handler returns a promise - (i.e. has a method called `then`), this function will pause - building up the `HandlerInfo` Array until the promise is - resolved. It will use the resolved value as the context of - `HandlerInfo`. - */ - function collectObjects(router, results, index, objects) { - if (results.length === index) { - var lastObject = objects[objects.length - 1], - lastHandler = lastObject && lastObject.handler; - - if (lastHandler && lastHandler.additionalHandler) { - var additionalResult = { - handler: lastHandler.additionalHandler(), - params: {}, - isDynamic: false - }; - results.push(additionalResult); - } else { - loaded(router); - setupContexts(router, objects); - return; - } - } - - var result = results[index]; - var handler = router.getHandler(result.handler); - var object = handler.deserialize && handler.deserialize(result.params); - - if (object && typeof object.then === 'function') { - loading(router); - - // The chained `then` means that we can also catch errors that happen in `proceed` - object.then(proceed).then(null, function(error) { - failure(router, error); - }); - } else { - proceed(object); - } - - function proceed(value) { - if (handler.context !== object) { - setContext(handler, object); - } - - var updatedObjects = objects.concat([{ - context: value, - name: result.handler, - handler: router.getHandler(result.handler), - isDynamic: result.isDynamic - }]); - collectObjects(router, results, index + 1, updatedObjects); - } - } /** @private @@ -23863,7 +25224,7 @@ define("router", Consider the following transitions: 1. A URL transition to `/posts/1`. - 1. Triggers the `deserialize` callback on the + 1. Triggers the `*model` callbacks on the `index`, `posts`, and `showPost` handlers 2. Triggers the `enter` callback on the same 3. Triggers the `setup` callback on the same @@ -23879,16 +25240,17 @@ define("router", 3. Triggers the `enter` callback on `about` 4. Triggers the `setup` callback on `about` - @param {Router} router + @param {Transition} transition @param {Array[HandlerInfo]} handlerInfos */ - function setupContexts(router, handlerInfos) { - var partition = - partitionHandlers(router.currentHandlerInfos || [], handlerInfos); + function setupContexts(transition, handlerInfos) { + var router = transition.router, + partition = partitionHandlers(router.currentHandlerInfos || [], handlerInfos); router.targetHandlerInfos = handlerInfos; - eachHandler(partition.exited, function(handler, context) { + eachHandler(partition.exited, function(handlerInfo) { + var handler = handlerInfo.handler; delete handler.context; if (handler.exit) { handler.exit(); } }); @@ -23896,33 +25258,51 @@ define("router", var currentHandlerInfos = partition.unchanged.slice(); router.currentHandlerInfos = currentHandlerInfos; - eachHandler(partition.updatedContext, function(handler, context, handlerInfo) { - setContext(handler, context); - if (handler.setup) { handler.setup(context); } - currentHandlerInfos.push(handlerInfo); + eachHandler(partition.updatedContext, function(handlerInfo) { + handlerEnteredOrUpdated(transition, currentHandlerInfos, handlerInfo, false); }); - var aborted = false; - eachHandler(partition.entered, function(handler, context, handlerInfo) { - if (aborted) { return; } - if (handler.enter) { handler.enter(); } - setContext(handler, context); - if (handler.setup) { - if (false === handler.setup(context)) { - aborted = true; - } - } - - if (!aborted) { - currentHandlerInfos.push(handlerInfo); - } + eachHandler(partition.entered, function(handlerInfo) { + handlerEnteredOrUpdated(transition, currentHandlerInfos, handlerInfo, true); }); - if (!aborted && router.didTransition) { + if (router.didTransition) { router.didTransition(handlerInfos); } } + /** + @private + + Helper method used by setupContexts. Handles errors or redirects + that may happen in enter/setup. + */ + function handlerEnteredOrUpdated(transition, currentHandlerInfos, handlerInfo, enter) { + var handler = handlerInfo.handler, + context = handlerInfo.context; + + try { + if (enter && handler.enter) { handler.enter(); } + checkAbort(transition); + + setContext(handler, context); + + if (handler.setup) { handler.setup(context); } + checkAbort(transition); + } catch(e) { + if (!(e instanceof Router.TransitionAborted)) { + // Trigger the `error` event starting from this failed handler. + trigger(currentHandlerInfos.concat(handlerInfo), true, ['error', e, transition]); + } + + // Propagate the error so that the transition promise will reject. + throw e; + } + + currentHandlerInfos.push(handlerInfo); + } + + /** @private @@ -23934,11 +25314,7 @@ define("router", */ function eachHandler(handlerInfos, callback) { for (var i=0, l=handlerInfos.length; i=0; i--) { - var handlerInfo = currentHandlerInfos[i], + for (var i=handlerInfos.length-1; i>=0; i--) { + var handlerInfo = handlerInfos[i], handler = handlerInfo.handler; if (handler.events && handler.events[name]) { @@ -24042,7 +25418,7 @@ define("router", } } - if (!eventWasHandled) { + if (!eventWasHandled && !ignoreFailure) { throw new Error("Nothing handled the event '" + name + "'."); } } @@ -24051,10 +25427,377 @@ define("router", handler.context = context; if (handler.contextDidChange) { handler.contextDidChange(); } } + + /** + @private + + Creates, begins, and returns a Transition. + */ + function performTransition(router, recogHandlers, providedModelsArray, params, data) { + + var matchPointResults = getMatchPoint(router, recogHandlers, providedModelsArray, params), + targetName = recogHandlers[recogHandlers.length - 1].handler, + wasTransitioning = false; + + // Check if there's already a transition underway. + if (router.activeTransition) { + if (transitionsIdentical(router.activeTransition, targetName, providedModelsArray)) { + return router.activeTransition; + } + router.activeTransition.abort(); + wasTransitioning = true; + } + + var deferred = RSVP.defer(), + transition = new Transition(router, deferred.promise); + + transition.targetName = targetName; + transition.providedModels = matchPointResults.providedModels; + transition.providedModelsArray = providedModelsArray; + transition.params = matchPointResults.params; + transition.data = data || {}; + router.activeTransition = transition; + + var handlerInfos = generateHandlerInfos(router, recogHandlers); + + // Fire 'willTransition' event on current handlers, but don't fire it + // if a transition was already underway. + if (!wasTransitioning) { + trigger(router.currentHandlerInfos, true, ['willTransition', transition]); + } + + log(router, transition.sequence, "Beginning validation for transition to " + transition.targetName); + validateEntry(transition, handlerInfos, 0, matchPointResults.matchPoint, matchPointResults.handlerParams) + .then(transitionSuccess, transitionFailure); + + return transition; + + function transitionSuccess() { + checkAbort(transition); + + try { + finalizeTransition(transition, handlerInfos); + + // Resolve with the final handler. + deferred.resolve(handlerInfos[handlerInfos.length - 1].handler); + } catch(e) { + deferred.reject(e); + } + + // Don't nullify if another transition is underway (meaning + // there was a transition initiated with enter/setup). + if (!transition.isAborted) { + router.activeTransition = null; + } + } + + function transitionFailure(reason) { + deferred.reject(reason); + } + } + + /** + @private + + Accepts handlers in Recognizer format, either returned from + recognize() or handlersFor(), and returns unified + `HandlerInfo`s. + */ + function generateHandlerInfos(router, recogHandlers) { + var handlerInfos = []; + for (var i = 0, len = recogHandlers.length; i < len; ++i) { + var handlerObj = recogHandlers[i], + isDynamic = handlerObj.isDynamic || (handlerObj.names && handlerObj.names.length); + + handlerInfos.push({ + isDynamic: !!isDynamic, + name: handlerObj.handler, + handler: router.getHandler(handlerObj.handler) + }); + } + return handlerInfos; + } + + /** + @private + */ + function transitionsIdentical(oldTransition, targetName, providedModelsArray) { + + if (oldTransition.targetName !== targetName) { return false; } + + var oldModels = oldTransition.providedModelsArray; + if (oldModels.length !== providedModelsArray.length) { return false; } + + for (var i = 0, len = oldModels.length; i < len; ++i) { + if (oldModels[i] !== providedModelsArray[i]) { return false; } + } + return true; + } + + /** + @private + + Updates the URL (if necessary) and calls `setupContexts` + to update the router's array of `currentHandlerInfos`. + */ + function finalizeTransition(transition, handlerInfos) { + + var router = transition.router, + seq = transition.sequence, + handlerName = handlerInfos[handlerInfos.length - 1].name; + + log(router, seq, "Validation succeeded, finalizing transition;"); + + // Collect params for URL. + var objects = []; + for (var i = 0, len = handlerInfos.length; i < len; ++i) { + var handlerInfo = handlerInfos[i]; + if (handlerInfo.isDynamic) { + objects.push(handlerInfo.context); + } + } + + var params = paramsForHandler(router, handlerName, objects); + + transition.providedModelsArray = []; + transition.providedContexts = {}; + router.currentParams = params; + + var urlMethod = transition.urlMethod; + if (urlMethod) { + var url = router.recognizer.generate(handlerName, params); + + if (urlMethod === 'replace') { + router.replaceURL(url); + } else { + // Assume everything else is just a URL update for now. + router.updateURL(url); + } + } + + setupContexts(transition, handlerInfos); + log(router, seq, "TRANSITION COMPLETE."); + } + + /** + @private + + Internal function used to construct the chain of promises used + to validate a transition. Wraps calls to `beforeModel`, `model`, + and `afterModel` in promises, and checks for redirects/aborts + between each. + */ + function validateEntry(transition, handlerInfos, index, matchPoint, handlerParams) { + + if (index === handlerInfos.length) { + // No more contexts to resolve. + return RSVP.resolve(transition.resolvedModels); + } + + var router = transition.router, + handlerInfo = handlerInfos[index], + handler = handlerInfo.handler, + handlerName = handlerInfo.name, + seq = transition.sequence, + errorAlreadyHandled = false; + + if (index < matchPoint) { + log(router, seq, handlerName + ": using context from already-active handler"); + + // We're before the match point, so don't run any hooks, + // just use the already resolved context from the handler. + transition.resolvedModels[handlerInfo.name] = handlerInfo.handler.context; + return proceed(); + } + + return RSVP.resolve().then(handleAbort) + .then(beforeModel) + .then(null, handleError) + .then(handleAbort) + .then(model) + .then(null, handleError) + .then(handleAbort) + .then(afterModel) + .then(null, handleError) + .then(handleAbort) + .then(proceed); + + function handleAbort(result) { + + if (transition.isAborted) { + log(transition.router, transition.sequence, "detected abort."); + errorAlreadyHandled = true; + return RSVP.reject(new Router.TransitionAborted()); + } + + return result; + } + + function handleError(reason) { + + if (errorAlreadyHandled) { return RSVP.reject(reason); } + errorAlreadyHandled = true; + transition.abort(); + + log(router, seq, handlerName + ": handling error: " + reason); + + // An error was thrown / promise rejected, so fire an + // `error` event from this handler info up to root. + trigger(handlerInfos.slice(0, index + 1), true, ['error', reason, transition]); + + if (handler.error) { + handler.error(reason, transition); + } + + // Propagate the original error. + return RSVP.reject(reason); + } + + function beforeModel() { + + log(router, seq, handlerName + ": calling beforeModel hook"); + + return handler.beforeModel && handler.beforeModel(transition); + } + + function model() { + log(router, seq, handlerName + ": resolving model"); + + return getModel(handlerInfo, transition, handlerParams[handlerName], index >= matchPoint); + } + + function afterModel(context) { + + log(router, seq, handlerName + ": calling afterModel hook"); + + // Pass the context and resolved parent contexts to afterModel, but we don't + // want to use the value returned from `afterModel` in any way, but rather + // always resolve with the original `context` object. + + transition.resolvedModels[handlerInfo.name] = context; + return handler.afterModel && handler.afterModel(context, transition); + } + + function proceed() { + log(router, seq, handlerName + ": validation succeeded, proceeding"); + + handlerInfo.context = transition.resolvedModels[handlerInfo.name]; + return validateEntry(transition, handlerInfos, index + 1, matchPoint, handlerParams); + } + } + + /** + @private + + Throws a TransitionAborted if the provided transition has been aborted. + */ + function checkAbort(transition) { + if (transition.isAborted) { + log(transition.router, transition.sequence, "detected abort."); + throw new Router.TransitionAborted(); + } + } + + /** + @private + + Encapsulates the logic for whether to call `model` on a route, + or use one of the models provided to `transitionTo`. + */ + function getModel(handlerInfo, transition, handlerParams, needsUpdate) { + + var handler = handlerInfo.handler, + handlerName = handlerInfo.name; + + if (!needsUpdate && handler.hasOwnProperty('context')) { + return handler.context; + } + + if (transition.providedModels.hasOwnProperty(handlerName)) { + var providedModel = transition.providedModels[handlerName]; + return typeof providedModel === 'function' ? providedModel() : providedModel; + } + + return handler.model && handler.model(handlerParams || {}, transition); + } + + /** + @private + */ + function log(router, sequence, msg) { + + if (!router.log) { return; } + + if (arguments.length === 3) { + router.log("Transition #" + sequence + ": " + msg); + } else { + msg = sequence; + router.log(msg); + } + } + + /** + @private + + Begins and returns a Transition based on the provided + arguments. Accepts arguments in the form of both URL + transitions and named transitions. + + @param {Router} router + @param {Array[Object]} args arguments passed to transitionTo, + replaceWith, or handleURL + */ + function doTransition(router, args) { + // Normalize blank transitions to root URL transitions. + var name = args[0] || '/'; + + if (name.charAt(0) === '/') { + return createURLTransition(router, name); + } else { + return createNamedTransition(router, args); + } + } + + /** + @private + + Serializes a handler using its custom `serialize` method or + by a default that looks up the expected property name from + the dynamic segment. + + @param {Object} handler a router handler + @param {Object} model the model to be serialized for this handler + @param {Array[Object]} names the names array attached to an + handler object returned from router.recognizer.handlersFor() + */ + function serialize(handler, model, names) { + + var object = {}; + if (isParam(model)) { + object[names[0]] = model; + return object; + } + + // Use custom serialize if it exists. + if (handler.serialize) { + return handler.serialize(model, names); + } + + if (names.length !== 1) { return; } + + var name = names[0]; + + if (/_id$/.test(name)) { + object[name] = model.id; + } else { + object[name] = model; + } + return object; + } + return Router; }); - })(); @@ -24146,6 +25889,8 @@ Ember.RouterDSL = DSL; (function() { +var get = Ember.get; + /** @module ember @submodule ember-routing @@ -24162,7 +25907,7 @@ Ember.controllerFor = function(container, controllerName, context, lookupOptions `App.ObjectController` and `App.ArrayController` */ Ember.generateController = function(container, controllerName, context) { - var controller, DefaultController, fullName; + var controller, DefaultController, fullName, instance; if (context && Ember.isArray(context)) { DefaultController = container.resolve('controller:array'); @@ -24183,10 +25928,16 @@ Ember.generateController = function(container, controllerName, context) { return "(generated " + controllerName + " controller)"; }; - fullName = 'controller:' + controllerName; container.register(fullName, controller); - return container.lookup(fullName); + + instance = container.lookup(fullName); + + if (get(instance, 'namespace.LOG_ACTIVE_GENERATION')) { + Ember.Logger.info("generated -> " + fullName, { fullName: fullName }); + } + + return instance; }; })(); @@ -24201,6 +25952,7 @@ Ember.generateController = function(container, controllerName, context) { var Router = requireModule("router"); var get = Ember.get, set = Ember.set; +var defineProperty = Ember.defineProperty; var DefaultView = Ember._MetamorphView; function setupLocation(router) { @@ -24231,7 +25983,7 @@ Ember.Router = Ember.Object.extend({ location: 'hash', init: function() { - this.router = this.constructor.router; + this.router = this.constructor.router || this.constructor.map(Ember.K); this._activeViews = {}; setupLocation(this); }, @@ -24264,6 +26016,9 @@ Ember.Router = Ember.Object.extend({ var appController = this.container.lookup('controller:application'), path = routePath(infos); + if (!('currentPath' in appController)) { + defineProperty(appController, 'currentPath'); + } set(appController, 'currentPath', path); this.notifyPropertyChange('url'); @@ -24273,34 +26028,21 @@ Ember.Router = Ember.Object.extend({ }, handleURL: function(url) { - this.router.handleURL(url); - this.notifyPropertyChange('url'); + scheduleLoadingStateEntry(this); + + var self = this; + + return this.router.handleURL(url).then(function() { + transitionCompleted(self); + }); }, - /** - Transition to another route via the `routeTo` event which - will by default be handled by ApplicationRoute. - - @method routeTo - @param {TransitionEvent} transitionEvent - */ - routeTo: function(transitionEvent) { - var handlerInfos = this.router.currentHandlerInfos; - if (handlerInfos) { - transitionEvent.sourceRoute = handlerInfos[handlerInfos.length - 1].handler; - } - - this.send('routeTo', transitionEvent); - }, - - transitionTo: function(name) { - var args = [].slice.call(arguments); - doTransition(this, 'transitionTo', args); + transitionTo: function() { + return doTransition(this, 'transitionTo', arguments); }, replaceWith: function() { - var args = [].slice.call(arguments); - doTransition(this, 'replaceWith', args); + return doTransition(this, 'replaceWith', arguments); }, generate: function() { @@ -24321,6 +26063,18 @@ Ember.Router = Ember.Object.extend({ return this.router.hasRoute(route); }, + /** + @private + + Resets the state of the router by clearing the current route + handlers and deactivating them. + + @method reset + */ + reset: function() { + this.router.reset(); + }, + _lookupActiveView: function(templateName) { var active = this._activeViews[templateName]; return active && active[0]; @@ -24342,17 +26096,6 @@ Ember.Router = Ember.Object.extend({ } }); -Ember.Router.reopenClass({ - defaultFailureHandler: { - setup: function(error) { - Ember.Logger.error('Error while loading route:', error); - - // Using setTimeout allows us to escape from the Promise's try/catch block - setTimeout(function() { throw error; }); - } - } -}); - function getHandlerFunction(router) { var seen = {}, container = router.container, DefaultRoute = container.resolve('route:basic'); @@ -24367,16 +26110,19 @@ function getHandlerFunction(router) { if (!handler) { if (name === 'loading') { return {}; } - if (name === 'failure') { return router.constructor.defaultFailureHandler; } container.register(routeName, DefaultRoute.extend()); handler = container.lookup(routeName); + + if (get(router, 'namespace.LOG_ACTIVE_GENERATION')) { + Ember.Logger.info("generated -> " + routeName, { fullName: routeName }); + } } if (name === 'application') { - // Inject default `routeTo` handler. + // Inject default `error` handler. handler.events = handler.events || {}; - handler.events.routeTo = handler.events.routeTo || Ember.TransitionEvent.defaultHandler; + handler.events.error = handler.events.error || defaultErrorHandler; } handler.routeName = name; @@ -24384,6 +26130,14 @@ function getHandlerFunction(router) { }; } +function defaultErrorHandler(error, transition) { + Ember.Logger.error('Error while loading route:', error); + + // Using setTimeout allows us to escape from the Promise's try/catch block + setTimeout(function() { throw error; }); +} + + function routePath(handlerInfos) { var path = []; @@ -24428,35 +26182,96 @@ function setupRouter(emberRouter, router, location) { } function doTransition(router, method, args) { + // Normalize blank route to root URL. + args = [].slice.call(args); + args[0] = args[0] || '/'; + var passedName = args[0], name; - if (!router.router.hasRoute(args[0])) { - name = args[0] = passedName + '.index'; - } else { + if (passedName.charAt(0) === '/') { name = passedName; + } else { + if (!router.router.hasRoute(passedName)) { + name = args[0] = passedName + '.index'; + } else { + name = passedName; + } + + Ember.assert("The route " + passedName + " was not found", router.router.hasRoute(name)); } - Ember.assert("The route " + passedName + " was not found", router.router.hasRoute(name)); + scheduleLoadingStateEntry(router); - router.router[method].apply(router.router, args); + var transitionPromise = router.router[method].apply(router.router, args); + transitionPromise.then(function() { + transitionCompleted(router); + }); + + // We want to return the configurable promise object + // so that callers of this function can use `.method()` on it, + // which obviously doesn't exist for normal RSVP promises. + return transitionPromise; +} + +function scheduleLoadingStateEntry(router) { + if (router._loadingStateActive) { return; } + router._shouldEnterLoadingState = true; + Ember.run.scheduleOnce('routerTransitions', null, enterLoadingState, router); +} + +function enterLoadingState(router) { + if (router._loadingStateActive || !router._shouldEnterLoadingState) { return; } + + var loadingRoute = router.router.getHandler('loading'); + if (loadingRoute) { + if (loadingRoute.enter) { loadingRoute.enter(); } + if (loadingRoute.setup) { loadingRoute.setup(); } + router._loadingStateActive = true; + } +} + +function exitLoadingState(router) { + router._shouldEnterLoadingState = false; + if (!router._loadingStateActive) { return; } + + var loadingRoute = router.router.getHandler('loading'); + if (loadingRoute && loadingRoute.exit) { loadingRoute.exit(); } + router._loadingStateActive = false; +} + +function transitionCompleted(router) { router.notifyPropertyChange('url'); + exitLoadingState(router); } Ember.Router.reopenClass({ map: function(callback) { - var router = this.router = new Router(); + var router = this.router; + if (!router){ + router = this.router = new Router(); + router.callbacks = []; + } + + if (get(this, 'namespace.LOG_TRANSITIONS_INTERNAL')) { + router.log = Ember.Logger.debug; + } var dsl = Ember.RouterDSL.map(function() { this.resource('application', { path: "/" }, function() { + for (var i=0; i < router.callbacks.length; i++){ + router.callbacks[i].call(this); + } callback.call(this); }); }); + router.callbacks.push(callback); router.map(dsl.generate()); return router; } }); + })(); @@ -24469,7 +26284,9 @@ Ember.Router.reopenClass({ var get = Ember.get, set = Ember.set, classify = Ember.String.classify, - fmt = Ember.String.fmt; + fmt = Ember.String.fmt, + a_forEach = Ember.EnumerableUtils.forEach, + a_replace = Ember.EnumerableUtils.replace; /** The `Ember.Route` class is used to define individual routes. Refer to @@ -24487,7 +26304,7 @@ Ember.Route = Ember.Object.extend({ */ exit: function() { this.deactivate(); - teardownView(this); + this.teardownViews(); }, /** @@ -24500,15 +26317,114 @@ Ember.Route = Ember.Object.extend({ }, /** - The collection of functions keyed by name available on this route as + The collection of functions, keyed by name, available on this route as action targets. These functions will be invoked when a matching `{{action}}` is triggered from within a template and the application's current route is this route. - Events can also be invoked from other parts of your application via `Route#send`. + Events can also be invoked from other parts of your application via `Route#send` + or `Controller#send`. - The context of event will be the this route. + The context of the event will be this route. + + ## Bubbling + + By default, an event will stop bubbling once a handler defined + on the `events` hash handles it. To continue bubbling the event, + you must return `true` from the handler. + + ## Built-in events + + There are a few built-in events pertaining to transitions that you + can use to customize transition behavior: `willTransition` and + `error`. + + ### `willTransition` + + The `willTransition` event is fired at the beginning of any + attempted transition with a `Transition` object as the sole + argument. This event can be used for aborting, redirecting, + or decorating the transition from the currently active routes. + + A good example is preventing navigation when a form is + half-filled out: + + ```js + App.ContactFormRoute = Ember.Route.extend({ + events: { + willTransition: function(transition) { + if (this.controller.get('userHasEnteredData')) { + this.controller.displayNavigationConfirm(); + transition.abort(); + } + } + } + }); + ``` + + You can also redirect elsewhere by calling + `this.transitionTo('elsewhere')` from within `willTransition`. + Note that `willTransition` will not be fired for the + redirecting `transitionTo`, since `willTransition` doesn't + fire when there is already a transition underway. If you want + subsequent `willTransition` events to fire for the redirecting + transition, you must first explicitly call + `transition.abort()`. + + ### `error` + + When attempting to transition into a route, any of the hooks + may throw an error, or return a promise that rejects, at which + point an `error` event will be fired on the partially-entered + routes, allowing for per-route error handling logic, or shared + error handling logic defined on a parent route. + + Here is an example of an error handler that will be invoked + for rejected promises / thrown errors from the various hooks + on the route, as well as any unhandled errors from child + routes: + + ```js + App.AdminRoute = Ember.Route.extend({ + beforeModel: function() { + throw "bad things!"; + // ...or, equivalently: + return Ember.RSVP.reject("bad things!"); + }, + + events: { + error: function(error, transition) { + // Assuming we got here due to the error in `beforeModel`, + // we can expect that error === "bad things!", + // but a promise model rejecting would also + // call this hook, as would any errors encountered + // in `afterModel`. + + // The `error` hook is also provided the failed + // `transition`, which can be stored and later + // `.retry()`d if desired. + + this.transitionTo('login'); + } + } + }); + ``` + + `error` events that bubble up all the way to `ApplicationRoute` + will fire a default error handler that logs the error. You can + specify your own global default error handler by overriding the + `error` handler on `ApplicationRoute`: + + ```js + App.ApplicationRoute = Ember.Route.extend({ + events: { + error: function(error, transition) { + this.controllerFor('banner').displayError(error.message); + } + } + }); + ``` @see {Ember.Route#send} @see {Handlebars.helpers.action} @@ -24535,17 +26451,6 @@ Ember.Route = Ember.Object.extend({ */ activate: Ember.K, - /** - Transition to another route via the `routeTo` event which - will by default be handled by ApplicationRoute. - - @method routeTo - @param {TransitionEvent} transitionEvent - */ - routeTo: function(transitionEvent) { - this.router.routeTo(transitionEvent); - }, - /** Transition into another route. Optionally supply a model for the route in question. The model will be serialized into the URL @@ -24557,13 +26462,6 @@ Ember.Route = Ember.Object.extend({ */ transitionTo: function(name, context) { var router = this.router; - - // If the transition is a no-op, just bail. - if (router.isActive.apply(router, arguments)) { - return; - } - - if (this._checkingRedirect) { this._redirected[this._redirectDepth] = true; } return router.transitionTo.apply(router, arguments); }, @@ -24571,19 +26469,15 @@ Ember.Route = Ember.Object.extend({ Transition into another route while replacing the current URL if possible. Identical to `transitionTo` in all other respects. + Of the bundled location types, only `history` currently supports + this behavior. + @method replaceWith @param {String} name the name of the route @param {...Object} models the */ replaceWith: function() { var router = this.router; - - // If the transition is a no-op, just bail. - if (router.isActive.apply(router, arguments)) { - return; - } - - if (this._checkingRedirect) { this._redirected[this._redirectDepth] = true; } return this.router.replaceWith.apply(this.router, arguments); }, @@ -24591,15 +26485,6 @@ Ember.Route = Ember.Object.extend({ return this.router.send.apply(this.router, arguments); }, - /** - @private - - Internal counter for tracking whether a route handler has - called transitionTo or replaceWith inside its redirect hook. - - */ - _redirectDepth: 0, - /** @private @@ -24608,64 +26493,11 @@ Ember.Route = Ember.Object.extend({ @method setup */ setup: function(context) { - // Determine if this is the top-most transition. - // If so, we'll set up a data structure to track - // whether `transitionTo` or replaceWith gets called - // inside our `redirect` hook. - // - // This is necessary because we set a flag on the route - // inside transitionTo/replaceWith to determine afterwards - // if they were called, but `setup` can be called - // recursively and we need to disambiguate where in the - // call stack the redirect happened. + var controller = this.controllerFor(this.controllerName || this.routeName, context); - // Are we the first call to setup? If so, set up the - // redirect tracking data structure, and remember that - // we're the top-most so we can clean it up later. - var isTop; - if (!this._redirected) { - isTop = true; - this._redirected = []; - } - - // Set a flag on this route saying that we are interested in - // tracking redirects, and increment the depth count. - this._checkingRedirect = true; - var depth = ++this._redirectDepth; - - // Check to see if context is set. This check preserves - // the correct arguments.length inside the `redirect` hook. - if (context === undefined) { - this.redirect(); - } else { - this.redirect(context); - } - - // After the call to `redirect` returns, decrement the depth count. - this._redirectDepth--; - this._checkingRedirect = false; - - // Save off the data structure so we can reset it on the route but - // still reference it later in this method. - var redirected = this._redirected; - - // If this is the top `setup` call in the call stack, clear the - // redirect tracking data structure. - if (isTop) { this._redirected = null; } - - // If we were redirected, there is nothing left for us to do. - // Returning false tells router.js not to continue calling setup - // on any children route handlers. - if (redirected[depth]) { - return false; - } - - var controller = this.controllerFor(this.routeName, context); - - if (controller) { - this.controller = controller; - set(controller, 'model', context); - } + // Assign the route's controller so that it can more easily be + // referenced in event handlers + this.controller = controller; if (this.setupControllers) { Ember.deprecate("Ember.Route.setupControllers is deprecated. Please use Ember.Route.setupController(controller, model) instead."); @@ -24683,29 +26515,133 @@ Ember.Route = Ember.Object.extend({ }, /** + @deprecated + A hook you can implement to optionally redirect to another route. If you call `this.transitionTo` from inside of this hook, this route will not be entered in favor of the other hook. + This hook is deprecated in favor of using the `afterModel` hook + for performing redirects after the model has resolved. + @method redirect @param {Object} model the model for this route */ redirect: Ember.K, /** - @private + This hook is the first of the route entry validation hooks + called when an attempt is made to transition into a route + or one of its children. It is called before `model` and + `afterModel`, and is appropriate for cases when: - The hook called by `router.js` to convert parameters into the context - for this handler. The public Ember hook is `model`. + 1) A decision can be made to redirect elsewhere without + needing to resolve the model first. + 2) Any async operations need to occur first before the + model is attempted to be resolved. - @method deserialize + This hook is provided the current `transition` attempt + as a parameter, which can be used to `.abort()` the transition, + save it for a later `.retry()`, or retrieve values set + on it from a previous hook. You can also just call + `this.transitionTo` to another route to implicitly + abort the `transition`. + + You can return a promise from this hook to pause the + transition until the promise resolves (or rejects). This could + be useful, for instance, for retrieving async code from + the server that is required to enter a route. + + ```js + App.PostRoute = Ember.Route.extend({ + beforeModel: function(transition) { + if (!App.Post) { + return Ember.$.getScript('/models/post.js'); + } + } + }); + ``` + + If `App.Post` doesn't exist in the above example, + `beforeModel` will use jQuery's `getScript`, which + returns a promise that resolves after the server has + successfully retrieved and executed the code from the + server. Note that if an error were to occur, it would + be passed to the `error` hook on `Ember.Route`, but + it's also possible to handle errors specific to + `beforeModel` right from within the hook (to distinguish + from the shared error handling behavior of the `error` + hook): + + ```js + App.PostRoute = Ember.Route.extend({ + beforeModel: function(transition) { + if (!App.Post) { + var self = this; + return Ember.$.getScript('post.js').then(null, function(e) { + self.transitionTo('help'); + + // Note that the above transitionTo will implicitly + // halt the transition. If you were to return + // nothing from this promise reject handler, + // according to promise semantics, that would + // convert the reject into a resolve and the + // transition would continue. To propagate the + // error so that it'd be handled by the `error` + // hook, you would have to either + return Ember.RSVP.reject(e); + // or + throw e; + }); + } + } + }); + ``` + + @method beforeModel + @param {Transition} transition + @return {Promise} if the value returned from this hook is + a promise, the transition will pause until the transition + resolves. Otherwise, non-promise return values are not + utilized in any way. */ - deserialize: function(params) { - var model = this.model(params); - return this.currentModel = model; + beforeModel: Ember.K, + + /** + This hook is called after this route's model has resolved. + It follows identical async/promise semantics to `beforeModel` + but is provided the route's resolved model in addition to + the `transition`, and is therefore suited to performing + logic that can only take place after the model has already + resolved. + + ```js + App.PostRoute = Ember.Route.extend({ + afterModel: function(posts, transition) { + if (posts.length === 1) { + this.transitionTo('post.show', posts[0]); + } + } + }); + ``` + + Refer to documentation for `beforeModel` for a description + of transition-pausing semantics when a promise is returned + from this hook. + + @method afterModel + @param {Transition} transition + @return {Promise} if the value returned from this hook is + a promise, the transition will pause until the transition + resolves. Otherwise, non-promise return values are not + utilized in any way. + */ + afterModel: function(resolvedModel, transition) { + this.redirect(resolvedModel, transition); }, + /** @private @@ -24743,10 +26679,15 @@ Ember.Route = Ember.Object.extend({ is not called. Routes without dynamic segments will always execute the model hook. + This hook follows the asynchronous/promise semantics + described in the documentation for `beforeModel`. In particular, + if a promise returned from `model` fails, the error will be + handled by the `error` hook on `Ember.Route`. + @method model @param {Object} params the parameters extracted from the URL */ - model: function(params) { + model: function(params, resolvedParentModels) { var match, name, sawParams, value; for (var prop in params) { @@ -24760,11 +26701,10 @@ Ember.Route = Ember.Object.extend({ if (!name && sawParams) { return params; } else if (!name) { return; } - var className = classify(name), - namespace = this.router.namespace, - modelClass = namespace[className]; + var modelClass = this.container.lookupFactory('model:' + name); + var namespace = get(this, 'router.namespace'); - Ember.assert("You used the dynamic segment " + name + "_id in your router, but " + namespace + "." + className + " did not exist and you did not override your route's `model` hook.", modelClass); + Ember.assert("You used the dynamic segment " + name + "_id in your router, but " + namespace + "." + classify(name) + " did not exist and you did not override your route's `model` hook.", modelClass); return modelClass.find(value); }, @@ -24822,30 +26762,41 @@ Ember.Route = Ember.Object.extend({ This method is called with the controller for the current route and the model supplied by the `model` hook. + By default, the `setupController` hook sets the `content` property of + the controller to the `model`. + + This means that your template will get a proxy for the model as its + context, and you can act as though the model itself was the context. + + The provided controller will be one resolved based on the name + of this route. + + If no explicit controller is defined, Ember will automatically create + an appropriate controller for the model. + + * if the model is an `Ember.Array` (including record arrays from Ember + Data), the controller is an `Ember.ArrayController`. + * otherwise, the controller is an `Ember.ObjectController`. + + As an example, consider the router: + ```js App.Router.map(function() { this.resource('post', {path: '/posts/:post_id'}); }); ``` - For the `post` route, the controller is `App.PostController`. - - By default, the `setupController` hook sets the `content` property of - the controller to the `model`. - - If no explicit controller is defined, the route will automatically create - an appropriate controller for the model: - - * if the model is an `Ember.Array` (including record arrays from Ember - Data), the controller is an `Ember.ArrayController`. - * otherwise, the controller is an `Ember.ObjectController`. - - This means that your template will get a proxy for the model as its - context, and you can act as though the model itself was the context. + For the `post` route, a controller named `App.PostController` would + be used if it is defined. If it is not defined, an `Ember.ObjectController` + instance would be used. @method setupController */ - setupController: Ember.K, + setupController: function(controller, context){ + if (controller && (context !== undefined)) { + set(controller, 'model', context); + } + }, /** Returns the controller for a particular route. @@ -24893,7 +26844,19 @@ Ember.Route = Ember.Object.extend({ @return {Object} the model object */ modelFor: function(name) { - var route = this.container.lookup('route:' + name); + + var route = this.container.lookup('route:' + name), + transition = this.router.router.activeTransition; + + // If we are mid-transition, we want to try and look up + // resolved parent contexts on the current transitionEvent. + if (transition) { + var modelLookupName = (route && route.routeName) || name; + if (transition.resolvedModels.hasOwnProperty(modelLookupName)) { + return transition.resolvedModels[modelLookupName]; + } + } + return route && route.currentModel; }, @@ -24980,7 +26943,12 @@ Ember.Route = Ember.Object.extend({ view = container.lookup('view:' + name), template = container.lookup('template:' + name); - if (!view && !template) { return; } + if (!view && !template) { + if (get(this.router, 'namespace.LOG_VIEW_LOOKUPS')) { + Ember.Logger.info("Could not find \"" + name + "\" template or view. Nothing will be rendered", { fullName: 'template:' + name }); + } + return; + } options = normalizeOptions(this, name, template, options); view = setupView(view, container, options); @@ -24990,14 +26958,73 @@ Ember.Route = Ember.Object.extend({ appendView(this, view, options); }, + /** + Disconnects a view that has been rendered into an outlet. + + You may pass any or all of the following options to `disconnectOutlet`: + + * `outlet`: the name of the outlet to clear (default: 'main') + * `parentView`: the name of the view containing the outlet to clear + (default: the view rendered by the parent route) + + Example: + + ```js + App.ApplicationRoute = App.Route.extend({ + events: { + showModal: function(evt) { + this.render(evt.modalName, { + outlet: 'modal', + into: 'application' + }); + }, + hideModal: function(evt) { + this.disconnectOutlet({ + outlet: 'modal', + parentView: 'application' + }); + } + } + }); + ``` + + @method disconnectOutlet + @param {Object} options the options + */ + disconnectOutlet: function(options) { + options = options || {}; + options.parentView = options.parentView ? options.parentView.replace(/\//g, '.') : parentTemplate(this); + options.outlet = options.outlet || 'main'; + + var parentView = this.router._lookupActiveView(options.parentView); + parentView.disconnectOutlet(options.outlet); + }, + willDestroy: function() { - teardownView(this); + this.teardownViews(); + }, + + teardownViews: function() { + // Tear down the top level view + if (this.teardownTopLevelView) { this.teardownTopLevelView(); } + + // Tear down any outlets rendered with 'into' + var teardownOutletViews = this.teardownOutletViews || []; + a_forEach(teardownOutletViews, function(teardownOutletView) { + teardownOutletView(); + }); + + delete this.teardownTopLevelView; + delete this.teardownOutletViews; + delete this.lastRenderedTemplate; } }); function parentRoute(route) { var handlerInfos = route.router.router.targetHandlerInfos; + if (!handlerInfos) { return; } + var parent, current; for (var i=0, l=handlerInfos.length; i @@ -25927,7 +28097,7 @@ Ember.onLoad('Ember.Handlebars', function(Handlebars) { Alternatively, a `target` option can be provided to the helper to change which object will receive the method call. This option must be a path - path to an object, accessible in the current context: + to an object, accessible in the current context: ```handlebars