From f02b33d35bc43aa5c10dd4647d8ada4787433c56 Mon Sep 17 00:00:00 2001 From: Salvatore Iovene Date: Fri, 8 Feb 2013 13:39:13 +0200 Subject: [PATCH] Upgrades Ember and Handlebars to the latest versions. Fixes #3. --- examples/calf/index.html | 4 +- examples/hoofbeats/index.html | 16 +- .../javascripts/app/controllers/allController.js | 7 + .../app/controllers/applicationController.js | 5 - .../app/controllers/mediaItemsController.js | 8 - examples/hoofbeats/javascripts/app/router.js | 33 +- .../app/views/{mediaItemsView.js => allView.js} | 8 +- examples/hoofbeats/make-wgt.sh | 2 +- grunt.js | 16 +- lib/{ember-latest.js => ember-1.0.0-pre.4.js} | 36501 ++++++++++--------- ...ndlebars-1.0.rc.1.js => handlebars-1.0.rc.2.js} | 380 +- 11 files changed, 20363 insertions(+), 16617 deletions(-) create mode 100644 examples/hoofbeats/javascripts/app/controllers/allController.js delete mode 100644 examples/hoofbeats/javascripts/app/controllers/applicationController.js delete mode 100644 examples/hoofbeats/javascripts/app/controllers/mediaItemsController.js rename examples/hoofbeats/javascripts/app/views/{mediaItemsView.js => allView.js} (68%) rename lib/{ember-latest.js => ember-1.0.0-pre.4.js} (59%) rename lib/{handlebars-1.0.rc.1.js => handlebars-1.0.rc.2.js} (79%) diff --git a/examples/calf/index.html b/examples/calf/index.html index 94f51b8..3ca63df 100644 --- a/examples/calf/index.html +++ b/examples/calf/index.html @@ -178,9 +178,9 @@ - + - + diff --git a/examples/hoofbeats/index.html b/examples/hoofbeats/index.html index 207f904..142b61b 100644 --- a/examples/hoofbeats/index.html +++ b/examples/hoofbeats/index.html @@ -24,7 +24,7 @@
- {{outlet library}} + {{outlet}}
- - - + + @@ -68,12 +68,10 @@ - - + - + diff --git a/examples/hoofbeats/javascripts/app/controllers/allController.js b/examples/hoofbeats/javascripts/app/controllers/allController.js new file mode 100644 index 0000000..225eb3e --- /dev/null +++ b/examples/hoofbeats/javascripts/app/controllers/allController.js @@ -0,0 +1,7 @@ +(function(app, Ember, _) { + var AllController = Ember.ArrayController.extend({ + content: [], + }); + + app.AllController = AllController; +})(window.Hoofbeats, window.Ember); diff --git a/examples/hoofbeats/javascripts/app/controllers/applicationController.js b/examples/hoofbeats/javascripts/app/controllers/applicationController.js deleted file mode 100644 index 75bb4ca..0000000 --- a/examples/hoofbeats/javascripts/app/controllers/applicationController.js +++ /dev/null @@ -1,5 +0,0 @@ -(function(app, Ember) { - var ApplicationController = Ember.Controller.extend({}); - - app.ApplicationController = ApplicationController; -})(window.Hoofbeats, window.Ember); diff --git a/examples/hoofbeats/javascripts/app/controllers/mediaItemsController.js b/examples/hoofbeats/javascripts/app/controllers/mediaItemsController.js deleted file mode 100644 index 62d2ce8..0000000 --- a/examples/hoofbeats/javascripts/app/controllers/mediaItemsController.js +++ /dev/null @@ -1,8 +0,0 @@ -(function(app, Ember, _) { - var MediaItemsController = Ember.ArrayController.extend({ - content: [], - }); - - app.MediaItemsController = MediaItemsController; - app.mediaItemsController = MediaItemsController.create(); -})(window.Hoofbeats, window.Ember); diff --git a/examples/hoofbeats/javascripts/app/router.js b/examples/hoofbeats/javascripts/app/router.js index 22c0537..56daa88 100644 --- a/examples/hoofbeats/javascripts/app/router.js +++ b/examples/hoofbeats/javascripts/app/router.js @@ -1,11 +1,11 @@ /* vi: set et sw=4 ts=4 si: */ (function(win, app, Ember) { - var Router = Ember.Router.extend({ - location: 'none', - - showMediaItems: Ember.Route.transitionTo('mediaItems'), + app.Router.map(function() { + this.resource('all', {path: '/'}); + }); - initLibrary: function() { + app.AllRoute = Ember.Route.extend({ + setupController: function(controller) { var self = this; if (app.library !== null) { @@ -19,26 +19,9 @@ self.initLibrary(); }, 100); } - }, - - root: Ember.Route.extend({ - index: Ember.Route.extend({ - route: '/', - redirectsTo: 'mediaItems' - }), - - mediaItems: Ember.Route.extend({ - route: '/mediaItems', - connectOutlets: function(router) { - var controller = router.get('applicationController'); - router.initLibrary(); - controller.connectOutlet( - 'library', 'mediaItems', app.MediaItem.findAll()); - } - }) - }) + model: function() { + return app.MediaItem.findAll(); + }, }); - - app.Router = Router; }(window, window.Hoofbeats, window.Ember)); diff --git a/examples/hoofbeats/javascripts/app/views/mediaItemsView.js b/examples/hoofbeats/javascripts/app/views/allView.js similarity index 68% rename from examples/hoofbeats/javascripts/app/views/mediaItemsView.js rename to examples/hoofbeats/javascripts/app/views/allView.js index c751792..394cc86 100644 --- a/examples/hoofbeats/javascripts/app/views/mediaItemsView.js +++ b/examples/hoofbeats/javascripts/app/views/allView.js @@ -1,13 +1,15 @@ /* vi: set et sw=4 ts=4 si: */ (function(app, Ember) { - var MediaItemsView = Ember.View.extend({ - templateName: 'mediaItems', + var AllView = Ember.View.extend({ + templateName: 'all' + /* classNames: ['mediaItems ch-simple-scrollable'], didInsertElement: function() { this.$().ch_simple_scrollable('enable'); } + */ }); - app.MediaItemsView = MediaItemsView; + app.AllView = AllView; })(window.Hoofbeats, window.Ember); diff --git a/examples/hoofbeats/make-wgt.sh b/examples/hoofbeats/make-wgt.sh index 7c3a439..5418bd9 100755 --- a/examples/hoofbeats/make-wgt.sh +++ b/examples/hoofbeats/make-wgt.sh @@ -45,5 +45,5 @@ if [[ -f $PROJECT_NAME.wgt ]] ; then rm $PROJECT_NAME.wgt fi -zip --exclude stats/utils/\* stats/.git -r $PROJECT_NAME.wgt index.html icon.png javascripts stylesheets lib +zip --exclude stats/utils/\* stats/.git -r $PROJECT_NAME.wgt index.html icon.png javascripts stylesheets lib templates zip -j $PROJECT_NAME.wgt $CONFIG_FILE diff --git a/grunt.js b/grunt.js index 9b77e3a..cbbe9b4 100644 --- a/grunt.js +++ b/grunt.js @@ -248,16 +248,16 @@ module.exports = function(grunt) { 'examples/calf/lib/': [ 'dist/cowhide-default.css', 'dist/cowhide.js', - 'lib/handlebars-1.0.rc.1.js', - 'lib/ember-latest.js' + 'lib/handlebars-1.0.rc.2.js', + 'lib/ember-1.0.0-pre.4.js' ], 'examples/calf/lib/images/': ['dist/images/**'], 'examples/hoofbeats/lib/': [ 'dist/cowhide-default.css', 'dist/cowhide.js', - 'lib/handlebars-1.0.rc.1.js', - 'lib/ember-latest.js' + 'lib/handlebars-1.0.rc.2.js', + 'lib/ember-1.0.0-pre.4.js' ], 'examples/hoofbeats/lib/images/': ['dist/images/**'] } @@ -271,8 +271,8 @@ module.exports = function(grunt) { 'dist/images/', 'dist/cowhide-default.css', 'dist/cowhide.js', - 'lib/handlebars-1.0.rc.1.js', - 'lib/ember-latest.js' + 'lib/handlebars-1.0.rc.2.js', + 'lib/ember-1.0.0-pre.4.js' ], 'dist/examples/calf/lib/images/': ['dist/images/**'], @@ -280,8 +280,8 @@ module.exports = function(grunt) { 'dist/images/', 'dist/cowhide-default.css', 'dist/cowhide.js', - 'lib/handlebars-1.0.rc.1.js', - 'lib/ember-latest.js' + 'lib/handlebars-1.0.rc.2.js', + 'lib/ember-1.0.0-pre.4.js' ], 'dist/examples/hoofbeats/lib/images/': ['dist/images/**'] } diff --git a/lib/ember-latest.js b/lib/ember-1.0.0-pre.4.js similarity index 59% rename from lib/ember-latest.js rename to lib/ember-1.0.0-pre.4.js index 4525e71..f0a3f2c 100644 --- a/lib/ember-latest.js +++ b/lib/ember-1.0.0-pre.4.js @@ -1,6 +1,5 @@ -// Version: v1.0.pre-160-g7d62790 -// Last commit: 7d62790 (2012-09-26 15:59:36 -0700) - +// Version: v1.0.0-pre.4 +// Last commit: 855db1a (2013-01-17 23:06:53 -0800) (function() { /*global __fail__*/ @@ -32,18 +31,19 @@ if (!('MANDATORY_SETTER' in Ember.ENV)) { /** Define an assertion that will throw an exception if the condition is not - met. Ember build tools will remove any calls to Ember.assert() when + met. Ember build tools will remove any calls to `Ember.assert()` when doing a production build. Example: - // Test for truthiness - Ember.assert('Must pass a valid object', obj); - // Fail unconditionally - Ember.assert('This code path should never be run') + ```javascript + // Test for truthiness + Ember.assert('Must pass a valid object', obj); + // Fail unconditionally + Ember.assert('This code path should never be run') + ``` @method assert - @param {String} desc A description of the assertion. This will become + @param {String} desc A description of the assertion. This will become the text of the Error thrown if the assertion fails. - @param {Boolean} test Must be truthy for the assertion to pass. If falsy, an exception will be thrown. */ @@ -54,7 +54,7 @@ Ember.assert = function(desc, test) { /** Display a warning with the provided message. Ember build tools will - remove any calls to Ember.warn() when doing a production build. + remove any calls to `Ember.warn()` when doing a production build. @method warn @param {String} message A warning to display. @@ -71,7 +71,7 @@ Ember.warn = function(message, test) { /** Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only). Ember build tools will remove any calls to - Ember.deprecate() when doing a production build. + `Ember.deprecate()` when doing a production build. @method deprecate @param {String} message A description of the deprecation. @@ -118,7 +118,7 @@ Ember.deprecate = function(message, test) { Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only) when the wrapped method is called. - Ember build tools will not remove calls to Ember.deprecateFunc(), though + Ember build tools will not remove calls to `Ember.deprecateFunc()`, though no warnings will be shown in production. @method deprecateFunc @@ -132,18 +132,51 @@ Ember.deprecateFunc = function(message, func) { }; }; - -window.ember_assert = Ember.deprecateFunc("ember_assert is deprecated. Please use Ember.assert instead.", Ember.assert); -window.ember_warn = Ember.deprecateFunc("ember_warn is deprecated. Please use Ember.warn instead.", Ember.warn); -window.ember_deprecate = Ember.deprecateFunc("ember_deprecate is deprecated. Please use Ember.deprecate instead.", Ember.deprecate); -window.ember_deprecateFunc = Ember.deprecateFunc("ember_deprecateFunc is deprecated. Please use Ember.deprecateFunc instead.", Ember.deprecateFunc); +if ('undefined' !== typeof window) { + window.ember_assert = Ember.deprecateFunc("ember_assert is deprecated. Please use Ember.assert instead.", Ember.assert); + window.ember_warn = Ember.deprecateFunc("ember_warn is deprecated. Please use Ember.warn instead.", Ember.warn); + window.ember_deprecate = Ember.deprecateFunc("ember_deprecate is deprecated. Please use Ember.deprecate instead.", Ember.deprecate); + window.ember_deprecateFunc = Ember.deprecateFunc("ember_deprecateFunc is deprecated. Please use Ember.deprecateFunc instead.", Ember.deprecateFunc); +} })(); -// Version: v1.0.pre-160-g7d62790 -// Last commit: 7d62790 (2012-09-26 15:59:36 -0700) +// Version: v1.0.0-pre.3-19-g015138e +// Last commit: 015138e (2013-01-17 23:02:17 -0800) + + +(function() { +var define, requireModule; + +(function() { + var registry = {}, seen = {}; + + define = function(name, deps, callback) { + registry[name] = { deps: deps, callback: callback }; + }; + + requireModule = function(name) { + if (seen[name]) { return seen[name]; } + seen[name] = {}; + + var mod = registry[name], + deps = mod.deps, + callback = mod.callback, + reified = [], + exports; + for (var i=0, l=deps.length; i -1; -}; - -// From: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/map -var arrayMap = isNativeFunc(Array.prototype.map) ? Array.prototype.map : function(fun /*, thisp */) { - //"use strict"; - - if (this === void 0 || this === null) { - throw new TypeError(); - } - - var t = Object(this); - var len = t.length >>> 0; - if (typeof fun !== "function") { - throw new TypeError(); - } - - var res = new Array(len); - var thisp = arguments[1]; - for (var i = 0; i < len; i++) { - if (i in t) { - res[i] = fun.call(thisp, t[i], i, t); - } - } - - return res; -}; - -// From: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/foreach -var arrayForEach = isNativeFunc(Array.prototype.forEach) ? Array.prototype.forEach : function(fun /*, thisp */) { - //"use strict"; - - if (this === void 0 || this === null) { - throw new TypeError(); - } - - var t = Object(this); - var len = t.length >>> 0; - if (typeof fun !== "function") { - throw new TypeError(); - } - - var thisp = arguments[1]; - for (var i = 0; i < len; i++) { - if (i in t) { - fun.call(thisp, t[i], i, t); - } - } -}; - -var arrayIndexOf = isNativeFunc(Array.prototype.indexOf) ? Array.prototype.indexOf : function (obj, fromIndex) { - if (fromIndex === null || fromIndex === undefined) { fromIndex = 0; } - else if (fromIndex < 0) { fromIndex = Math.max(0, this.length + fromIndex); } - for (var i = fromIndex, j = this.length; i < j; i++) { - if (this[i] === obj) { return i; } - } - return -1; -}; - -Ember.ArrayPolyfills = { - map: arrayMap, - forEach: arrayForEach, - indexOf: arrayIndexOf -}; - -var utils = Ember.EnumerableUtils = { - map: function(obj, callback, thisArg) { - return obj.map ? obj.map.call(obj, callback, thisArg) : arrayMap.call(obj, callback, thisArg); - }, - - forEach: function(obj, callback, thisArg) { - return obj.forEach ? obj.forEach.call(obj, callback, thisArg) : arrayForEach.call(obj, callback, thisArg); - }, - - indexOf: function(obj, element, index) { - return obj.indexOf ? obj.indexOf.call(obj, element, index) : arrayIndexOf.call(obj, element, index); - }, - - indexesOf: function(obj, elements) { - return elements === undefined ? [] : utils.map(elements, function(item) { - return utils.indexOf(obj, item); - }); - }, - - removeObject: function(array, item) { - var index = utils.indexOf(array, item); - if (index !== -1) { array.splice(index, 1); } +Ember.merge = function(original, updates) { + for (var prop in updates) { + if (!updates.hasOwnProperty(prop)) { continue; } + original[prop] = updates[prop]; } }; - -if (Ember.SHIM_ES5) { - if (!Array.prototype.map) { - Array.prototype.map = arrayMap; - } - - if (!Array.prototype.forEach) { - Array.prototype.forEach = arrayForEach; - } - - if (!Array.prototype.indexOf) { - Array.prototype.indexOf = arrayIndexOf; - } -} - })(); @@ -529,13 +407,16 @@ var platform = Ember.platform = {}; /** - Identical to Object.create(). Implements if not available natively. + Identical to `Object.create()`. Implements if not available natively. + @method create @for Ember */ Ember.create = Object.create; -if (!Ember.create) { +// STUB_OBJECT_CREATE allows us to override other libraries that stub +// Object.create different than we would prefer +if (!Ember.create || Ember.ENV.STUB_OBJECT_CREATE) { var K = function() {}; Ember.create = function(obj, props) { @@ -630,7 +511,7 @@ if (defineProperty) { */ /** - Identical to Object.defineProperty(). Implements as much functionality + Identical to `Object.defineProperty()`. Implements as much functionality as possible if not available natively. @method defineProperty @@ -672,6 +553,7 @@ if (Ember.ENV.MANDATORY_SETTER && !platform.hasPropertyAccessors) { @module ember-metal */ + var o_defineProperty = Ember.platform.defineProperty, o_create = Ember.create, // Used for guid generation... @@ -710,20 +592,18 @@ var GUID_DESC = { @private Generates a new guid, optionally saving the guid to the object that you - pass in. You will rarely need to use this method. Instead you should - call Ember.guidFor(obj), which return an existing guid if available. + pass in. You will rarely need to use this method. Instead you should + call `Ember.guidFor(obj)`, which return an existing guid if available. @method generateGuid @for Ember - @param {Object} [obj] Object the guid will be used for. If passed in, the guid will + @param {Object} [obj] Object the guid will be used for. If passed in, the guid will be saved on the object and reused whenever you pass the same object again. If no object is passed, just generate a new guid. - - @param {String} [prefix] Prefix to place in front of the guid. Useful when you want to + @param {String} [prefix] Prefix to place in front of the guid. Useful when you want to separate the guid into separate namespaces. - @return {String} the guid */ Ember.generateGuid = function generateGuid(obj, prefix) { @@ -739,9 +619,10 @@ Ember.generateGuid = function generateGuid(obj, prefix) { /** @private - Returns a unique id for the object. If the object does not yet have - a guid, one will be assigned to it. You can call this on any object, - Ember.Object-based or not, but be aware that it will add a _guid property. + Returns a unique id for the object. If the object does not yet have a guid, + one will be assigned to it. You can call this on any object, + `Ember.Object`-based or not, but be aware that it will add a `_guid` + property. You can also use this method on DOM Element objects. @@ -836,14 +717,18 @@ if (isDefinePropertySimulated) { // jQuery.extend() by having a property that fails // hasOwnProperty check. Meta.prototype.__preventPlainObject__ = true; + + // Without non-enumerable properties, meta objects will be output in JSON + // unless explicitly suppressed + Meta.prototype.toJSON = function () { }; } /** - Retrieves the meta hash for an object. If 'writable' is true ensures the + Retrieves the meta hash for an object. If `writable` is true ensures the hash is writable for this object as well. The meta object contains information about computed property descriptors as - well as any watched properties and other information. You generally will + well as any watched properties and other information. You generally will not access this information directly but instead work with higher level methods that manipulate this hash indirectly. @@ -852,10 +737,8 @@ if (isDefinePropertySimulated) { @private @param {Object} obj The object to retrieve meta for - - @param {Boolean} [writable=true] Pass false if you do not intend to modify + @param {Boolean} [writable=true] Pass `false` if you do not intend to modify the meta hash, allowing the method to avoid making an unnecessary copy. - @return {Hash} */ Ember.meta = function meta(obj, writable) { @@ -915,7 +798,7 @@ Ember.setMeta = function setMeta(obj, property, value) { This method allows extensions to deeply clone a series of nested hashes or other complex objects. For instance, the event system might pass - ['listeners', 'foo:change', 'ember157'] to `prepareMetaPath`, which will + `['listeners', 'foo:change', 'ember157']` to `prepareMetaPath`, which will walk down the keys provided. For each key, if the key does not exist, it is created. If it already @@ -960,7 +843,7 @@ Ember.metaPath = function metaPath(obj, path, writable) { @private Wraps the passed function so that `this._super` will point to the superFunc - when the function is invoked. This is the primitive we use to implement + when the function is invoked. This is the primitive we use to implement calls to super. @method wrap @@ -970,19 +853,21 @@ Ember.metaPath = function metaPath(obj, path, writable) { @return {Function} wrapped function. */ Ember.wrap = function(func, superFunc) { - function K() {} - var newFunc = function() { + function superWrapper() { var ret, sup = this._super; this._super = superFunc || K; ret = func.apply(this, arguments); this._super = sup; return ret; - }; + } - newFunc.base = func; - return newFunc; + superWrapper.wrappedFunction = func; + superWrapper.__ember_observes__ = func.__ember_observes__; + superWrapper.__ember_observesBefore__ = func.__ember_observesBefore__; + + return superWrapper; }; /** @@ -994,12 +879,14 @@ Ember.wrap = function(func, superFunc) { - the object is a native Array - the object is an Object, and has a length property - Unlike Ember.typeOf this method returns true even if the passed object is - not formally array but appears to be array-like (i.e. implements Ember.Array) + Unlike `Ember.typeOf` this method returns true even if the passed object is + not formally array but appears to be array-like (i.e. implements `Ember.Array`) - Ember.isArray(); // false - Ember.isArray([]); // true - Ember.isArray( Ember.ArrayProxy.create({ content: [] }) ); // true + ```javascript + Ember.isArray(); // false + Ember.isArray([]); // true + Ember.isArray( Ember.ArrayProxy.create({ content: [] }) ); // true + ``` @method isArray @for Ember @@ -1015,18 +902,20 @@ Ember.isArray = function(obj) { }; /** - Forces the passed object to be part of an array. If the object is already - an array or array-like, returns the object. Otherwise adds the object to - an array. If obj is null or undefined, returns an empty array. - - Ember.makeArray(); => [] - Ember.makeArray(null); => [] - Ember.makeArray(undefined); => [] - Ember.makeArray('lindsay'); => ['lindsay'] - Ember.makeArray([1,2,42]); => [1,2,42] + Forces the passed object to be part of an array. If the object is already + an array or array-like, returns the object. Otherwise adds the object to + an array. If obj is `null` or `undefined`, returns an empty array. - var controller = Ember.ArrayProxy.create({ content: [] }); - Ember.makeArray(controller) === controller; => true + ```javascript + Ember.makeArray(); // [] + Ember.makeArray(null); // [] + Ember.makeArray(undefined); // [] + Ember.makeArray('lindsay'); // ['lindsay'] + Ember.makeArray([1,2,42]); // [1,2,42] + + var controller = Ember.ArrayProxy.create({ content: [] }); + Ember.makeArray(controller) === controller; // true + ``` @method makeArray @for Ember @@ -1069,1740 +958,1526 @@ Ember.tryInvoke = function(obj, methodName, args) { } }; -})(); - +// https://github.com/emberjs/ember.js/pull/1617 +var needsFinallyFix = (function() { + var count = 0; + try{ + try { } + finally { + count++; + throw new Error('needsFinallyFixTest'); + } + } catch (e) {} + return count !== 1; +})(); -(function() { /** -@module ember-metal -*/ - -/* - JavaScript (before ES6) does not have a Map implementation. Objects, - which are often used as dictionaries, may only have Strings as keys. + Provides try { } finally { } functionality, while working + around Safari's double finally bug. - Because Ember has a way to get a unique identifier for every object - via `Ember.guidFor`, we can implement a performant Map with arbitrary - keys. Because it is commonly used in low-level bookkeeping, Map is - implemented as a pure JavaScript object for performance. + @method tryFinally + @for Ember + @param {Function} function The function to run the try callback + @param {Function} function The function to run the finally callback + @param [binding] + @return {anything} The return value is the that of the finalizer, + unless that valueis undefined, in which case it is the return value + of the tryable +*/ - This implementation follows the current iteration of the ES6 proposal - for maps (http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets), - with two exceptions. First, because we need our implementation to be - pleasant on older browsers, we do not use the `delete` name (using - `remove` instead). Second, as we do not have the luxury of in-VM - iteration, we implement a forEach method for iteration. +if (needsFinallyFix) { + Ember.tryFinally = function(tryable, finalizer, binding) { + var result, finalResult, finalError; - Map is mocked out to look like an Ember object, so you can do - `Ember.Map.create()` for symmetry with other Ember classes. -*/ -var guidFor = Ember.guidFor, - indexOf = Ember.ArrayPolyfills.indexOf; + binding = binding || this; -var copy = function(obj) { - var output = {}; + try { + result = tryable.call(binding); + } finally { + try { + finalResult = finalizer.call(binding); + } catch (e){ + finalError = e; + } + } - for (var prop in obj) { - if (obj.hasOwnProperty(prop)) { output[prop] = obj[prop]; } - } + if (finalError) { throw finalError; } - return output; -}; + return (finalResult === undefined) ? result : finalResult; + }; +} else { + Ember.tryFinally = function(tryable, finalizer, binding) { + var result, finalResult; -var copyMap = function(original, newObject) { - var keys = original.keys.copy(), - values = copy(original.values); + binding = binding || this; - newObject.keys = keys; - newObject.values = values; + try { + result = tryable.call(binding); + } finally { + finalResult = finalizer.call(binding); + } - return newObject; -}; + return (finalResult === undefined) ? result : finalResult; + }; +} /** - This class is used internally by Ember.js and Ember Data. - Please do not use it at this time. We plan to clean it up - and add many tests soon. + Provides try { } catch finally { } functionality, while working + around Safari's double finally bug. - @class OrderedSet - @namespace Ember - @constructor - @private + @method tryCatchFinally + @for Ember + @param {Function} function The function to run the try callback + @param {Function} function The function to run the catchable callback + @param {Function} function The function to run the finally callback + @param [binding] + @return {anything} The return value is the that of the finalizer, + unless that value is undefined, in which case it is the return value + of the tryable. */ -var OrderedSet = Ember.OrderedSet = function() { - this.clear(); -}; +if (needsFinallyFix) { + Ember.tryCatchFinally = function(tryable, catchable, finalizer, binding) { + var result, finalResult, finalError, finalReturn; -/** - @method create - @static - @return {Ember.OrderedSet} -*/ -OrderedSet.create = function() { - return new OrderedSet(); -}; + binding = binding || this; + try { + result = tryable.call(binding); + } catch(error) { + result = catchable.call(binding, error); + } finally { + try { + finalResult = finalizer.call(binding); + } catch (e){ + finalError = e; + } + } -OrderedSet.prototype = { - /** - @method clear - */ - clear: function() { - this.presenceSet = {}; - this.list = []; - }, + if (finalError) { throw finalError; } - /** - @method add - @param obj - */ - add: function(obj) { - var guid = guidFor(obj), - presenceSet = this.presenceSet, - list = this.list; + return (finalResult === undefined) ? result : finalResult; + }; +} else { + Ember.tryCatchFinally = function(tryable, catchable, finalizer, binding) { + var result, finalResult; - if (guid in presenceSet) { return; } + binding = binding || this; - presenceSet[guid] = true; - list.push(obj); - }, + try { + result = tryable.call(binding); + } catch(error) { + result = catchable.call(binding, error); + } finally { + finalResult = finalizer.call(binding); + } - /** - @method remove - @param obj - */ - remove: function(obj) { - var guid = guidFor(obj), - presenceSet = this.presenceSet, - list = this.list; + return (finalResult === undefined) ? result : finalResult; + }; +} - delete presenceSet[guid]; +})(); - var index = indexOf.call(list, obj); - if (index > -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; +(function() { +// Ember.tryCatchFinally - return guid in presenceSet; - }, +/** + The purpose of the Ember Instrumentation module is + to provide efficient, general-purpose instrumentation + for Ember. - /** - @method forEach - @param {Function} function - @param target - */ - forEach: function(fn, self) { - // allow mutation during iteration - var list = this.list.slice(); + Subscribe to a listener by using `Ember.subscribe`: - for (var i = 0, j = list.length; i < j; i++) { - fn.call(self, list[i]); - } - }, + ```javascript + Ember.subscribe("render", { + before: function(name, timestamp, payload) { - /** - @method toArray - @return {Array} - */ - toArray: function() { - return this.list.slice(); - }, + }, - /** - @method copy - @return {Ember.OrderedSet} - */ - copy: function() { - var set = new OrderedSet(); + after: function(name, timestamp, payload) { - set.presenceSet = copy(this.presenceSet); - set.list = this.list.slice(); + } + }); + ``` - return set; - } -}; + If you return a value from the `before` callback, that same + value will be passed as a fourth parameter to the `after` + callback. -/** - A Map stores values indexed by keys. Unlike JavaScript's - default Objects, the keys of a Map can be any JavaScript - object. + Instrument a block of code by using `Ember.instrument`: - Internally, a Map has two data structures: + ```javascript + Ember.instrument("render.handlebars", payload, function() { + // rendering logic + }, binding); + ``` - `keys`: an OrderedSet of all of the existing keys - `values`: a JavaScript Object indexed by the - Ember.guidFor(key) + Event names passed to `Ember.instrument` are namespaced + by periods, from more general to more specific. Subscribers + can listen for events by whatever level of granularity they + are interested in. - 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`. + In the above example, the event is `render.handlebars`, + and the subscriber listened for all events beginning with + `render`. It would receive callbacks for events named + `render`, `render.handlebars`, `render.container`, or + even `render.handlebars.layout`. - @class Map + @class Instrumentation @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(); +Ember.Instrumentation = {}; + +var subscribers = [], cache = {}; + +var populateListeners = function(name) { + var listeners = [], subscriber; + + for (var i=0, l=subscribers.length; i -1; +}; -// .......................................................... -// GET AND SET -// -// If we are on a platform that supports accessors we can get use those. -// Otherwise simulate accessors by looking up the property directly on the -// object. +// From: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/map +var arrayMap = isNativeFunc(Array.prototype.map) ? Array.prototype.map : function(fun /*, thisp */) { + //"use strict"; -/** - Gets the value of a property on an object. If the property is computed, - the function will be invoked. If the property is not defined but the - object implements the unknownProperty() method then that will be invoked. + if (this === void 0 || this === null) { + throw new TypeError(); + } - If you plan to run on IE8 and older browsers then you should use this - method anytime you want to retrieve a property on an object that you don't - know for sure is private. (My convention only properties beginning with - an underscore '_' are considered private.) + var t = Object(this); + var len = t.length >>> 0; + if (typeof fun !== "function") { + throw new TypeError(); + } - On all newer browsers, you only need to use this method to retrieve - properties if the property might not be defined on the object and you want - to respect the unknownProperty() handler. Otherwise you can ignore this - method. + var res = new Array(len); + var thisp = arguments[1]; + for (var i = 0; i < len; i++) { + if (i in t) { + res[i] = fun.call(thisp, t[i], i, t); + } + } - Note that if the obj itself is null, this method will simply return - undefined. + return res; +}; - @method get - @for Ember - @param {Object} obj The object to retrieve from. - @param {String} keyName The property key to retrieve - @return {Object} the property value or null. -*/ -get = function get(obj, keyName) { - // Helpers that operate with 'this' within an #each - if (keyName === '') { - return obj; - } +// From: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/foreach +var arrayForEach = isNativeFunc(Array.prototype.forEach) ? Array.prototype.forEach : function(fun /*, thisp */) { + //"use strict"; - if (!keyName && 'string'===typeof obj) { - keyName = obj; - obj = null; + if (this === void 0 || this === null) { + throw new TypeError(); } - if (!obj || keyName.indexOf('.') !== -1) { - return getPath(obj, keyName); + var t = Object(this); + var len = t.length >>> 0; + if (typeof fun !== "function") { + throw new TypeError(); } - Ember.assert("You need to provide an object and key to `get`.", !!obj && keyName); - - var meta = obj[META_KEY], desc = meta && meta.descs[keyName], ret; - if (desc) { - return desc.get(obj, keyName); - } else { - if (MANDATORY_SETTER && meta && meta.watching[keyName] > 0) { - ret = meta.values[keyName]; - } else { - ret = obj[keyName]; - } - - if (ret === undefined && - 'object' === typeof obj && !(keyName in obj) && 'function' === typeof obj.unknownProperty) { - return obj.unknownProperty(keyName); + var thisp = arguments[1]; + for (var i = 0; i < len; i++) { + if (i in t) { + fun.call(thisp, t[i], i, t); } + } +}; - return ret; +var arrayIndexOf = isNativeFunc(Array.prototype.indexOf) ? Array.prototype.indexOf : function (obj, fromIndex) { + if (fromIndex === null || fromIndex === undefined) { fromIndex = 0; } + else if (fromIndex < 0) { fromIndex = Math.max(0, this.length + fromIndex); } + for (var i = fromIndex, j = this.length; i < j; i++) { + if (this[i] === obj) { return i; } } + return -1; }; -/** - Sets the value of a property on an object, respecting computed properties - and notifying observers and other listeners of the change. If the - property is not defined but the object implements the unknownProperty() - method then that will be invoked as well. +Ember.ArrayPolyfills = { + map: arrayMap, + forEach: arrayForEach, + indexOf: arrayIndexOf +}; - If you plan to run on IE8 and older browsers then you should use this - method anytime you want to set a property on an object that you don't - know for sure is private. (My convention only properties beginning with - an underscore '_' are considered private.) +var utils = Ember.EnumerableUtils = { + map: function(obj, callback, thisArg) { + return obj.map ? obj.map.call(obj, callback, thisArg) : arrayMap.call(obj, callback, thisArg); + }, - On all newer browsers, you only need to use this method to set - properties if the property might not be defined on the object and you want - to respect the unknownProperty() handler. Otherwise you can ignore this - method. + forEach: function(obj, callback, thisArg) { + return obj.forEach ? obj.forEach.call(obj, callback, thisArg) : arrayForEach.call(obj, callback, thisArg); + }, - @method set - @for Ember - @param {Object} obj The object to modify. - @param {String} keyName The property key to set - @param {Object} value The value to set - @return {Object} the passed value. -*/ -set = function set(obj, keyName, value, tolerant) { - if (typeof obj === 'string') { - Ember.assert("Path '" + obj + "' must be global if no obj is given.", IS_GLOBAL.test(obj)); - value = keyName; - keyName = obj; - obj = null; - } + indexOf: function(obj, element, index) { + return obj.indexOf ? obj.indexOf.call(obj, element, index) : arrayIndexOf.call(obj, element, index); + }, - if (!obj || keyName.indexOf('.') !== -1) { - return setPath(obj, keyName, value, tolerant); - } + indexesOf: function(obj, elements) { + return elements === undefined ? [] : utils.map(elements, function(item) { + return utils.indexOf(obj, item); + }); + }, - Ember.assert("You need to provide an object and key to `set`.", !!obj && keyName !== undefined); - Ember.assert('calling set on destroyed object', !obj.isDestroyed); + addObject: function(array, item) { + var index = utils.indexOf(array, item); + if (index === -1) { array.push(item); } + }, - var meta = obj[META_KEY], desc = meta && meta.descs[keyName], - isUnknown, currentValue; - if (desc) { - desc.set(obj, keyName, value); - } - else { - isUnknown = 'object' === typeof obj && !(keyName in obj); + removeObject: function(array, item) { + var index = utils.indexOf(array, item); + if (index !== -1) { array.splice(index, 1); } + }, - // setUnknownProperty is called if `obj` is an object, - // the property does not already exist, and the - // `setUnknownProperty` method exists on the object - if (isUnknown && 'function' === typeof obj.setUnknownProperty) { - obj.setUnknownProperty(keyName, value); - } else if (meta && meta.watching[keyName] > 0) { - if (MANDATORY_SETTER) { - currentValue = meta.values[keyName]; - } else { - currentValue = obj[keyName]; - } - // only trigger a change if the value has changed - if (value !== currentValue) { - Ember.propertyWillChange(obj, keyName); - if (MANDATORY_SETTER) { - if (currentValue === undefined && !(keyName in obj)) { - Ember.defineProperty(obj, keyName, null, value); // setup mandatory setter - } else { - meta.values[keyName] = value; - } - } else { - obj[keyName] = value; - } - Ember.propertyDidChange(obj, keyName); - } + replace: function(array, idx, amt, objects) { + if (array.replace) { + return array.replace(idx, amt, objects); } else { - obj[keyName] = value; + var args = Array.prototype.concat.apply([idx, amt], objects); + return array.splice.apply(array, args); } } - return value; }; -function firstKey(path) { - return path.match(FIRST_KEY)[0]; -} - -// assumes path is already normalized -function normalizeTuple(target, path) { - var hasThis = HAS_THIS.test(path), - isGlobal = !hasThis && IS_GLOBAL_PATH.test(path), - key; - - if (!target || isGlobal) target = window; - if (hasThis) path = path.slice(5); - if (target === window) { - key = firstKey(path); - target = get(target, key); - path = path.slice(key.length+1); +if (Ember.SHIM_ES5) { + if (!Array.prototype.map) { + Array.prototype.map = arrayMap; } - // must return some kind of path to be valid else other things will break. - if (!path || path.length===0) throw new Error('Invalid Path'); + if (!Array.prototype.forEach) { + Array.prototype.forEach = arrayForEach; + } - return [ target, path ]; + if (!Array.prototype.indexOf) { + Array.prototype.indexOf = arrayIndexOf; + } } -function getPath(root, path) { - var hasThis, parts, tuple, idx, len; +})(); - // If there is no root and path is a key name, return that - // property from the global object. - // E.g. get('Ember') -> Ember - if (root === null && path.indexOf('.') === -1) { return get(window, path); } - // detect complicated paths and normalize them - hasThis = HAS_THIS.test(path); - if (!root || hasThis) { - tuple = normalizeTuple(root, path); - root = tuple[0]; - path = tuple[1]; - tuple.length = 0; - } - - parts = path.split("."); - len = parts.length; - for (idx=0; root && idx -1) { + list.splice(index, 1); + } + }, + /** + @method isEmpty + @return {Boolean} + */ + isEmpty: function() { + return this.list.length === 0; + }, -if (Ember.config.overrideAccessors) { - Ember.config.overrideAccessors(); - get = Ember.get; - set = Ember.set; -} + /** + @method has + @param obj + @return {Boolean} + */ + has: function(obj) { + var guid = guidFor(obj), + presenceSet = this.presenceSet; -})(); + return guid in presenceSet; + }, + /** + @method forEach + @param {Function} function + @param target + */ + forEach: function(fn, self) { + // allow mutation during iteration + var list = this.list.slice(); + for (var i = 0, j = list.length; i < j; i++) { + fn.call(self, list[i]); + } + }, -(function() { -/** -@module ember-metal -*/ + /** + @method toArray + @return {Array} + */ + toArray: function() { + return this.list.slice(); + }, -var GUID_KEY = Ember.GUID_KEY, - META_KEY = Ember.META_KEY, - EMPTY_META = Ember.EMPTY_META, - metaFor = Ember.meta, - o_create = Ember.create, - objectDefineProperty = Ember.platform.defineProperty; + /** + @method copy + @return {Ember.OrderedSet} + */ + copy: function() { + var set = new OrderedSet(); -var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER; + set.presenceSet = copy(this.presenceSet); + set.list = this.list.slice(); -// .......................................................... -// DESCRIPTOR -// + return set; + } +}; /** - Objects of this type can implement an interface to responds requests to - get and set. The default implementation handles simple properties. + A Map stores values indexed by keys. Unlike JavaScript's + default Objects, the keys of a Map can be any JavaScript + object. - You generally won't need to create or subclass this directly. + Internally, a Map has two data structures: - @class Descriptor + 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 Descriptor = Ember.Descriptor = function() {}; - -// .......................................................... -// DEFINING PROPERTIES API -// +var Map = Ember.Map = function() { + this.keys = Ember.OrderedSet.create(); + this.values = {}; +}; /** - @private - - NOTE: This is a low-level method used by other parts of the API. You almost - never want to call this method directly. Instead you should use Ember.mixin() - to define new properties. - - Defines a property on an object. This method works much like the ES5 - Object.defineProperty() method except that it can also accept computed - properties and other special descriptors. - - Normally this method takes only three parameters. However if you pass an - instance of Ember.Descriptor as the third param then you can pass an optional - value as the fourth parameter. This is often more efficient than creating - new descriptor hashes for each property. + @method create + @static +*/ +Map.create = function() { + return new Map(); +}; - ## Examples +Map.prototype = { + /** + Retrieve the value associated with a given key. - // ES5 compatible mode - Ember.defineProperty(contact, 'firstName', { - writable: true, - configurable: false, - enumerable: true, - value: 'Charles' - }); + @method get + @param {anything} key + @return {anything} the value associated with the key, or `undefined` + */ + get: function(key) { + var values = this.values, + guid = guidFor(key); - // define a simple property - Ember.defineProperty(contact, 'lastName', undefined, 'Jolley'); + return values[guid]; + }, - // define a computed property - Ember.defineProperty(contact, 'fullName', Ember.computed(function() { - return this.firstName+' '+this.lastName; - }).property('firstName', 'lastName').cacheable()); + /** + 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 defineProperty - @for Ember - @param {Object} obj the object to define this property on. This may be a prototype. - @param {String} keyName the name of the property - @param {Ember.Descriptor} [desc] an instance of Ember.Descriptor (typically a - computed property) or an ES5 descriptor. - You must provide this or `data` but not both. - @param {anything} [data] something other than a descriptor, that will - become the explicit value of this property. -*/ -Ember.defineProperty = function(obj, keyName, desc, data, meta) { - var descs, existingDesc, watching, value; + @method set + @param {anything} key + @param {anything} value + */ + set: function(key, value) { + var keys = this.keys, + values = this.values, + guid = guidFor(key); - if (!meta) meta = metaFor(obj); - descs = meta.descs; - existingDesc = meta.descs[keyName]; - watching = meta.watching[keyName] > 0; + keys.add(key); + values[guid] = value; + }, - if (existingDesc instanceof Ember.Descriptor) { - existingDesc.teardown(obj, keyName); - } + /** + Removes a value from the map for an associated key. - if (desc instanceof Ember.Descriptor) { - value = desc; + @method remove + @param {anything} 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), + value; - descs[keyName] = desc; - if (MANDATORY_SETTER && watching) { - objectDefineProperty(obj, keyName, { - configurable: true, - enumerable: true, - writable: true, - value: undefined // make enumerable - }); + if (values.hasOwnProperty(guid)) { + keys.remove(key); + value = values[guid]; + delete values[guid]; + return true; } else { - obj[keyName] = undefined; // make enumerable + return false; } - desc.setup(obj, keyName); - } else { - descs[keyName] = undefined; // shadow descriptor in proto - if (desc == null) { - value = data; - - if (MANDATORY_SETTER && watching) { - meta.values[keyName] = data; - objectDefineProperty(obj, keyName, { - configurable: true, - enumerable: true, - set: function() { - Ember.assert('Must use Ember.set() to access this property', false); - }, - get: function() { - var meta = this[META_KEY]; - return meta && meta.values[keyName]; - } - }); - } else { - obj[keyName] = data; - } - } else { - value = desc; + }, - // compatibility with ES5 - objectDefineProperty(obj, keyName, desc); - } - } + /** + Check whether a key is present. - // if key is being watched, override chains that - // were initialized with the prototype - if (watching) { Ember.overrideChains(obj, keyName, meta); } + @method has + @param {anything} key + @return {Boolean} true if the item was present, false otherwise + */ + has: function(key) { + var values = this.values, + guid = guidFor(key); - // The `value` passed to the `didDefineProperty` hook is - // either the descriptor or data, whichever was passed. - if (obj.didDefineProperty) { obj.didDefineProperty(obj, keyName, value); } + return values.hasOwnProperty(guid); + }, - return this; -}; + /** + 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 {anything} 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()); + } +}; -(function() { /** -@module ember-metal + @class MapWithDefault + @namespace Ember + @extends Ember.Map + @private + @constructor + @param [options] + @param {anything} [options.defaultValue] */ - -var AFTER_OBSERVERS = ':change'; -var BEFORE_OBSERVERS = ':before'; -var guidFor = Ember.guidFor; - -var deferred = 0; -var array_Slice = [].slice; - -var ObserverSet = function () { - this.targetSet = {}; +var MapWithDefault = Ember.MapWithDefault = function(options) { + Map.call(this); + this.defaultValue = options.defaultValue; }; -ObserverSet.prototype.add = function (target, path) { - var targetSet = this.targetSet, - targetGuid = Ember.guidFor(target), - pathSet = targetSet[targetGuid]; - if (!pathSet) { - targetSet[targetGuid] = pathSet = {}; - } - if (pathSet[path]) { - return false; + +/** + @method create + @static + @param [options] + @param {anything} [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 pathSet[path] = true; + return new Map(); } }; -ObserverSet.prototype.clear = function () { - this.targetSet = {}; -}; -var DeferredEventQueue = function() { - this.targetSet = {}; - this.queue = []; -}; +MapWithDefault.prototype = Ember.create(Map.prototype); -DeferredEventQueue.prototype.push = function(target, eventName, keyName) { - var targetSet = this.targetSet, - queue = this.queue, - targetGuid = Ember.guidFor(target), - eventNameSet = targetSet[targetGuid], - index; +/** + Retrieve the value associated with a given key. - if (!eventNameSet) { - targetSet[targetGuid] = eventNameSet = {}; - } - index = eventNameSet[eventName]; - if (index === undefined) { - eventNameSet[eventName] = queue.push(Ember.deferEvent(target, eventName, [target, keyName])) - 1; + @method get + @param {anything} key + @return {anything} 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 { - queue[index] = Ember.deferEvent(target, eventName, [target, keyName]); + var defaultValue = this.defaultValue(key); + this.set(key, defaultValue); + return defaultValue; } }; -DeferredEventQueue.prototype.flush = function() { - var queue = this.queue; - this.queue = []; - this.targetSet = {}; - for (var i=0, len=queue.length; i < len; ++i) { - queue[i](); - } +/** + @method copy + @return {Ember.MapWithDefault} +*/ +MapWithDefault.prototype.copy = function() { + return copyMap(this, new MapWithDefault({ + defaultValue: this.defaultValue + })); }; -var queue = new DeferredEventQueue(), beforeObserverSet = new ObserverSet(); - -function notifyObservers(obj, eventName, keyName, forceNotification) { - if (deferred && !forceNotification) { - queue.push(obj, eventName, keyName); - } else { - Ember.sendEvent(obj, eventName, [obj, keyName]); - } -} +})(); -function flushObserverQueue() { - beforeObserverSet.clear(); - queue.flush(); -} +(function() { /** - @method beginPropertyChanges - @chainable +@module ember-metal */ -Ember.beginPropertyChanges = function() { - deferred++; - return this; -}; -/** - @method endPropertyChanges -*/ -Ember.endPropertyChanges = function() { - deferred--; - if (deferred<=0) flushObserverQueue(); -}; +var META_KEY = Ember.META_KEY, get, set; -/** - Make a series of property changes together in an - exception-safe way. +var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER; - Ember.changeProperties(function() { - obj1.set('foo', mayBlowUpWhenSet); - obj2.set('bar', baz); - }); +var IS_GLOBAL = /^([A-Z$]|([0-9][A-Z$]))/; +var IS_GLOBAL_PATH = /^([A-Z$]|([0-9][A-Z$])).*[\.\*]/; +var HAS_THIS = /^this[\.\*]/; +var FIRST_KEY = /^([^\.\*]+)/; - @method changeProperties - @param {Function} callback - @param [binding] -*/ -Ember.changeProperties = function(cb, binding){ - Ember.beginPropertyChanges(); - try { - cb.call(binding); - } finally { - Ember.endPropertyChanges(); - } -}; +// .......................................................... +// GET AND SET +// +// If we are on a platform that supports accessors we can get use those. +// Otherwise simulate accessors by looking up the property directly on the +// object. /** - Set a list of properties on an object. These properties are set inside - a single `beginPropertyChanges` and `endPropertyChanges` batch, so - observers will be buffered. - - @method setProperties - @param target - @param {Hash} properties - @return target -*/ -Ember.setProperties = function(self, hash) { - Ember.changeProperties(function(){ - for(var prop in hash) { - if (hash.hasOwnProperty(prop)) Ember.set(self, prop, hash[prop]); - } - }); - return self; -}; + Gets the value of a property on an object. If the property is computed, + the function will be invoked. If the property is not defined but the + object implements the `unknownProperty` method then that will be invoked. + If you plan to run on IE8 and older browsers then you should use this + method anytime you want to retrieve a property on an object that you don't + know for sure is private. (Properties beginning with an underscore '_' + are considered private.) -function changeEvent(keyName) { - return keyName+AFTER_OBSERVERS; -} + On all newer browsers, you only need to use this method to retrieve + properties if the property might not be defined on the object and you want + to respect the `unknownProperty` handler. Otherwise you can ignore this + method. -function beforeEvent(keyName) { - return keyName+BEFORE_OBSERVERS; -} + Note that if the object itself is `undefined`, this method will throw + an error. -/** - @method addObserver - @param obj - @param {String} path - @param {Object|Function} targetOrMethod - @param {Function|String} [method] + @method get + @for Ember + @param {Object} obj The object to retrieve from. + @param {String} keyName The property key to retrieve + @return {Object} the property value or `null`. */ -Ember.addObserver = function(obj, path, target, method) { - Ember.addListener(obj, changeEvent(path), target, method); - Ember.watch(obj, path); - return this; -}; - -Ember.observersFor = function(obj, path) { - return Ember.listenersFor(obj, changeEvent(path)); -}; +get = function get(obj, keyName) { + // Helpers that operate with 'this' within an #each + if (keyName === '') { + return obj; + } -/** - @method removeObserver - @param obj - @param {String} path - @param {Object|Function} targetOrMethod - @param {Function|String} [method] -*/ -Ember.removeObserver = function(obj, path, target, method) { - Ember.unwatch(obj, path); - Ember.removeListener(obj, changeEvent(path), target, method); - return this; -}; + if (!keyName && 'string'===typeof obj) { + keyName = obj; + obj = null; + } -/** - @method addBeforeObserver - @param obj - @param {String} path - @param {Object|Function} targetOrMethod - @param {Function|String} [method] -*/ -Ember.addBeforeObserver = function(obj, path, target, method) { - Ember.addListener(obj, beforeEvent(path), target, method); - Ember.watch(obj, path); - return this; -}; + if (!obj || keyName.indexOf('.') !== -1) { + Ember.assert("Cannot call get with '"+ keyName +"' on an undefined object.", obj !== undefined); + return getPath(obj, keyName); + } -// Suspend observer during callback. -// -// This should only be used by the target of the observer -// while it is setting the observed path. -Ember._suspendBeforeObserver = function(obj, path, target, method, callback) { - return Ember._suspendListener(obj, beforeEvent(path), target, method, callback); -}; + Ember.assert("You need to provide an object and key to `get`.", !!obj && keyName); -Ember._suspendObserver = function(obj, path, target, method, callback) { - return Ember._suspendListener(obj, changeEvent(path), target, method, callback); -}; + var meta = obj[META_KEY], desc = meta && meta.descs[keyName], ret; + if (desc) { + return desc.get(obj, keyName); + } else { + if (MANDATORY_SETTER && meta && meta.watching[keyName] > 0) { + ret = meta.values[keyName]; + } else { + ret = obj[keyName]; + } -var map = Ember.ArrayPolyfills.map; + if (ret === undefined && + 'object' === typeof obj && !(keyName in obj) && 'function' === typeof obj.unknownProperty) { + return obj.unknownProperty(keyName); + } -Ember._suspendBeforeObservers = function(obj, paths, target, method, callback) { - var events = map.call(paths, beforeEvent); - return Ember._suspendListeners(obj, events, target, method, callback); + return ret; + } }; -Ember._suspendObservers = function(obj, paths, target, method, callback) { - var events = map.call(paths, changeEvent); - return Ember._suspendListeners(obj, events, target, method, callback); -}; +/** + Sets the value of a property on an object, respecting computed properties + and notifying observers and other listeners of the change. If the + property is not defined but the object implements the `unknownProperty` + method then that will be invoked as well. -Ember.beforeObserversFor = function(obj, path) { - return Ember.listenersFor(obj, beforeEvent(path)); -}; + If you plan to run on IE8 and older browsers then you should use this + method anytime you want to set a property on an object that you don't + know for sure is private. (Properties beginning with an underscore '_' + are considered private.) -/** - @method removeBeforeObserver - @param obj - @param {String} path - @param {Object|Function} targetOrMethod - @param {Function|String} [method] -*/ -Ember.removeBeforeObserver = function(obj, path, target, method) { - Ember.unwatch(obj, path); - Ember.removeListener(obj, beforeEvent(path), target, method); - return this; -}; + On all newer browsers, you only need to use this method to set + properties if the property might not be defined on the object and you want + to respect the `unknownProperty` handler. Otherwise you can ignore this + method. -Ember.notifyObservers = function(obj, keyName) { - if (obj.isDestroying) { return; } + @method set + @for Ember + @param {Object} obj The object to modify. + @param {String} keyName The property key to set + @param {Object} value The value to set + @return {Object} the passed value. +*/ +set = function set(obj, keyName, value, tolerant) { + if (typeof obj === 'string') { + Ember.assert("Path '" + obj + "' must be global if no obj is given.", IS_GLOBAL.test(obj)); + value = keyName; + keyName = obj; + obj = null; + } - notifyObservers(obj, changeEvent(keyName), keyName); -}; + if (!obj || keyName.indexOf('.') !== -1) { + return setPath(obj, keyName, value, tolerant); + } -Ember.notifyBeforeObservers = function(obj, keyName) { - if (obj.isDestroying) { return; } + Ember.assert("You need to provide an object and key to `set`.", !!obj && keyName !== undefined); + Ember.assert('calling set on destroyed object', !obj.isDestroyed); - var guid, set, forceNotification = false; + var meta = obj[META_KEY], desc = meta && meta.descs[keyName], + isUnknown, currentValue; + if (desc) { + desc.set(obj, keyName, value); + } else { + isUnknown = 'object' === typeof obj && !(keyName in obj); - if (deferred) { - if (beforeObserverSet.add(obj, keyName)) { - forceNotification = true; + // setUnknownProperty is called if `obj` is an object, + // the property does not already exist, and the + // `setUnknownProperty` method exists on the object + if (isUnknown && 'function' === typeof obj.setUnknownProperty) { + obj.setUnknownProperty(keyName, value); + } else if (meta && meta.watching[keyName] > 0) { + if (MANDATORY_SETTER) { + currentValue = meta.values[keyName]; + } else { + currentValue = obj[keyName]; + } + // only trigger a change if the value has changed + if (value !== currentValue) { + Ember.propertyWillChange(obj, keyName); + if (MANDATORY_SETTER) { + if (currentValue === undefined && !(keyName in obj)) { + Ember.defineProperty(obj, keyName, null, value); // setup mandatory setter + } else { + meta.values[keyName] = value; + } + } else { + obj[keyName] = value; + } + Ember.propertyDidChange(obj, keyName); + } } else { - return; + obj[keyName] = value; } } - - notifyObservers(obj, beforeEvent(keyName), keyName, forceNotification); + return value; }; +// Currently used only by Ember Data tests +if (Ember.config.overrideAccessors) { + Ember.get = get; + Ember.set = set; + Ember.config.overrideAccessors(); + get = Ember.get; + set = Ember.set; +} -})(); - +function firstKey(path) { + return path.match(FIRST_KEY)[0]; +} +// assumes path is already normalized +function normalizeTuple(target, path) { + var hasThis = HAS_THIS.test(path), + isGlobal = !hasThis && IS_GLOBAL_PATH.test(path), + key; -(function() { -/** -@module ember-metal -*/ + if (!target || isGlobal) target = Ember.lookup; + if (hasThis) path = path.slice(5); -var guidFor = Ember.guidFor, // utils.js - metaFor = Ember.meta, // utils.js - get = Ember.get, // accessors.js - set = Ember.set, // accessors.js - normalizeTuple = Ember.normalizeTuple, // accessors.js - GUID_KEY = Ember.GUID_KEY, // utils.js - META_KEY = Ember.META_KEY, // utils.js - // circular reference observer depends on Ember.watch - // we should move change events to this file or its own property_events.js - notifyObservers = Ember.notifyObservers, // observer.js - forEach = Ember.ArrayPolyfills.forEach, // array.js - FIRST_KEY = /^([^\.\*]+)/, - IS_PATH = /[\.\*]/; + if (target === Ember.lookup) { + key = firstKey(path); + target = get(target, key); + path = path.slice(key.length+1); + } -var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER, -o_defineProperty = Ember.platform.defineProperty; + // must return some kind of path to be valid else other things will break. + if (!path || path.length===0) throw new Error('Invalid Path'); -function firstKey(path) { - return path.match(FIRST_KEY)[0]; + return [ target, path ]; } -// returns true if the passed path is just a keyName -function isKeyName(path) { - return path==='*' || !IS_PATH.test(path); -} +function getPath(root, path) { + var hasThis, parts, tuple, idx, len; -// .......................................................... -// DEPENDENT KEYS -// + // If there is no root and path is a key name, return that + // property from the global object. + // E.g. get('Ember') -> Ember + if (root === null && path.indexOf('.') === -1) { return get(Ember.lookup, path); } -var DEP_SKIP = { __emberproto__: true }; // skip some keys and toString + // detect complicated paths and normalize them + hasThis = HAS_THIS.test(path); -function iterDeps(method, obj, depKey, seen, meta) { - - var guid = guidFor(obj); - if (!seen[guid]) seen[guid] = {}; - if (seen[guid][depKey]) return; - seen[guid][depKey] = true; + if (!root || hasThis) { + tuple = normalizeTuple(root, path); + root = tuple[0]; + path = tuple[1]; + tuple.length = 0; + } - var deps = meta.deps; - deps = deps && deps[depKey]; - if (deps) { - for(var key in deps) { - if (DEP_SKIP[key]) continue; - var desc = meta.descs[key]; - if (desc && desc._suspended === obj) continue; - method(obj, key); - } + parts = path.split("."); + len = parts.length; + for (idx=0; root && idx 0) { paths[path]--; } + @class Descriptor + @namespace Ember + @private + @constructor +*/ +var Descriptor = Ember.Descriptor = function() {}; - obj = this.value(); - tuple = normalizeTuple(obj, path); - if (tuple[0] === obj) { - path = tuple[1]; - key = firstKey(path); - path = path.slice(key.length+1); - } else { - src = tuple[0]; - key = path.slice(0, 0-(tuple[1].length+1)); - path = tuple[1]; - } +// .......................................................... +// DEFINING PROPERTIES API +// - tuple.length = 0; - this.unchain(key, path); -}; +/** + @private -ChainNodePrototype.count = 0; + NOTE: This is a low-level method used by other parts of the API. You almost + never want to call this method directly. Instead you should use + `Ember.mixin()` to define new properties. -ChainNodePrototype.chain = function(key, path, src, separator) { - var chains = this._chains, node; - if (!chains) { chains = this._chains = {}; } - - node = chains[key]; - if (!node) { node = chains[key] = new ChainNode(this, key, src, separator); } - node.count++; // count chains... - - // chain rest of path if there is one - if (path && path.length>0) { - key = firstKey(path); - path = path.slice(key.length+1); - node.chain(key, path); // NOTE: no src means it will observe changes... - } -}; + Defines a property on an object. This method works much like the ES5 + `Object.defineProperty()` method except that it can also accept computed + properties and other special descriptors. -ChainNodePrototype.unchain = function(key, path) { - var chains = this._chains, node = chains[key]; + Normally this method takes only three parameters. However if you pass an + instance of `Ember.Descriptor` as the third param then you can pass an + optional value as the fourth parameter. This is often more efficient than + creating new descriptor hashes for each property. - // unchain rest of path first... - if (path && path.length>1) { - key = firstKey(path); - path = path.slice(key.length+1); - node.unchain(key, path); - } + ## Examples - // delete node if needed. - node.count--; - if (node.count<=0) { - delete chains[node._key]; - node.destroy(); - } + ```javascript + // ES5 compatible mode + Ember.defineProperty(contact, 'firstName', { + writable: true, + configurable: false, + enumerable: true, + value: 'Charles' + }); -}; + // define a simple property + Ember.defineProperty(contact, 'lastName', undefined, 'Jolley'); -ChainNodePrototype.willChange = function() { - var chains = this._chains; - if (chains) { - for(var key in chains) { - if (!chains.hasOwnProperty(key)) { continue; } - chains[key].willChange(); - } - } + // define a computed property + Ember.defineProperty(contact, 'fullName', Ember.computed(function() { + return this.firstName+' '+this.lastName; + }).property('firstName', 'lastName')); + ``` - if (this._parent) { this._parent.chainWillChange(this, this._key, 1); } -}; + @method defineProperty + @for Ember + @param {Object} obj the object to define this property on. This may be a prototype. + @param {String} keyName the name of the property + @param {Ember.Descriptor} [desc] an instance of `Ember.Descriptor` (typically a + computed property) or an ES5 descriptor. + You must provide this or `data` but not both. + @param {anything} [data] something other than a descriptor, that will + become the explicit value of this property. +*/ +Ember.defineProperty = function(obj, keyName, desc, data, meta) { + var descs, existingDesc, watching, value; -ChainNodePrototype.chainWillChange = function(chain, path, depth) { - if (this._key) { path = this._key + this._separator + path; } + if (!meta) meta = metaFor(obj); + descs = meta.descs; + existingDesc = meta.descs[keyName]; + watching = meta.watching[keyName] > 0; - if (this._parent) { - this._parent.chainWillChange(this, path, depth+1); - } else { - if (depth > 1) { Ember.propertyWillChange(this.value(), path); } - path = 'this.' + path; - if (this._paths[path] > 0) { Ember.propertyWillChange(this.value(), path); } + if (existingDesc instanceof Ember.Descriptor) { + existingDesc.teardown(obj, keyName); } -}; -ChainNodePrototype.chainDidChange = function(chain, path, depth) { - if (this._key) { path = this._key + this._separator + path; } - if (this._parent) { - this._parent.chainDidChange(this, path, depth+1); - } else { - if (depth > 1) { Ember.propertyDidChange(this.value(), path); } - path = 'this.' + path; - if (this._paths[path] > 0) { Ember.propertyDidChange(this.value(), path); } - } -}; + if (desc instanceof Ember.Descriptor) { + value = desc; -ChainNodePrototype.didChange = function(suppressEvent) { - // invalidate my own value first. - if (this._watching) { - var obj = this._parent.value(); - if (obj !== this._object) { - removeChainWatcher(this._object, this._key, this); - this._object = obj; - addChainWatcher(obj, this._key, this); + descs[keyName] = desc; + if (MANDATORY_SETTER && watching) { + objectDefineProperty(obj, keyName, { + configurable: true, + enumerable: true, + writable: true, + value: undefined // make enumerable + }); + } else { + obj[keyName] = undefined; // make enumerable } - this._value = undefined; + desc.setup(obj, keyName); + } else { + descs[keyName] = undefined; // shadow descriptor in proto + if (desc == null) { + value = data; - // Special-case: the EachProxy relies on immediate evaluation to - // establish its observers. - if (this._parent && this._parent._key === '@each') - this.value(); - } + if (MANDATORY_SETTER && watching) { + meta.values[keyName] = data; + objectDefineProperty(obj, keyName, { + configurable: true, + enumerable: true, + set: function() { + Ember.assert('Must use Ember.set() to access this property', false); + }, + get: function() { + var meta = this[META_KEY]; + return meta && meta.values[keyName]; + } + }); + } else { + obj[keyName] = data; + } + } else { + value = desc; - // then notify chains... - var chains = this._chains; - if (chains) { - for(var key in chains) { - if (!chains.hasOwnProperty(key)) { continue; } - chains[key].didChange(suppressEvent); + // compatibility with ES5 + objectDefineProperty(obj, keyName, desc); } } - if (suppressEvent) { return; } - - // and finally tell parent about my path changing... - if (this._parent) { this._parent.chainDidChange(this, this._key, 1); } -}; - -// get the chains for the current object. If the current object has -// chains inherited from the proto they will be cloned and reconfigured for -// the current object. -function chainsFor(obj) { - var m = metaFor(obj), ret = m.chains; - if (!ret) { - ret = m.chains = new ChainNode(null, null, obj); - } else if (ret.value() !== obj) { - ret = m.chains = ret.copy(obj); - } - return ret; -} - -function notifyChains(obj, m, keyName, methodName, arg) { - var nodes = m.chainWatchers; - - if (!nodes || nodes.__emberproto__ !== obj) { return; } // nothing to do - - nodes = nodes[keyName]; - if (!nodes) { return; } + // if key is being watched, override chains that + // were initialized with the prototype + if (watching) { Ember.overrideChains(obj, keyName, meta); } - for(var key in nodes) { - if (!nodes.hasOwnProperty(key)) { continue; } - nodes[key][methodName](arg); - } -} + // The `value` passed to the `didDefineProperty` hook is + // either the descriptor or data, whichever was passed. + if (obj.didDefineProperty) { obj.didDefineProperty(obj, keyName, value); } -Ember.overrideChains = function(obj, keyName, m) { - notifyChains(obj, m, keyName, 'didChange', true); + return this; }; -function chainsWillChange(obj, keyName, m) { - notifyChains(obj, m, keyName, 'willChange'); -} -function chainsDidChange(obj, keyName, m) { - notifyChains(obj, m, keyName, 'didChange'); -} +})(); + -// .......................................................... -// WATCH -// +(function() { +// Ember.tryFinally /** - @private +@module ember-metal +*/ - Starts watching a property on an object. Whenever the property changes, - invokes Ember.propertyWillChange and Ember.propertyDidChange. This is the - primitive used by observers and dependent keys; usually you will never call - this method directly but instead use higher level methods like - Ember.addObserver(). +var AFTER_OBSERVERS = ':change'; +var BEFORE_OBSERVERS = ':before'; - @method watch - @for Ember - @param obj - @param {String} keyName -*/ -Ember.watch = function(obj, keyName) { - // can't watch length on Array - it is special... - if (keyName === 'length' && Ember.typeOf(obj) === 'array') { return this; } +var guidFor = Ember.guidFor; - var m = metaFor(obj), watching = m.watching, desc; +var deferred = 0; - // activate watching first time - if (!watching[keyName]) { - watching[keyName] = 1; - if (isKeyName(keyName)) { - desc = m.descs[keyName]; - if (desc && desc.willWatch) { desc.willWatch(obj, keyName); } +/* + this.observerSet = { + [senderGuid]: { // variable name: `keySet` + [keyName]: listIndex + } + }, + this.observers = [ + { + sender: obj, + keyName: keyName, + eventName: eventName, + listeners: [ + [target, method, onceFlag, suspendedFlag] + ] + }, + ... + ] +*/ +function ObserverSet() { + this.clear(); +} - if ('function' === typeof obj.willWatchProperty) { - obj.willWatchProperty(keyName); - } +ObserverSet.prototype.add = function(sender, keyName, eventName) { + var observerSet = this.observerSet, + observers = this.observers, + senderGuid = Ember.guidFor(sender), + keySet = observerSet[senderGuid], + index; - if (MANDATORY_SETTER && keyName in obj) { - m.values[keyName] = obj[keyName]; - o_defineProperty(obj, keyName, { - configurable: true, - enumerable: true, - set: function() { - Ember.assert('Must use Ember.set() to access this property', false); - }, - get: function() { - var meta = this[META_KEY]; - return meta && meta.values[keyName]; - } - }); - } - } else { - chainsFor(obj).add(keyName); - } + if (!keySet) { + observerSet[senderGuid] = keySet = {}; + } + index = keySet[keyName]; + if (index === undefined) { + index = observers.push({ + sender: sender, + keyName: keyName, + eventName: eventName, + listeners: [] + }) - 1; + keySet[keyName] = index; + } + return observers[index].listeners; +}; - } else { - watching[keyName] = (watching[keyName] || 0) + 1; +ObserverSet.prototype.flush = function() { + var observers = this.observers, i, len, observer, sender; + this.clear(); + for (i=0, len=observers.length; i < len; ++i) { + observer = observers[i]; + sender = observer.sender; + if (sender.isDestroying || sender.isDestroyed) { continue; } + Ember.sendEvent(sender, observer.eventName, [sender, observer.keyName], observer.listeners); } - return this; }; -Ember.isWatching = function isWatching(obj, key) { - var meta = obj[META_KEY]; - return (meta && meta.watching[key]) > 0; +ObserverSet.prototype.clear = function() { + this.observerSet = {}; + this.observers = []; }; -Ember.watch.flushPending = flushPendingChains; +var beforeObserverSet = new ObserverSet(), observerSet = new ObserverSet(); -Ember.unwatch = function(obj, keyName) { - // can't watch length on Array - it is special... - if (keyName === 'length' && Ember.typeOf(obj) === 'array') { return this; } +/** + @method beginPropertyChanges + @chainable +*/ +Ember.beginPropertyChanges = function() { + deferred++; +}; - var m = metaFor(obj), watching = m.watching, desc; +/** + @method endPropertyChanges +*/ +Ember.endPropertyChanges = function() { + deferred--; + if (deferred<=0) { + beforeObserverSet.clear(); + observerSet.flush(); + } +}; - if (watching[keyName] === 1) { - watching[keyName] = 0; - - if (isKeyName(keyName)) { - desc = m.descs[keyName]; - if (desc && desc.didUnwatch) { desc.didUnwatch(obj, keyName); } +/** + Make a series of property changes together in an + exception-safe way. - if ('function' === typeof obj.didUnwatchProperty) { - obj.didUnwatchProperty(keyName); - } + ```javascript + Ember.changeProperties(function() { + obj1.set('foo', mayBlowUpWhenSet); + obj2.set('bar', baz); + }); + ``` - if (MANDATORY_SETTER && keyName in obj) { - o_defineProperty(obj, keyName, { - configurable: true, - enumerable: true, - writable: true, - value: m.values[keyName] - }); - delete m.values[keyName]; - } - } else { - chainsFor(obj).remove(keyName); - } + @method changeProperties + @param {Function} callback + @param [binding] +*/ +Ember.changeProperties = function(cb, binding){ + Ember.beginPropertyChanges(); + Ember.tryFinally(cb, Ember.endPropertyChanges, binding); +}; - } else if (watching[keyName]>1) { - watching[keyName]--; - } +/** + Set a list of properties on an object. These properties are set inside + a single `beginPropertyChanges` and `endPropertyChanges` batch, so + observers will be buffered. - return this; + @method setProperties + @param target + @param {Hash} properties + @return target +*/ +Ember.setProperties = function(self, hash) { + Ember.changeProperties(function(){ + for(var prop in hash) { + if (hash.hasOwnProperty(prop)) Ember.set(self, prop, hash[prop]); + } + }); + return self; }; -/** - @private - Call on an object when you first beget it from another object. This will - setup any chained watchers on the object instance as needed. This method is - safe to call multiple times. +function changeEvent(keyName) { + return keyName+AFTER_OBSERVERS; +} - @method rewatch - @for Ember +function beforeEvent(keyName) { + return keyName+BEFORE_OBSERVERS; +} + +/** + @method addObserver @param obj + @param {String} path + @param {Object|Function} targetOrMethod + @param {Function|String} [method] */ -Ember.rewatch = function(obj) { - var m = metaFor(obj, false), chains = m.chains; - - // make sure the object has its own guid. - if (GUID_KEY in obj && !obj.hasOwnProperty(GUID_KEY)) { - Ember.generateGuid(obj, 'ember'); - } +Ember.addObserver = function(obj, path, target, method) { + Ember.addListener(obj, changeEvent(path), target, method); + Ember.watch(obj, path); + return this; +}; - // make sure any chained watchers update. - if (chains && chains.value() !== obj) { - m.chains = chains.copy(obj); - } +Ember.observersFor = function(obj, path) { + return Ember.listenersFor(obj, changeEvent(path)); +}; +/** + @method removeObserver + @param obj + @param {String} path + @param {Object|Function} targetOrMethod + @param {Function|String} [method] +*/ +Ember.removeObserver = function(obj, path, target, method) { + Ember.unwatch(obj, path); + Ember.removeListener(obj, changeEvent(path), target, method); return this; }; -Ember.finishChains = function(obj) { - var m = metaFor(obj, false), chains = m.chains; - if (chains) { - if (chains.value() !== obj) { - m.chains = chains = chains.copy(obj); - } - chains.didChange(true); - } +/** + @method addBeforeObserver + @param obj + @param {String} path + @param {Object|Function} targetOrMethod + @param {Function|String} [method] +*/ +Ember.addBeforeObserver = function(obj, path, target, method) { + Ember.addListener(obj, beforeEvent(path), target, method); + Ember.watch(obj, path); + return this; }; -// .......................................................... -// PROPERTY CHANGES +// Suspend observer during callback. // +// This should only be used by the target of the observer +// while it is setting the observed path. +Ember._suspendBeforeObserver = function(obj, path, target, method, callback) { + return Ember._suspendListener(obj, beforeEvent(path), target, method, callback); +}; -/** - This function is called just before an object property is about to change. - It will notify any before observers and prepare caches among other things. +Ember._suspendObserver = function(obj, path, target, method, callback) { + return Ember._suspendListener(obj, changeEvent(path), target, method, callback); +}; - Normally you will not need to call this method directly but if for some - reason you can't directly watch a property you can invoke this method - manually along with `Ember.propertyDidChange()` which you should call just - after the property value changes. +var map = Ember.ArrayPolyfills.map; - @method propertyWillChange - @for Ember - @param {Object} obj The object with the property that will change - @param {String} keyName The property key (or path) that will change. - @return {void} -*/ -function propertyWillChange(obj, keyName, value) { - var m = metaFor(obj, false), - watching = m.watching[keyName] > 0 || keyName === 'length', - proto = m.proto, - desc = m.descs[keyName]; +Ember._suspendBeforeObservers = function(obj, paths, target, method, callback) { + var events = map.call(paths, beforeEvent); + return Ember._suspendListeners(obj, events, target, method, callback); +}; - if (!watching) { return; } - if (proto === obj) { return; } - if (desc && desc.willChange) { desc.willChange(obj, keyName); } - dependentKeysWillChange(obj, keyName, m); - chainsWillChange(obj, keyName, m); - Ember.notifyBeforeObservers(obj, keyName); -} +Ember._suspendObservers = function(obj, paths, target, method, callback) { + var events = map.call(paths, changeEvent); + return Ember._suspendListeners(obj, events, target, method, callback); +}; -Ember.propertyWillChange = propertyWillChange; +Ember.beforeObserversFor = function(obj, path) { + return Ember.listenersFor(obj, beforeEvent(path)); +}; /** - This function is called just after an object property has changed. - It will notify any observers and clear caches among other things. - - Normally you will not need to call this method directly but if for some - reason you can't directly watch a property you can invoke this method - manually along with `Ember.propertyWilLChange()` which you should call just - before the property value changes. - - @method propertyDidChange - @for Ember - @param {Object} obj The object with the property that will change - @param {String} keyName The property key (or path) that will change. - @return {void} + @method removeBeforeObserver + @param obj + @param {String} path + @param {Object|Function} targetOrMethod + @param {Function|String} [method] */ -function propertyDidChange(obj, keyName) { - var m = metaFor(obj, false), - watching = m.watching[keyName] > 0 || keyName === 'length', - proto = m.proto, - desc = m.descs[keyName]; - - if (proto === obj) { return; } - - // shouldn't this mean that we're watching this key? - if (desc && desc.didChange) { desc.didChange(obj, keyName); } - if (!watching && keyName !== 'length') { return; } - - dependentKeysDidChange(obj, keyName, m); - chainsDidChange(obj, keyName, m); - Ember.notifyObservers(obj, keyName); -} +Ember.removeBeforeObserver = function(obj, path, target, method) { + Ember.unwatch(obj, path); + Ember.removeListener(obj, beforeEvent(path), target, method); + return this; +}; -Ember.propertyDidChange = propertyDidChange; +Ember.notifyBeforeObservers = function(obj, keyName) { + if (obj.isDestroying) { return; } -var NODE_STACK = []; + var eventName = beforeEvent(keyName), listeners, listenersDiff; + if (deferred) { + listeners = beforeObserverSet.add(obj, keyName, eventName); + listenersDiff = Ember.listenersDiff(obj, eventName, listeners); + Ember.sendEvent(obj, eventName, [obj, keyName], listenersDiff); + } else { + Ember.sendEvent(obj, eventName, [obj, keyName]); + } +}; -/** - Tears down the meta on an object so that it can be garbage collected. - Multiple calls will have no effect. +Ember.notifyObservers = function(obj, keyName) { + if (obj.isDestroying) { return; } - @method destroy - @for Ember - @param {Object} obj the object to destroy - @return {void} -*/ -Ember.destroy = function (obj) { - var meta = obj[META_KEY], node, nodes, key, nodeObject; - if (meta) { - obj[META_KEY] = null; - // remove chainWatchers to remove circular references that would prevent GC - node = meta.chains; - if (node) { - NODE_STACK.push(node); - // process tree - while (NODE_STACK.length > 0) { - node = NODE_STACK.pop(); - // push children - nodes = node._chains; - if (nodes) { - for (key in nodes) { - if (nodes.hasOwnProperty(key)) { - NODE_STACK.push(nodes[key]); - } - } - } - // remove chainWatcher in node object - if (node._watching) { - nodeObject = node._object; - if (nodeObject) { - removeChainWatcher(nodeObject, node._key, node); - } - } - } - } + var eventName = changeEvent(keyName), listeners; + if (deferred) { + listeners = observerSet.add(obj, keyName, eventName); + Ember.listenersUnion(obj, eventName, listeners); + } else { + Ember.sendEvent(obj, eventName, [obj, keyName]); } }; @@ -2815,2916 +2490,5933 @@ Ember.destroy = function (obj) { @module ember-metal */ -Ember.warn("Computed properties will soon be cacheable by default. To enable this in your app, set `ENV.CP_DEFAULT_CACHEABLE = true`.", Ember.CP_DEFAULT_CACHEABLE); +var guidFor = Ember.guidFor, // utils.js + metaFor = Ember.meta, // utils.js + get = Ember.get, // accessors.js + set = Ember.set, // accessors.js + normalizeTuple = Ember.normalizeTuple, // accessors.js + GUID_KEY = Ember.GUID_KEY, // utils.js + META_KEY = Ember.META_KEY, // utils.js + // circular reference observer depends on Ember.watch + // we should move change events to this file or its own property_events.js + notifyObservers = Ember.notifyObservers, // observer.js + forEach = Ember.ArrayPolyfills.forEach, // array.js + FIRST_KEY = /^([^\.\*]+)/, + IS_PATH = /[\.\*]/; +var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER, +o_defineProperty = Ember.platform.defineProperty; -var get = Ember.get, - metaFor = Ember.meta, - guidFor = Ember.guidFor, - a_slice = [].slice, - o_create = Ember.create, - META_KEY = Ember.META_KEY, - watch = Ember.watch, - unwatch = Ember.unwatch; +function firstKey(path) { + return path.match(FIRST_KEY)[0]; +} + +// returns true if the passed path is just a keyName +function isKeyName(path) { + return path==='*' || !IS_PATH.test(path); +} // .......................................................... // DEPENDENT KEYS // -// data structure: -// meta.deps = { -// 'depKey': { -// 'keyName': count, -// __emberproto__: SRC_OBJ [to detect clones] -// }, -// __emberproto__: SRC_OBJ -// } +function iterDeps(method, obj, depKey, seen, meta) { -/* - This function returns a map of unique dependencies for a - given object and key. -*/ -function keysForDep(obj, depsMeta, depKey) { - var keys = depsMeta[depKey]; - if (!keys) { - // if there are no dependencies yet for a the given key - // create a new empty list of dependencies for the key - keys = depsMeta[depKey] = { __emberproto__: obj }; - } else if (keys.__emberproto__ !== obj) { - // otherwise if the dependency list is inherited from - // a superclass, clone the hash - keys = depsMeta[depKey] = o_create(keys); - keys.__emberproto__ = obj; - } - return keys; -} + var guid = guidFor(obj); + if (!seen[guid]) seen[guid] = {}; + if (seen[guid][depKey]) return; + seen[guid][depKey] = true; -/* return obj[META_KEY].deps */ -function metaForDeps(obj, meta) { var deps = meta.deps; - // If the current object has no dependencies... - if (!deps) { - // initialize the dependencies with a pointer back to - // the current object - deps = meta.deps = { __emberproto__: obj }; - } else if (deps.__emberproto__ !== obj) { - // otherwise if the dependencies are inherited from the - // object's superclass, clone the deps - deps = meta.deps = o_create(deps); - deps.__emberproto__ = obj; + deps = deps && deps[depKey]; + if (deps) { + for(var key in deps) { + var desc = meta.descs[key]; + if (desc && desc._suspended === obj) continue; + method(obj, key); + } } - return deps; } -function addDependentKeys(desc, obj, keyName, meta) { - // the descriptor has a list of dependent keys, so - // add all of its dependent keys. - var depKeys = desc._dependentKeys, depsMeta, idx, len, depKey, keys; - if (!depKeys) return; - depsMeta = metaForDeps(obj, meta); +var WILL_SEEN, DID_SEEN; - for(idx = 0, len = depKeys.length; idx < len; idx++) { - depKey = depKeys[idx]; - // Lookup keys meta for depKey - keys = keysForDep(obj, depsMeta, depKey); - // Increment the number of times depKey depends on keyName. - keys[keyName] = (keys[keyName] || 0) + 1; - // Watch the depKey - watch(obj, depKey); - } -} +// called whenever a property is about to change to clear the cache of any dependent keys (and notify those properties of changes, etc...) +function dependentKeysWillChange(obj, depKey, meta) { + if (obj.isDestroying) { return; } -function removeDependentKeys(desc, obj, keyName, meta) { - // the descriptor has a list of dependent keys, so - // add all of its dependent keys. - var depKeys = desc._dependentKeys, depsMeta, idx, len, depKey, keys; - if (!depKeys) return; + var seen = WILL_SEEN, top = !seen; + if (top) { seen = WILL_SEEN = {}; } + iterDeps(propertyWillChange, obj, depKey, seen, meta); + if (top) { WILL_SEEN = null; } +} - depsMeta = metaForDeps(obj, meta); +// called whenever a property has just changed to update dependent keys +function dependentKeysDidChange(obj, depKey, meta) { + if (obj.isDestroying) { return; } - for(idx = 0, len = depKeys.length; idx < len; idx++) { - depKey = depKeys[idx]; - // Lookup keys meta for depKey - keys = keysForDep(obj, depsMeta, depKey); - // Increment the number of times depKey depends on keyName. - keys[keyName] = (keys[keyName] || 0) - 1; - // Watch the depKey - unwatch(obj, depKey); - } + var seen = DID_SEEN, top = !seen; + if (top) { seen = DID_SEEN = {}; } + iterDeps(propertyDidChange, obj, depKey, seen, meta); + if (top) { DID_SEEN = null; } } // .......................................................... -// COMPUTED PROPERTY +// CHAIN // -/** - @class ComputedProperty - @namespace Ember - @extends Ember.Descriptor - @constructor -*/ -function ComputedProperty(func, opts) { - this.func = func; - this._cacheable = (opts && opts.cacheable !== undefined) ? opts.cacheable : Ember.CP_DEFAULT_CACHEABLE; - this._dependentKeys = opts && opts.dependentKeys; -} - -Ember.ComputedProperty = ComputedProperty; -ComputedProperty.prototype = new Ember.Descriptor(); - -var ComputedPropertyPrototype = ComputedProperty.prototype; - -/** - Call on a computed property to set it into cacheable mode. When in this - mode the computed property will automatically cache the return value of - your function until one of the dependent keys changes. +function addChainWatcher(obj, keyName, node) { + if (!obj || ('object' !== typeof obj)) { return; } // nothing to do - MyApp.president = Ember.Object.create({ - fullName: function() { - return this.get('firstName') + ' ' + this.get('lastName'); + var m = metaFor(obj), nodes = m.chainWatchers; - // After calculating the value of this function, Ember.js will - // return that value without re-executing this function until - // one of the dependent properties change. - }.property('firstName', 'lastName').cacheable() - }); + if (!m.hasOwnProperty('chainWatchers')) { + nodes = m.chainWatchers = {}; + } - Properties are cacheable by default. + if (!nodes[keyName]) { nodes[keyName] = []; } + nodes[keyName].push(node); + Ember.watch(obj, keyName); +} - @method cacheable - @param {Boolean} aFlag optional set to false to disable caching - @chainable -*/ -ComputedPropertyPrototype.cacheable = function(aFlag) { - this._cacheable = aFlag !== false; - return this; -}; +function removeChainWatcher(obj, keyName, node) { + if (!obj || 'object' !== typeof obj) { return; } // nothing to do -/** - Call on a computed property to set it into non-cached mode. When in this - mode the computed property will not automatically cache the return value. + var m = metaFor(obj, false); + if (!m.hasOwnProperty('chainWatchers')) { return; } // nothing to do - MyApp.outsideService = Ember.Object.create({ - value: function() { - return OutsideService.getValue(); - }.property().volatile() - }); + var nodes = m.chainWatchers; - @method volatile - @chainable -*/ -ComputedPropertyPrototype.volatile = function() { - return this.cacheable(false); -}; + if (nodes[keyName]) { + nodes = nodes[keyName]; + for (var i = 0, l = nodes.length; i < l; i++) { + if (nodes[i] === node) { nodes.splice(i, 1); } + } + } + Ember.unwatch(obj, keyName); +} -/** - Sets the dependent keys on this computed property. Pass any number of - arguments containing key paths that this computed property depends on. +var pendingQueue = []; - MyApp.president = Ember.Object.create({ - fullName: Ember.computed(function() { - return this.get('firstName') + ' ' + this.get('lastName'); +// attempts to add the pendingQueue chains again. If some of them end up +// back in the queue and reschedule is true, schedules a timeout to try +// again. +function flushPendingChains() { + if (pendingQueue.length === 0) { return; } // nothing to do - // Tell Ember.js that this computed property depends on firstName - // and lastName - }).property('firstName', 'lastName') - }); + var queue = pendingQueue; + pendingQueue = []; - @method property - @param {String} path* zero or more property paths - @chainable -*/ -ComputedPropertyPrototype.property = function() { - var args = []; - for (var i = 0, l = arguments.length; i < l; i++) { - args.push(arguments[i]); - } - this._dependentKeys = args; - return this; -}; + forEach.call(queue, function(q) { q[0].add(q[1]); }); -/** - In some cases, you may want to annotate computed properties with additional - metadata about how they function or what values they operate on. For example, - computed property functions may close over variables that are then no longer - available for introspection. + Ember.warn('Watching an undefined global, Ember expects watched globals to be setup by the time the run loop is flushed, check for typos', pendingQueue.length === 0); +} - You can pass a hash of these values to a computed property like this: +function isProto(pvalue) { + return metaFor(pvalue, false).proto === pvalue; +} - person: function() { - var personId = this.get('personId'); - return App.Person.create({ id: personId }); - }.property().meta({ type: App.Person }) +// A ChainNode watches a single key on an object. If you provide a starting +// value for the key then the node won't actually watch it. For a root node +// pass null for parent and key and object for value. +var ChainNode = function(parent, key, value) { + var obj; + this._parent = parent; + this._key = key; - The hash that you pass to the `meta()` function will be saved on the - computed property descriptor under the `_meta` key. Ember runtime - exposes a public API for retrieving these values from classes, - via the `metaForProperty()` function. + // _watching is true when calling get(this._parent, this._key) will + // return the value of this node. + // + // It is false for the root of a chain (because we have no parent) + // and for global paths (because the parent node is the object with + // the observer on it) + this._watching = value===undefined; - @method meta - @param {Hash} meta - @chainable -*/ + this._value = value; + this._paths = {}; + if (this._watching) { + this._object = parent.value(); + if (this._object) { addChainWatcher(this._object, this._key, this); } + } -ComputedPropertyPrototype.meta = function(meta) { - if (arguments.length === 0) { - return this._meta || {}; - } else { - this._meta = meta; - return this; + // Special-case: the EachProxy relies on immediate evaluation to + // establish its observers. + // + // TODO: Replace this with an efficient callback that the EachProxy + // can implement. + if (this._parent && this._parent._key === '@each') { + this.value(); } }; -/* impl descriptor API */ -ComputedPropertyPrototype.willWatch = function(obj, keyName) { - // watch already creates meta for this instance - var meta = obj[META_KEY]; - Ember.assert('watch should have setup meta to be writable', meta.source === obj); - if (!(keyName in meta.cache)) { - addDependentKeys(this, obj, keyName, meta); +var ChainNodePrototype = ChainNode.prototype; + +ChainNodePrototype.value = function() { + if (this._value === undefined && this._watching) { + var obj = this._parent.value(); + this._value = (obj && !isProto(obj)) ? get(obj, this._key) : undefined; } + return this._value; }; -ComputedPropertyPrototype.didUnwatch = function(obj, keyName) { - var meta = obj[META_KEY]; - Ember.assert('unwatch should have setup meta to be writable', meta.source === obj); - if (!(keyName in meta.cache)) { - // unwatch already creates meta for this instance - removeDependentKeys(this, obj, keyName, meta); - } -}; - -/* impl descriptor API */ -ComputedPropertyPrototype.didChange = function(obj, keyName) { - // _suspended is set via a CP.set to ensure we don't clear - // the cached value set by the setter - if (this._cacheable && this._suspended !== obj) { - var meta = metaFor(obj); - if (keyName in meta.cache) { - delete meta.cache[keyName]; - if (!meta.watching[keyName]) { - removeDependentKeys(this, obj, keyName, meta); - } - } +ChainNodePrototype.destroy = function() { + if (this._watching) { + var obj = this._object; + if (obj) { removeChainWatcher(obj, this._key, this); } + this._watching = false; // so future calls do nothing } }; -/* impl descriptor API */ -ComputedPropertyPrototype.get = function(obj, keyName) { - var ret, cache, meta; - if (this._cacheable) { - meta = metaFor(obj); - cache = meta.cache; - if (keyName in cache) { return cache[keyName]; } - ret = cache[keyName] = this.func.call(obj, keyName); - if (!meta.watching[keyName]) { - addDependentKeys(this, obj, keyName, meta); - } - } else { - ret = this.func.call(obj, keyName); +// copies a top level object only +ChainNodePrototype.copy = function(obj) { + var ret = new ChainNode(null, null, obj), + paths = this._paths, path; + for (path in paths) { + if (paths[path] <= 0) { continue; } // this check will also catch non-number vals. + ret.add(path); } return ret; }; -/* impl descriptor API */ -ComputedPropertyPrototype.set = function(obj, keyName, value) { - var cacheable = this._cacheable, - meta = metaFor(obj, cacheable), - watched = meta.watching[keyName], - oldSuspended = this._suspended, - hadCachedValue = false, - ret; - this._suspended = obj; - try { - ret = this.func.call(obj, keyName, value); +// called on the root node of a chain to setup watchers on the specified +// path. +ChainNodePrototype.add = function(path) { + var obj, tuple, key, src, paths; - if (cacheable && keyName in meta.cache) { - if (meta.cache[keyName] === ret) { - return; - } - hadCachedValue = true; - } + paths = this._paths; + paths[path] = (paths[path] || 0) + 1; - if (watched) { Ember.propertyWillChange(obj, keyName); } + obj = this.value(); + tuple = normalizeTuple(obj, path); - if (cacheable && hadCachedValue) { - delete meta.cache[keyName]; - } + // the path was a local path + if (tuple[0] && tuple[0] === obj) { + path = tuple[1]; + key = firstKey(path); + path = path.slice(key.length+1); - if (cacheable) { - if (!watched && !hadCachedValue) { - addDependentKeys(this, obj, keyName, meta); - } - meta.cache[keyName] = ret; - } + // global path, but object does not exist yet. + // put into a queue and try to connect later. + } else if (!tuple[0]) { + pendingQueue.push([this, path]); + tuple.length = 0; + return; - if (watched) { Ember.propertyDidChange(obj, keyName); } - } finally { - this._suspended = oldSuspended; + // global path, and object already exists + } else { + src = tuple[0]; + key = path.slice(0, 0-(tuple[1].length+1)); + path = tuple[1]; } - return ret; -}; -/* called when property is defined */ -ComputedPropertyPrototype.setup = function(obj, keyName) { - var meta = obj[META_KEY]; - if (meta && meta.watching[keyName]) { - addDependentKeys(this, obj, keyName, metaFor(obj)); - } + tuple.length = 0; + this.chain(key, path, src); }; -/* called before property is overridden */ -ComputedPropertyPrototype.teardown = function(obj, keyName) { - var meta = metaFor(obj); +// called on the root node of a chain to teardown watcher on the specified +// path +ChainNodePrototype.remove = function(path) { + var obj, tuple, key, src, paths; - if (meta.watching[keyName] || keyName in meta.cache) { - removeDependentKeys(this, obj, keyName, meta); - } + paths = this._paths; + if (paths[path] > 0) { paths[path]--; } - if (this._cacheable) { delete meta.cache[keyName]; } + obj = this.value(); + tuple = normalizeTuple(obj, path); + if (tuple[0] === obj) { + path = tuple[1]; + key = firstKey(path); + path = path.slice(key.length+1); + } else { + src = tuple[0]; + key = path.slice(0, 0-(tuple[1].length+1)); + path = tuple[1]; + } - return null; // no value to restore + tuple.length = 0; + this.unchain(key, path); }; +ChainNodePrototype.count = 0; -/** - This helper returns a new property descriptor that wraps the passed - computed property function. You can use this helper to define properties - with mixins or via Ember.defineProperty(). - - The function you pass will be used to both get and set property values. - 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. +ChainNodePrototype.chain = function(key, path, src) { + var chains = this._chains, node; + if (!chains) { chains = this._chains = {}; } - @method computed - @for Ember - @param {Function} func The computed property function. - @return {Ember.ComputedProperty} property descriptor instance -*/ -Ember.computed = function(func) { - var args; + node = chains[key]; + if (!node) { node = chains[key] = new ChainNode(this, key, src); } + node.count++; // count chains... - if (arguments.length > 1) { - args = a_slice.call(arguments, 0, -1); - func = a_slice.call(arguments, -1)[0]; + // chain rest of path if there is one + if (path && path.length>0) { + key = firstKey(path); + path = path.slice(key.length+1); + node.chain(key, path); // NOTE: no src means it will observe changes... } +}; - var cp = new ComputedProperty(func); +ChainNodePrototype.unchain = function(key, path) { + var chains = this._chains, node = chains[key]; - if (args) { - cp.property.apply(cp, args); + // unchain rest of path first... + if (path && path.length>1) { + key = firstKey(path); + path = path.slice(key.length+1); + node.unchain(key, path); } - return cp; -}; - -/** - Returns the cached value for a property, if one exists. - This can be useful for peeking at the value of a computed - property that is generated lazily, without accidentally causing - it to be created. + // delete node if needed. + node.count--; + if (node.count<=0) { + delete chains[node._key]; + node.destroy(); + } - @method cacheFor - @for Ember - @param {Object} obj the object whose property you want to check - @param {String} key the name of the property whose cached value you want - to return -*/ -Ember.cacheFor = function cacheFor(obj, key) { - var cache = metaFor(obj, false).cache; +}; - if (cache && key in cache) { - return cache[key]; +ChainNodePrototype.willChange = function() { + var chains = this._chains; + if (chains) { + for(var key in chains) { + if (!chains.hasOwnProperty(key)) { continue; } + chains[key].willChange(); + } } -}; -/** - @method computed.not - @for Ember - @param {String} dependentKey -*/ -Ember.computed.not = function(dependentKey) { - return Ember.computed(dependentKey, function(key) { - return !get(this, dependentKey); - }).cacheable(); + if (this._parent) { this._parent.chainWillChange(this, this._key, 1); } }; -/** - @method computed.empty - @for Ember - @param {String} dependentKey -*/ -Ember.computed.empty = function(dependentKey) { - return Ember.computed(dependentKey, function(key) { - var val = get(this, dependentKey); - return val === undefined || val === null || val === '' || (Ember.isArray(val) && get(val, 'length') === 0); - }).cacheable(); +ChainNodePrototype.chainWillChange = function(chain, path, depth) { + if (this._key) { path = this._key + '.' + path; } + + if (this._parent) { + this._parent.chainWillChange(this, path, depth+1); + } else { + if (depth > 1) { Ember.propertyWillChange(this.value(), path); } + path = 'this.' + path; + if (this._paths[path] > 0) { Ember.propertyWillChange(this.value(), path); } + } }; -/** - @method computed.bool - @for Ember - @param {String} dependentKey -*/ -Ember.computed.bool = function(dependentKey) { - return Ember.computed(dependentKey, function(key) { - return !!get(this, dependentKey); - }).cacheable(); +ChainNodePrototype.chainDidChange = function(chain, path, depth) { + if (this._key) { path = this._key + '.' + path; } + if (this._parent) { + this._parent.chainDidChange(this, path, depth+1); + } else { + if (depth > 1) { Ember.propertyDidChange(this.value(), path); } + path = 'this.' + path; + if (this._paths[path] > 0) { Ember.propertyDidChange(this.value(), path); } + } }; -})(); +ChainNodePrototype.didChange = function(suppressEvent) { + // invalidate my own value first. + if (this._watching) { + var obj = this._parent.value(); + if (obj !== this._object) { + removeChainWatcher(this._object, this._key, this); + this._object = obj; + addChainWatcher(obj, this._key, this); + } + this._value = undefined; + // Special-case: the EachProxy relies on immediate evaluation to + // establish its observers. + if (this._parent && this._parent._key === '@each') + this.value(); + } + // then notify chains... + var chains = this._chains; + if (chains) { + for(var key in chains) { + if (!chains.hasOwnProperty(key)) { continue; } + chains[key].didChange(suppressEvent); + } + } -(function() { -/** -@module ember-metal -*/ + if (suppressEvent) { return; } -var o_create = Ember.create, - meta = Ember.meta, - metaPath = Ember.metaPath, - guidFor = Ember.guidFor, - a_slice = [].slice; + // and finally tell parent about my path changing... + if (this._parent) { this._parent.chainDidChange(this, this._key, 1); } +}; -/* - The event system uses a series of nested hashes to store listeners on an - object. When a listener is registered, or when an event arrives, these - hashes are consulted to determine which target and action pair to invoke. +// get the chains for the current object. If the current object has +// chains inherited from the proto they will be cloned and reconfigured for +// the current object. +function chainsFor(obj) { + var m = metaFor(obj), ret = m.chains; + if (!ret) { + ret = m.chains = new ChainNode(null, null, obj); + } else if (ret.value() !== obj) { + ret = m.chains = ret.copy(obj); + } + return ret; +} - The hashes are stored in the object's meta hash, and look like this: +Ember.overrideChains = function(obj, keyName, m) { + chainsDidChange(obj, keyName, m, true); +}; - // Object's meta hash - { - listeners: { // variable name: `listenerSet` - "foo:changed": { // variable name: `targetSet` - [targetGuid]: { // variable name: `actionSet` - [methodGuid]: { // variable name: `action` - target: [Object object], - method: [Function function] - } - } - } - } - } +function chainsWillChange(obj, keyName, m, arg) { + if (!m.hasOwnProperty('chainWatchers')) { return; } // nothing to do -*/ + var nodes = m.chainWatchers; + + nodes = nodes[keyName]; + if (!nodes) { return; } -// Gets the set of all actions, keyed on the guid of each action's -// method property. -function actionSetFor(obj, eventName, target, writable) { - return metaPath(obj, ['listeners', eventName, guidFor(target)], writable); + for(var i = 0, l = nodes.length; i < l; i++) { + nodes[i].willChange(arg); + } } -// Gets the set of all targets, keyed on the guid of each action's -// target property. -function targetSetFor(obj, eventName) { - var listenerSet = meta(obj, false).listeners; - if (!listenerSet) { return false; } +function chainsDidChange(obj, keyName, m, arg) { + if (!m.hasOwnProperty('chainWatchers')) { return; } // nothing to do - return listenerSet[eventName] || false; -} + var nodes = m.chainWatchers; -// TODO: This knowledge should really be a part of the -// meta system. -var SKIP_PROPERTIES = { __ember_source__: true }; - -function iterateSet(obj, eventName, callback, params) { - var targetSet = targetSetFor(obj, eventName); - if (!targetSet) { return false; } - // Iterate through all elements of the target set - for(var targetGuid in targetSet) { - if (SKIP_PROPERTIES[targetGuid]) { continue; } - - var actionSet = targetSet[targetGuid]; - if (actionSet) { - // Iterate through the elements of the action set - for(var methodGuid in actionSet) { - if (SKIP_PROPERTIES[methodGuid]) { continue; } - - var action = actionSet[methodGuid]; - if (action) { - if (callback(action, params, obj) === true) { - return true; - } - } - } - } - } - return false; -} + nodes = nodes[keyName]; + if (!nodes) { return; } -function invokeAction(action, params, sender) { - var method = action.method, target = action.target; - // If there is no target, the target is the object - // on which the event was fired. - if (!target) { target = sender; } - if ('string' === typeof method) { method = target[method]; } - if (params) { - method.apply(target, params); - } else { - method.apply(target); + // looping in reverse because the chainWatchers array can be modified inside didChange + for (var i = nodes.length - 1; i >= 0; i--) { + nodes[i].didChange(arg); } } +// .......................................................... +// WATCH +// + /** - Add an event listener + @private - @method addListener + Starts watching a property on an object. Whenever the property changes, + invokes `Ember.propertyWillChange` and `Ember.propertyDidChange`. This is the + primitive used by observers and dependent keys; usually you will never call + this method directly but instead use higher level methods like + `Ember.addObserver()` + + @method watch @for Ember @param obj - @param {String} eventName - @param {Object|Function} targetOrMethod A target object or a function - @param {Function|String} method A function or the name of a function to be called on `target` + @param {String} keyName */ -function addListener(obj, eventName, target, method) { - Ember.assert("You must pass at least an object and event name to Ember.addListener", !!obj && !!eventName); - - if (!method && 'function' === typeof target) { - method = target; - target = null; - } - - var actionSet = actionSetFor(obj, eventName, target, true), - methodGuid = guidFor(method); - - if (!actionSet[methodGuid]) { - actionSet[methodGuid] = { target: target, method: method }; - } +Ember.watch = function(obj, keyName) { + // can't watch length on Array - it is special... + if (keyName === 'length' && Ember.typeOf(obj) === 'array') { return this; } - if ('function' === typeof obj.didAddListener) { - obj.didAddListener(eventName, target, method); - } -} + var m = metaFor(obj), watching = m.watching, desc; -/** - Remove an event listener + // activate watching first time + if (!watching[keyName]) { + watching[keyName] = 1; + if (isKeyName(keyName)) { + desc = m.descs[keyName]; + if (desc && desc.willWatch) { desc.willWatch(obj, keyName); } - Arguments should match those passed to {{#crossLink "Ember/addListener"}}{{/crossLink}} + if ('function' === typeof obj.willWatchProperty) { + obj.willWatchProperty(keyName); + } - @method removeListener - @for Ember - @param obj - @param {String} eventName - @param {Object|Function} targetOrMethod A target object or a function - @param {Function|String} method A function or the name of a function to be called on `target` -*/ -function removeListener(obj, eventName, target, method) { - Ember.assert("You must pass at least an object and event name to Ember.removeListener", !!obj && !!eventName); + if (MANDATORY_SETTER && keyName in obj) { + m.values[keyName] = obj[keyName]; + o_defineProperty(obj, keyName, { + configurable: true, + enumerable: true, + set: function() { + Ember.assert('Must use Ember.set() to access this property', false); + }, + get: function() { + var meta = this[META_KEY]; + return meta && meta.values[keyName]; + } + }); + } + } else { + chainsFor(obj).add(keyName); + } - if (!method && 'function' === typeof target) { - method = target; - target = null; + } else { + watching[keyName] = (watching[keyName] || 0) + 1; } + return this; +}; - var actionSet = actionSetFor(obj, eventName, target, true), - methodGuid = guidFor(method); +Ember.isWatching = function isWatching(obj, key) { + var meta = obj[META_KEY]; + return (meta && meta.watching[key]) > 0; +}; - // we can't simply delete this parameter, because if we do, we might - // re-expose the property from the prototype chain. - if (actionSet && actionSet[methodGuid]) { actionSet[methodGuid] = null; } +Ember.watch.flushPending = flushPendingChains; - if ('function' === typeof obj.didRemoveListener) { - obj.didRemoveListener(eventName, target, method); - } -} +Ember.unwatch = function(obj, keyName) { + // can't watch length on Array - it is special... + if (keyName === 'length' && Ember.typeOf(obj) === 'array') { return this; } -/** - @private + var m = metaFor(obj), watching = m.watching, desc; - Suspend listener during callback. + if (watching[keyName] === 1) { + watching[keyName] = 0; - This should only be used by the target of the event listener - when it is taking an action that would cause the event, e.g. - an object might suspend its property change listener while it is - setting that property. + if (isKeyName(keyName)) { + desc = m.descs[keyName]; + if (desc && desc.didUnwatch) { desc.didUnwatch(obj, keyName); } - @method suspendListener - @for Ember - @param obj - @param {String} eventName - @param {Object|Function} targetOrMethod A target object or a function - @param {Function|String} method A function or the name of a function to be called on `target` - @param {Function} callback -*/ -function suspendListener(obj, eventName, target, method, callback) { - if (!method && 'function' === typeof target) { - method = target; - target = null; - } + if ('function' === typeof obj.didUnwatchProperty) { + obj.didUnwatchProperty(keyName); + } - var actionSet = actionSetFor(obj, eventName, target, true), - methodGuid = guidFor(method), - action = actionSet && actionSet[methodGuid]; + if (MANDATORY_SETTER && keyName in obj) { + o_defineProperty(obj, keyName, { + configurable: true, + enumerable: true, + writable: true, + value: m.values[keyName] + }); + delete m.values[keyName]; + } + } else { + chainsFor(obj).remove(keyName); + } - actionSet[methodGuid] = null; - try { - return callback.call(target); - } finally { - actionSet[methodGuid] = action; + } else if (watching[keyName]>1) { + watching[keyName]--; } -} + + return this; +}; /** @private - Suspend listener during callback. - - This should only be used by the target of the event listener - when it is taking an action that would cause the event, e.g. - an object might suspend its property change listener while it is - setting that property. + Call on an object when you first beget it from another object. This will + setup any chained watchers on the object instance as needed. This method is + safe to call multiple times. - @method suspendListener + @method rewatch @for Ember @param obj - @param {Array} eventName Array of event names - @param {Object|Function} targetOrMethod A target object or a function - @param {Function|String} method A function or the name of a function to be called on `target` - @param {Function} callback */ -function suspendListeners(obj, eventNames, target, method, callback) { - if (!method && 'function' === typeof target) { - method = target; - target = null; - } - - var oldActions = [], - actionSets = [], - eventName, actionSet, methodGuid, action, i, l; - - for (i=0, l=eventNames.length; i 0 || keyName === 'length', + proto = m.proto, + desc = m.descs[keyName]; - if (listeners) { - for(var eventName in listeners) { - if (!SKIP_PROPERTIES[eventName] && listeners[eventName]) { - ret.push(eventName); - } - } - } - return ret; + if (!watching) { return; } + if (proto === obj) { return; } + if (desc && desc.willChange) { desc.willChange(obj, keyName); } + dependentKeysWillChange(obj, keyName, m); + chainsWillChange(obj, keyName, m); + Ember.notifyBeforeObservers(obj, keyName); } +Ember.propertyWillChange = propertyWillChange; + /** - @method sendEvent - @for Ember - @param obj - @param {String} eventName - @param {Array} params - @return true -*/ -function sendEvent(obj, eventName, params) { - // first give object a chance to handle it - if (obj !== Ember && 'function' === typeof obj.sendEvent) { - obj.sendEvent(eventName, params); - } + This function is called just after an object property has changed. + It will notify any observers and clear caches among other things. - iterateSet(obj, eventName, invokeAction, params); - return true; -} + Normally you will not need to call this method directly but if for some + reason you can't directly watch a property you can invoke this method + manually along with `Ember.propertyWilLChange()` which you should call just + before the property value changes. -/** - @private - @method deferEvent + @method propertyDidChange @for Ember - @param obj - @param {String} eventName - @param {Array} params + @param {Object} obj The object with the property that will change + @param {String} keyName The property key (or path) that will change. + @return {void} */ -function deferEvent(obj, eventName, params) { - var actions = []; - iterateSet(obj, eventName, function (action) { - actions.push(action); - }); +function propertyDidChange(obj, keyName) { + var m = metaFor(obj, false), + watching = m.watching[keyName] > 0 || keyName === 'length', + proto = m.proto, + desc = m.descs[keyName]; - return function() { - if (obj.isDestroyed) { return; } + if (proto === obj) { return; } - if (obj !== Ember && 'function' === typeof obj.sendEvent) { - obj.sendEvent(eventName, params); - } + // shouldn't this mean that we're watching this key? + if (desc && desc.didChange) { desc.didChange(obj, keyName); } + if (!watching && keyName !== 'length') { return; } - for (var i=0, len=actions.length; i < len; ++i) { - invokeAction(actions[i], params, obj); - } - }; + dependentKeysDidChange(obj, keyName, m); + chainsDidChange(obj, keyName, m); + Ember.notifyObservers(obj, keyName); } -/** - @private - @method hasListeners - @for Ember - @param obj - @param {String} eventName -*/ -function hasListeners(obj, eventName) { - if (iterateSet(obj, eventName, function() { return true; })) { - return true; - } - - // no listeners! might as well clean this up so it is faster later. - var set = metaPath(obj, ['listeners'], true); - set[eventName] = null; +Ember.propertyDidChange = propertyDidChange; - return false; -} +var NODE_STACK = []; /** - @private - @method listenersFor + Tears down the meta on an object so that it can be garbage collected. + Multiple calls will have no effect. + + @method destroy @for Ember - @param obj - @param {String} eventName + @param {Object} obj the object to destroy + @return {void} */ -function listenersFor(obj, eventName) { - var ret = []; - iterateSet(obj, eventName, function (action) { - ret.push([action.target, action.method]); - }); - return ret; -} - -Ember.addListener = addListener; -Ember.removeListener = removeListener; -Ember._suspendListener = suspendListener; -Ember._suspendListeners = suspendListeners; -Ember.sendEvent = sendEvent; -Ember.hasListeners = hasListeners; -Ember.watchedEvents = watchedEvents; -Ember.listenersFor = listenersFor; -Ember.deferEvent = deferEvent; +Ember.destroy = function (obj) { + var meta = obj[META_KEY], node, nodes, key, nodeObject; + if (meta) { + obj[META_KEY] = null; + // remove chainWatchers to remove circular references that would prevent GC + node = meta.chains; + if (node) { + NODE_STACK.push(node); + // process tree + while (NODE_STACK.length > 0) { + node = NODE_STACK.pop(); + // push children + nodes = node._chains; + if (nodes) { + for (key in nodes) { + if (nodes.hasOwnProperty(key)) { + NODE_STACK.push(nodes[key]); + } + } + } + // remove chainWatcher in node object + if (node._watching) { + nodeObject = node._object; + if (nodeObject) { + removeChainWatcher(nodeObject, node._key, node); + } + } + } + } + } +}; })(); (function() { -// Ember.Logger -// Ember.watch.flushPending -// Ember.beginPropertyChanges, Ember.endPropertyChanges -// Ember.guidFor - /** @module ember-metal */ +Ember.warn("The CP_DEFAULT_CACHEABLE flag has been removed and computed properties are always cached by default. Use `volatile` if you don't want caching.", Ember.ENV.CP_DEFAULT_CACHEABLE !== false); + + +var get = Ember.get, + set = Ember.set, + metaFor = Ember.meta, + guidFor = Ember.guidFor, + a_slice = [].slice, + o_create = Ember.create, + META_KEY = Ember.META_KEY, + watch = Ember.watch, + unwatch = Ember.unwatch; + // .......................................................... -// HELPERS +// DEPENDENT KEYS // -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) { +// data structure: +// meta.deps = { +// 'depKey': { +// 'keyName': count, +// } +// } - if (method === undefined) { - method = target; - target = undefined; +/* + This function returns a map of unique dependencies for a + given object and key. +*/ +function keysForDep(obj, depsMeta, depKey) { + var keys = depsMeta[depKey]; + if (!keys) { + // if there are no dependencies yet for a the given key + // create a new empty list of dependencies for the key + keys = depsMeta[depKey] = {}; + } else if (!depsMeta.hasOwnProperty(depKey)) { + // otherwise if the dependency list is inherited from + // a superclass, clone the hash + keys = depsMeta[depKey] = o_create(keys); } + return keys; +} - if ('string' === typeof method) { method = target[method]; } - if (args && ignore > 0) { - args = args.length > ignore ? slice.call(args, ignore) : null; +/* return obj[META_KEY].deps */ +function metaForDeps(obj, meta) { + var deps = meta.deps; + // If the current object has no dependencies... + if (!deps) { + // initialize the dependencies with a pointer back to + // the current object + deps = meta.deps = {}; + } else if (!meta.hasOwnProperty('deps')) { + // otherwise if the dependencies are inherited from the + // object's superclass, clone the deps + deps = meta.deps = o_create(deps); } + return deps; +} - return Ember.handleErrors(function() { - // IE8's Function.prototype.apply doesn't accept undefined/null arguments. - return method.apply(target || this, args || []); - }, this); +function addDependentKeys(desc, obj, keyName, meta) { + // the descriptor has a list of dependent keys, so + // add all of its dependent keys. + var depKeys = desc._dependentKeys, depsMeta, idx, len, depKey, keys; + if (!depKeys) return; + + depsMeta = metaForDeps(obj, meta); + + for(idx = 0, len = depKeys.length; idx < len; idx++) { + depKey = depKeys[idx]; + // Lookup keys meta for depKey + keys = keysForDep(obj, depsMeta, depKey); + // Increment the number of times depKey depends on keyName. + keys[keyName] = (keys[keyName] || 0) + 1; + // Watch the depKey + watch(obj, depKey); + } } +function removeDependentKeys(desc, obj, keyName, meta) { + // the descriptor has a list of dependent keys, so + // add all of its dependent keys. + var depKeys = desc._dependentKeys, depsMeta, idx, len, depKey, keys; + if (!depKeys) return; + + depsMeta = metaForDeps(obj, meta); + + for(idx = 0, len = depKeys.length; idx < len; idx++) { + depKey = depKeys[idx]; + // Lookup keys meta for depKey + keys = keysForDep(obj, depsMeta, depKey); + // Increment the number of times depKey depends on keyName. + keys[keyName] = (keys[keyName] || 0) - 1; + // Watch the depKey + unwatch(obj, depKey); + } +} // .......................................................... -// RUNLOOP +// COMPUTED PROPERTY // -var timerMark; // used by timers... - /** -Ember RunLoop (Private) - -@class RunLoop -@namespace Ember -@private -@constructor + @class ComputedProperty + @namespace Ember + @extends Ember.Descriptor + @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] = []; } +function ComputedProperty(func, opts) { + this.func = func; + this._cacheable = (opts && opts.cacheable !== undefined) ? opts.cacheable : true; + this._dependentKeys = opts && opts.dependentKeys; +} - var args = arguments.length > 3 ? slice.call(arguments, 3) : null; - queue.push({ target: target, method: method, args: args }); - return this; - }, +Ember.ComputedProperty = ComputedProperty; +ComputedProperty.prototype = new Ember.Descriptor(); - /** - @method flush - @param {String} queueName - */ - flush: function(queueName) { - var queueNames, idx, len, queue, log; +var ComputedPropertyPrototype = ComputedProperty.prototype; - if (!this._queues) { return this; } // nothing to do +/** + Call on a computed property to set it into cacheable mode. When in this + mode the computed property will automatically cache the return value of + your function until one of the dependent keys changes. - function iter(item) { - invoke(item.target, item.method, item.args); - } + ```javascript + MyApp.president = Ember.Object.create({ + fullName: function() { + return this.get('firstName') + ' ' + this.get('lastName'); + + // After calculating the value of this function, Ember will + // return that value without re-executing this function until + // one of the dependent properties change. + }.property('firstName', 'lastName') + }); + ``` - Ember.watch.flushPending(); // make sure all chained watchers are setup + Properties are cacheable by default. - if (queueName) { - while (this._queues && (queue = this._queues[queueName])) { - this._queues[queueName] = null; + @method cacheable + @param {Boolean} aFlag optional set to `false` to disable caching + @chainable +*/ +ComputedPropertyPrototype.cacheable = function(aFlag) { + this._cacheable = aFlag !== false; + return this; +}; - // 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'); } +/** + Call on a computed property to set it into non-cached mode. When in this + mode the computed property will not automatically cache the return value. - Ember.beginPropertyChanges(); - try { - forEach.call(queue, iter); - } finally { - Ember.endPropertyChanges(); - } + ```javascript + MyApp.outsideService = Ember.Object.create({ + value: function() { + return OutsideService.getValue(); + }.property().volatile() + }); + ``` - if (log) { Ember.Logger.log('End: Flush Sync Queue'); } + @method volatile + @chainable +*/ +ComputedPropertyPrototype.volatile = function() { + return this.cacheable(false); +}; - } else { - forEach.call(queue, iter); - } - } +/** + Sets the dependent keys on this computed property. Pass any number of + arguments containing key paths that this computed property depends on. - } else { - queueNames = Ember.run.queues; - len = queueNames.length; - idx = 0; + ```javascript + MyApp.president = Ember.Object.create({ + fullName: Ember.computed(function() { + return this.get('firstName') + ' ' + this.get('lastName'); - outerloop: - while (idx < len) { - queueName = queueNames[idx]; - queue = this._queues && this._queues[queueName]; - delete this._queues[queueName]; + // Tell Ember that this computed property depends on firstName + // and lastName + }).property('firstName', 'lastName') + }); + ``` - 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'); } + @method property + @param {String} path* zero or more property paths + @chainable +*/ +ComputedPropertyPrototype.property = function() { + var args = []; + for (var i = 0, l = arguments.length; i < l; i++) { + args.push(arguments[i]); + } + this._dependentKeys = args; + return this; +}; - Ember.beginPropertyChanges(); - try { - forEach.call(queue, iter); - } finally { - Ember.endPropertyChanges(); - } +/** + In some cases, you may want to annotate computed properties with additional + metadata about how they function or what values they operate on. For example, + computed property functions may close over variables that are then no longer + available for introspection. - if (log) { Ember.Logger.log('End: Flush Sync Queue'); } - } else { - forEach.call(queue, iter); - } - } + You can pass a hash of these values to a computed property like this: - // 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; - continue outerloop; - } - } + ``` + person: function() { + var personId = this.get('personId'); + return App.Person.create({ id: personId }); + }.property().meta({ type: App.Person }) + ``` - idx++; - } - } + The hash that you pass to the `meta()` function will be saved on the + computed property descriptor under the `_meta` key. Ember runtime + exposes a public API for retrieving these values from classes, + via the `metaForProperty()` function. - timerMark = null; + @method meta + @param {Hash} meta + @chainable +*/ +ComputedPropertyPrototype.meta = function(meta) { + if (arguments.length === 0) { + return this._meta || {}; + } else { + this._meta = meta; return this; } - }; -Ember.RunLoop = RunLoop; - -// .......................................................... -// Ember.run - this is ideally the only public API the dev sees -// - -/** - Runs the passed target and method inside of a RunLoop, ensuring any - deferred actions including bindings and views updates are flushed at the - end. +/* impl descriptor API */ +ComputedPropertyPrototype.willWatch = function(obj, keyName) { + // watch already creates meta for this instance + var meta = obj[META_KEY]; + Ember.assert('watch should have setup meta to be writable', meta.source === obj); + if (!(keyName in meta.cache)) { + addDependentKeys(this, obj, keyName, meta); + } +}; - Normally you should not need to invoke this method yourself. However if - you are implementing raw event handlers when interfacing with other - libraries or plugins, you should probably wrap all of your code inside this - call. +ComputedPropertyPrototype.didUnwatch = function(obj, keyName) { + var meta = obj[META_KEY]; + Ember.assert('unwatch should have setup meta to be writable', meta.source === obj); + if (!(keyName in meta.cache)) { + // unwatch already creates meta for this instance + removeDependentKeys(this, obj, keyName, meta); + } +}; - Ember.run(function(){ - // code to be execute within a RunLoop - }); +/* impl descriptor API */ +ComputedPropertyPrototype.didChange = function(obj, keyName) { + // _suspended is set via a CP.set to ensure we don't clear + // the cached value set by the setter + if (this._cacheable && this._suspended !== obj) { + var meta = metaFor(obj); + if (keyName in meta.cache) { + delete meta.cache[keyName]; + if (!meta.watching[keyName]) { + removeDependentKeys(this, obj, keyName, meta); + } + } + } +}; - @class run - @namespace Ember - @static - @constructor - @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. -*/ -Ember.run = function(target, method) { - var ret, loop; - run.begin(); - try { - if (target || method) { ret = invoke(target, method, arguments, 2); } - } finally { - run.end(); +/* impl descriptor API */ +ComputedPropertyPrototype.get = function(obj, keyName) { + var ret, cache, meta; + if (this._cacheable) { + meta = metaFor(obj); + cache = meta.cache; + if (keyName in cache) { return cache[keyName]; } + ret = cache[keyName] = this.func.call(obj, keyName); + if (!meta.watching[keyName]) { + addDependentKeys(this, obj, keyName, meta); + } + } else { + ret = this.func.call(obj, keyName); } return ret; }; -var run = Ember.run; +/* impl descriptor API */ +ComputedPropertyPrototype.set = function(obj, keyName, value) { + var cacheable = this._cacheable, + func = this.func, + meta = metaFor(obj, cacheable), + watched = meta.watching[keyName], + oldSuspended = this._suspended, + hadCachedValue = false, + cache = meta.cache, + cachedValue, ret; + this._suspended = obj; -/** - Begins a new RunLoop. Any deferred actions invoked after the begin will - be buffered until you invoke a matching call to Ember.run.end(). This is - an lower-level way to use a RunLoop instead of using Ember.run(). + try { + if (cacheable && cache.hasOwnProperty(keyName)) { + cachedValue = cache[keyName]; + hadCachedValue = true; + } - Ember.run.begin(); - // code to be execute within a RunLoop - Ember.run.end(); + // Check if the CP has been wrapped + if (func.wrappedFunction) { func = func.wrappedFunction; } - @method begin - @return {void} -*/ -Ember.run.begin = function() { - run.currentRunLoop = new RunLoop(run.currentRunLoop); -}; + // For backwards-compatibility with computed properties + // that check for arguments.length === 2 to determine if + // they are being get or set, only pass the old cached + // value if the computed property opts into a third + // argument. + if (func.length === 3) { + ret = func.call(obj, keyName, value, cachedValue); + } else if (func.length === 2) { + ret = func.call(obj, keyName, value); + } else { + Ember.defineProperty(obj, keyName, null, cachedValue); + Ember.set(obj, keyName, value); + return; + } -/** - Ends a RunLoop. This must be called sometime after you call Ember.run.begin() - to flush any deferred actions. This is a lower-level way to use a RunLoop - instead of using Ember.run(). + if (hadCachedValue && cachedValue === ret) { return; } + + if (watched) { Ember.propertyWillChange(obj, keyName); } - Ember.run.begin(); - // code to be execute within a RunLoop - Ember.run.end(); + if (hadCachedValue) { + delete cache[keyName]; + } - @method end - @return {void} -*/ -Ember.run.end = function() { - Ember.assert('must have a current run loop', run.currentRunLoop); - try { - run.currentRunLoop.end(); + if (cacheable) { + if (!watched && !hadCachedValue) { + addDependentKeys(this, obj, keyName, meta); + } + cache[keyName] = ret; + } + + if (watched) { Ember.propertyDidChange(obj, keyName); } + } finally { + this._suspended = oldSuspended; } - finally { - run.currentRunLoop = run.currentRunLoop.prev(); + return ret; +}; + +/* called when property is defined */ +ComputedPropertyPrototype.setup = function(obj, keyName) { + var meta = obj[META_KEY]; + if (meta && meta.watching[keyName]) { + addDependentKeys(this, obj, keyName, metaFor(obj)); } }; -/** - Array of named queues. This array determines the order in which queues - are flushed at the end of the RunLoop. You can define your own queues by - simply adding the queue name to this array. Normally you should not need - to inspect or modify this property. +/* called before property is overridden */ +ComputedPropertyPrototype.teardown = function(obj, keyName) { + var meta = metaFor(obj); - @property queues - @type Array - @default ['sync', 'actions', 'destroy', 'timers'] -*/ -Ember.run.queues = ['sync', 'actions', 'destroy', 'timers']; + if (meta.watching[keyName] || keyName in meta.cache) { + removeDependentKeys(this, obj, keyName, meta); + } -/** - Adds the passed target/method and any optional arguments to the named - queue to be executed at the end of the RunLoop. If you have not already - started a RunLoop when calling this method one will be started for you - automatically. + if (this._cacheable) { delete meta.cache[keyName]; } - At the end of a RunLoop, any methods scheduled in this way will be invoked. - Methods will be invoked in an order matching the named queues defined in - the run.queues property. + return null; // no value to restore +}; - Ember.run.schedule('timers', this, function(){ - // this will be executed at the end of the RunLoop, when timers are run - console.log("scheduled on timers queue"); - }); - Ember.run.schedule('sync', this, function(){ - // this will be executed at the end of the RunLoop, when bindings are synced - console.log("scheduled on sync queue"); - }); - // Note the functions will be run in order based on the run queues order. Output would be: - // scheduled on sync queue - // scheduled on timers queue - @method schedule - @param {String} queue The name of the queue to schedule against. - Default queues are 'sync' and 'actions' +/** + This helper returns a new property descriptor that wraps the passed + computed property function. You can use this helper to define properties + with mixins or via `Ember.defineProperty()`. - @param {Object} [target] target object to use as the context when invoking a method. + The function you pass will be used to both get and set property values. + 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. - @param {String|Function} method The method to invoke. If you pass a string it - will be resolved on the target object at the time the scheduled item is - invoked allowing you to change the target function. + @method computed + @for Ember + @param {Function} func The computed property function. + @return {Ember.ComputedProperty} property descriptor instance +*/ +Ember.computed = function(func) { + var args; - @param {Object} [arguments*] Optional arguments to be passed to the queued method. + if (arguments.length > 1) { + args = a_slice.call(arguments, 0, -1); + func = a_slice.call(arguments, -1)[0]; + } - @return {void} -*/ -Ember.run.schedule = function(queue, target, method) { - var loop = run.autorun(); - loop.schedule.apply(loop, arguments); -}; + var cp = new ComputedProperty(func); -var scheduledAutorun; -function autorun() { - scheduledAutorun = null; - if (run.currentRunLoop) { run.end(); } -} + if (args) { + cp.property.apply(cp, args); + } -// Used by global test teardown -Ember.run.hasScheduledTimers = function() { - return !!(scheduledAutorun || scheduledLater || scheduledNext); + return cp; }; -// Used by global test teardown -Ember.run.cancelTimers = function () { - if (scheduledAutorun) { - clearTimeout(scheduledAutorun); - scheduledAutorun = null; - } - if (scheduledLater) { - clearTimeout(scheduledLater); - scheduledLater = null; - } - if (scheduledNext) { - clearTimeout(scheduledNext); - scheduledNext = null; +/** + Returns the cached value for a property, if one exists. + This can be useful for peeking at the value of a computed + property that is generated lazily, without accidentally causing + it to be created. + + @method cacheFor + @for Ember + @param {Object} obj the object whose property you want to check + @param {String} key the name of the property whose cached value you want + to return +*/ +Ember.cacheFor = function cacheFor(obj, key) { + var cache = metaFor(obj, false).cache; + + if (cache && key in cache) { + return cache[key]; } - 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 computed.not + @for Ember + @param {String} dependentKey +*/ +Ember.computed.not = function(dependentKey) { + return Ember.computed(dependentKey, function(key) { + return !get(this, dependentKey); + }); +}; - @method autorun - @example - Ember.run.autorun(); - @return {Ember.RunLoop} the new current RunLoop +/** + @method computed.empty + @for Ember + @param {String} dependentKey */ -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); +Ember.computed.empty = function(dependentKey) { + return Ember.computed(dependentKey, function(key) { + var val = get(this, dependentKey); + return val === undefined || val === null || val === '' || (Ember.isArray(val) && get(val, 'length') === 0); + }); +}; - run.begin(); +/** + @method computed.bool + @for Ember + @param {String} dependentKey +*/ +Ember.computed.bool = function(dependentKey) { + return Ember.computed(dependentKey, function(key) { + return !!get(this, dependentKey); + }); +}; - if (!scheduledAutorun) { - scheduledAutorun = setTimeout(autorun, 1); +/** + @method computed.alias + @for Ember + @param {String} dependentKey +*/ +Ember.computed.alias = function(dependentKey) { + return Ember.computed(dependentKey, function(key, value){ + if (arguments.length === 1) { + return get(this, dependentKey); + } else { + set(this, dependentKey, value); + return value; } - } - - return run.currentRunLoop; + }); }; -/** - Immediately flushes any events scheduled in the 'sync' queue. Bindings - use this queue so this method is a useful way to immediately force all - bindings in the application to sync. +})(); - You should call this method anytime you need any changed state to propagate - throughout the app immediately without repainting the UI. - Ember.run.sync(); - @method sync - @return {void} +(function() { +/** +@module ember-metal */ -Ember.run.sync = function() { - run.autorun(); - run.currentRunLoop.flush('sync'); -}; -// .......................................................... -// TIMERS -// +var o_create = Ember.create, + metaFor = Ember.meta, + metaPath = Ember.metaPath, + META_KEY = Ember.META_KEY; -var timers = {}; // active timers... +/* + The event system uses a series of nested hashes to store listeners on an + object. When a listener is registered, or when an event arrives, these + hashes are consulted to determine which target and action pair to invoke. -var scheduledLater; -function invokeLaterTimers() { - scheduledLater = null; - var now = (+ new Date()), earliest = -1; - 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]; - invoke(timer.target, timer.method, timer.args, 2); - } else { - if (earliest<0 || (timer.expires < earliest)) earliest=timer.expires; + The hashes are stored in the object's meta hash, and look like this: + + // Object's meta hash + { + listeners: { // variable name: `listenerSet` + "foo:changed": [ // variable name: `actions` + [target, method, onceFlag, suspendedFlag] + ] + } } - } - } - // schedule next timeout to fire... - if (earliest > 0) { scheduledLater = setTimeout(invokeLaterTimers, earliest-(+ new Date())); } +*/ + +function indexOf(array, target, method) { + var index = -1; + for (var i = 0, l = array.length; i < l; i++) { + if (target === array[i][0] && method === array[i][1]) { index = i; break; } + } + return index; } -/** - 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 - of milliseconds. +function actionsFor(obj, eventName) { + var meta = metaFor(obj, true), + actions; - You should use this method whenever you need to run some action after a - period of time instead of using setTimeout(). This method will ensure that - items that expire during the same script execution cycle all execute - together, which is often more efficient than using a real setTimeout. + if (!meta.listeners) { meta.listeners = {}; } - Ember.run.later(myContext, function(){ - // code here will execute within a RunLoop in about 500ms with this == myContext - }, 500); + if (!meta.hasOwnProperty('listeners')) { + // setup inherited copy of the listeners object + meta.listeners = o_create(meta.listeners); + } - @method later - @param {Object} [target] target of method to invoke + actions = meta.listeners[eventName]; - @param {Function|String} method The method to invoke. - If you pass a string it will be resolved on the - target at the time the method is invoked. + // if there are actions, but the eventName doesn't exist in our listeners, then copy them from the prototype + if (actions && !meta.listeners.hasOwnProperty(eventName)) { + actions = meta.listeners[eventName] = meta.listeners[eventName].slice(); + } else if (!actions) { + actions = meta.listeners[eventName] = []; + } - @param {Object} [args*] Optional arguments to pass to the timeout. + return actions; +} - @param {Number} wait - Number of milliseconds to wait. +function actionsUnion(obj, eventName, otherActions) { + var meta = obj[META_KEY], + actions = meta && meta.listeners && meta.listeners[eventName]; - @return {String} a string you can use to cancel the timer in - {{#crossLink "Ember/run.cancel"}}{{/crossLink}} later. -*/ -Ember.run.later = function(target, method) { - var args, expires, timer, guid, wait; + if (!actions) { return; } + for (var i = actions.length - 1; i >= 0; i--) { + var target = actions[i][0], + method = actions[i][1], + once = actions[i][2], + suspended = actions[i][3], + actionIndex = indexOf(otherActions, target, method); - // 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(); + if (actionIndex === -1) { + otherActions.push([target, method, once, suspended]); + } } - - expires = (+ new Date()) + wait; - timer = { target: target, method: method, expires: expires, args: args }; - guid = Ember.guidFor(timer); - timers[guid] = timer; - run.once(timers, invokeLaterTimers); - return guid; -}; - -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; +function actionsDiff(obj, eventName, otherActions) { + var meta = obj[META_KEY], + actions = meta && meta.listeners && meta.listeners[eventName], + diffActions = []; - if (guid && timers[guid]) { - timers[guid].args = args; // replace args - } else { - timer = { - target: target, - method: method, - args: args, - tguid: tguid, - mguid: mguid - }; + if (!actions) { return; } + for (var i = actions.length - 1; i >= 0; i--) { + var target = actions[i][0], + method = actions[i][1], + once = actions[i][2], + suspended = actions[i][3], + actionIndex = indexOf(otherActions, target, method); - guid = Ember.guidFor(timer); - timers[guid] = timer; - if (!onceTimers[tguid]) { onceTimers[tguid] = {}; } - onceTimers[tguid][mguid] = guid; // so it isn't scheduled more than once + if (actionIndex !== -1) { continue; } - run.schedule(queue, timer, invokeOnceTimer, guid, onceTimers); + otherActions.push([target, method, once, suspended]); + diffActions.push([target, method, once, suspended]); } - return guid; + return diffActions; } /** - Schedules an item to run one time during the current RunLoop. Calling - this method with the same target/method combination will have no effect. + Add an event listener - Note that although you can pass optional arguments these will not be - considered when looking for duplicates. New arguments will replace previous - calls. + @method addListener + @for Ember + @param obj + @param {String} eventName + @param {Object|Function} targetOrMethod A target object or a function + @param {Function|String} method A function or the name of a function to be called on `target` +*/ +function addListener(obj, eventName, target, method, once) { + Ember.assert("You must pass at least an object and event name to Ember.addListener", !!obj && !!eventName); - Ember.run(function(){ - var doFoo = function() { foo(); } - Ember.run.once(myContext, doFoo); - Ember.run.once(myContext, doFoo); - // doFoo will only be executed once at the end of the RunLoop - }); + if (!method && 'function' === typeof target) { + method = target; + target = null; + } - @method once - @param {Object} [target] target of method to invoke + var actions = actionsFor(obj, eventName), + actionIndex = indexOf(actions, target, method); - @param {Function|String} method The method to invoke. - If you pass a string it will be resolved on the - target at the time the method is invoked. + if (actionIndex !== -1) { return; } - @param {Object} [args*] Optional arguments to pass to the timeout. + actions.push([target, method, once, undefined]); + if ('function' === typeof obj.didAddListener) { + obj.didAddListener(eventName, target, method); + } +} - @return {Object} timer +/** + Remove an event listener + + Arguments should match those passed to {{#crossLink "Ember/addListener"}}{{/crossLink}} + + @method removeListener + @for Ember + @param obj + @param {String} eventName + @param {Object|Function} targetOrMethod A target object or a function + @param {Function|String} method A function or the name of a function to be called on `target` */ -Ember.run.once = function(target, method) { - return scheduleOnce('actions', target, method, slice.call(arguments, 2)); -}; +function removeListener(obj, eventName, target, method) { + Ember.assert("You must pass at least an object and event name to Ember.removeListener", !!obj && !!eventName); -Ember.run.scheduleOnce = function(queue, target, method, args) { - return scheduleOnce(queue, target, method, slice.call(arguments, 3)); -}; + if (!method && 'function' === typeof target) { + method = target; + target = null; + } -var scheduledNext; -function invokeNextTimers() { - scheduledNext = null; - for(var key in timers) { - if (!timers.hasOwnProperty(key)) { continue; } - var timer = timers[key]; - if (timer.next) { - delete timers[key]; - invoke(timer.target, timer.method, timer.args, 2); + function _removeListener(target, method, once) { + var actions = actionsFor(obj, eventName), + actionIndex = indexOf(actions, target, method); + + // action doesn't exist, give up silently + if (actionIndex === -1) { return; } + + actions.splice(actionIndex, 1); + + if ('function' === typeof obj.didRemoveListener) { + obj.didRemoveListener(eventName, target, method); + } + } + + if (method) { + _removeListener(target, method); + } else { + var meta = obj[META_KEY], + actions = meta && meta.listeners && meta.listeners[eventName]; + + if (!actions) { return; } + for (var i = actions.length - 1; i >= 0; i--) { + _removeListener(actions[i][0], actions[i][1]); } } } /** - Schedules an item to run after control has been returned to the system. - This is often equivalent to calling setTimeout(function...,1). + @private - Ember.run.next(myContext, function(){ - // code to be executed in the next RunLoop, which will be scheduled after the current one - }); + Suspend listener during callback. - @method next - @param {Object} [target] target of method to invoke + This should only be used by the target of the event listener + when it is taking an action that would cause the event, e.g. + an object might suspend its property change listener while it is + setting that property. - @param {Function|String} method The method to invoke. - If you pass a string it will be resolved on the - target at the time the method is invoked. + @method suspendListener + @for Ember + @param obj + @param {String} eventName + @param {Object|Function} targetOrMethod A target object or a function + @param {Function|String} method A function or the name of a function to be called on `target` + @param {Function} callback +*/ +function suspendListener(obj, eventName, target, method, callback) { + if (!method && 'function' === typeof target) { + method = target; + target = null; + } - @param {Object} [args*] Optional arguments to pass to the timeout. + var actions = actionsFor(obj, eventName), + actionIndex = indexOf(actions, target, method), + action; - @return {Object} timer -*/ -Ember.run.next = function(target, method) { - var guid, - timer = { - target: target, - method: method, - args: slice.call(arguments), - next: true - }; + if (actionIndex !== -1) { + action = actions[actionIndex].slice(); // copy it, otherwise we're modifying a shared object + action[3] = true; // mark the action as suspended + actions[actionIndex] = action; // replace the shared object with our copy + } - guid = Ember.guidFor(timer); - timers[guid] = timer; + function tryable() { return callback.call(target); } + function finalizer() { if (action) { action[3] = undefined; } } - if (!scheduledNext) { scheduledNext = setTimeout(invokeNextTimers, 1); } - return guid; -}; + return Ember.tryFinally(tryable, finalizer); +} /** - Cancels a scheduled item. Must be a value returned by `Ember.run.later()`, - `Ember.run.once()`, or `Ember.run.next()`. - - var runNext = Ember.run.next(myContext, function(){ - // will not be executed - }); - Ember.run.cancel(runNext); + @private - var runLater = Ember.run.later(myContext, function(){ - // will not be executed - }, 500); - Ember.run.cancel(runLater); + Suspend listener during callback. - var runOnce = Ember.run.once(myContext, function(){ - // will not be executed - }); - Ember.run.cancel(runOnce); + This should only be used by the target of the event listener + when it is taking an action that would cause the event, e.g. + an object might suspend its property change listener while it is + setting that property. - @method cancel - @param {Object} timer Timer object to cancel - @return {void} + @method suspendListener + @for Ember + @param obj + @param {Array} eventName Array of event names + @param {Object|Function} targetOrMethod A target object or a function + @param {Function|String} method A function or the name of a function to be called on `target` + @param {Function} callback */ -Ember.run.cancel = function(timer) { - delete timers[timer]; -}; +function suspendListeners(obj, eventNames, target, method, callback) { + if (!method && 'function' === typeof target) { + method = target; + target = null; + } -})(); + var suspendedActions = [], + eventName, actions, action, i, l; + for (i=0, l=eventNames.length; i= 0; i--) { // looping in reverse for once listeners + if (!actions[i] || actions[i][3] === true) { continue; } -// .......................................................... -// BINDING -// + var target = actions[i][0], + method = actions[i][1], + once = actions[i][2]; -var Binding = function(toPath, fromPath) { - this._direction = 'fwd'; - this._from = fromPath; - this._to = toPath; - this._directionMap = Ember.Map.create(); -}; + if (once) { removeListener(obj, eventName, target, method); } + if (!target) { target = obj; } + if ('string' === typeof method) { method = target[method]; } + if (params) { + method.apply(target, params); + } else { + method.apply(target); + } + } + return true; +} /** -@class Binding -@namespace Ember + @private + @method hasListeners + @for Ember + @param obj + @param {String} eventName */ +function hasListeners(obj, eventName) { + var meta = obj[META_KEY], + actions = meta && meta.listeners && meta.listeners[eventName]; -Binding.prototype = { - /** - This copies the Binding so it can be connected to another object. - - @method copy - @return {Ember.Binding} - */ - copy: function () { - var copy = new Binding(this._to, this._from); - if (this._oneWay) { copy._oneWay = true; } - return copy; - }, - - // .......................................................... - // CONFIG - // + return !!(actions && actions.length); +} - /** - This will set "from" property path to the specified value. It will not - attempt to resolve this property path to an actual object until you - connect the binding. +/** + @private + @method listenersFor + @for Ember + @param obj + @param {String} eventName +*/ +function listenersFor(obj, eventName) { + var ret = []; + var meta = obj[META_KEY], + actions = meta && meta.listeners && meta.listeners[eventName]; - The binding will search for the property path starting at the root object - you pass when you connect() the binding. It follows the same rules as - `get()` - see that method for more information. + if (!actions) { return ret; } - @method from - @param {String} propertyPath the property path to connect to - @return {Ember.Binding} receiver - */ - from: function(path) { - this._from = path; - return this; - }, + for (var i = 0, l = actions.length; i < l; i++) { + var target = actions[i][0], + method = actions[i][1]; + ret.push([target, method]); + } - /** - This will set the "to" property path to the specified value. It will not - attempt to resolve this property path to an actual object until you - connect the binding. + return ret; +} - The binding will search for the property path starting at the root object - you pass when you connect() the binding. It follows the same rules as - `get()` - see that method for more information. +Ember.addListener = addListener; +Ember.removeListener = removeListener; +Ember._suspendListener = suspendListener; +Ember._suspendListeners = suspendListeners; +Ember.sendEvent = sendEvent; +Ember.hasListeners = hasListeners; +Ember.watchedEvents = watchedEvents; +Ember.listenersFor = listenersFor; +Ember.listenersDiff = actionsDiff; +Ember.listenersUnion = actionsUnion; - @method to - @param {String|Tuple} propertyPath A property path or tuple - @return {Ember.Binding} this - */ - to: function(path) { - this._to = path; - return this; - }, +})(); - /** - Configures the binding as one way. A one-way binding will relay changes - on the "from" side to the "to" side, but not the other way around. This - means that if you change the "to" side directly, the "from" side may have - a different value. - @method oneWay - @return {Ember.Binding} receiver - */ - oneWay: function() { - this._oneWay = true; - return this; - }, - toString: function() { - var oneWay = this._oneWay ? '[oneWay]' : ''; - return "Ember.Binding<" + guidFor(this) + ">(" + this._from + " -> " + this._to + ")" + oneWay; - }, +(function() { +// Ember.Logger +// Ember.watch.flushPending +// Ember.beginPropertyChanges, Ember.endPropertyChanges +// Ember.guidFor, Ember.tryFinally - // .......................................................... - // CONNECT AND SYNC - // +/** +@module ember-metal +*/ - /** - Attempts to connect this binding instance so that it can receive and relay - changes. This method will raise an exception if you have not set the - from/to properties yet. +// .......................................................... +// HELPERS +// - @method connect - @param {Object} obj The root object for this binding. - @return {Ember.Binding} this - */ - connect: function(obj) { - Ember.assert('Must pass a valid object to Ember.Binding.connect()', !!obj); +var slice = [].slice, + forEach = Ember.ArrayPolyfills.forEach; - var fromPath = this._from, toPath = this._to; - Ember.trySet(obj, toPath, getWithGlobals(obj, fromPath)); +// invokes passed params - normalizing so you can pass target/func, +// target/string or just func +function invoke(target, method, args, ignore) { - // add an observer on the object to be notified when the binding should be updated - Ember.addObserver(obj, fromPath, this, this.fromDidChange); + if (method === undefined) { + method = target; + target = undefined; + } - // if the binding is a two-way binding, also set up an observer on the target - if (!this._oneWay) { Ember.addObserver(obj, toPath, this, this.toDidChange); } + if ('string' === typeof method) { method = target[method]; } + if (args && ignore > 0) { + args = args.length > ignore ? slice.call(args, ignore) : null; + } - this._readyToSync = true; + return Ember.handleErrors(function() { + // IE8's Function.prototype.apply doesn't accept undefined/null arguments. + return method.apply(target || this, args || []); + }, this); +} - return this; - }, - /** - Disconnects the binding instance. Changes will no longer be relayed. You - will not usually need to call this method. +// .......................................................... +// RUNLOOP +// - @method disconnect - @param {Object} obj The root object you passed when connecting the binding. - @return {Ember.Binding} this - */ - disconnect: function(obj) { - Ember.assert('Must pass a valid object to Ember.Binding.disconnect()', !!obj); +var timerMark; // used by timers... - var twoWay = !this._oneWay; +/** +Ember RunLoop (Private) - // remove an observer on the object so we're no longer notified of - // changes that should update bindings. - Ember.removeObserver(obj, this._from, this, this.fromDidChange); +@class RunLoop +@namespace Ember +@private +@constructor +*/ +var RunLoop = function(prev) { + this._prev = prev || null; + this.onceTimers = {}; +}; - // if the binding is two-way, remove the observer from the target as well - if (twoWay) { Ember.removeObserver(obj, this._to, this, this.toDidChange); } +RunLoop.prototype = { + /** + @method end + */ + end: function() { + this.flush(); + }, - this._readyToSync = false; // disable scheduled syncs... - return this; + /** + @method prev + */ + prev: function() { + return this._prev; }, // .......................................................... - // PRIVATE + // Delayed Actions // - /* called when the from side changes */ - fromDidChange: function(target) { - this._scheduleSync(target, 'fwd'); - }, + /** + @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] = []; } - /* called when the to side changes */ - toDidChange: function(target) { - this._scheduleSync(target, 'back'); + var args = arguments.length > 3 ? slice.call(arguments, 3) : null; + queue.push({ target: target, method: method, args: args }); + return this; }, - _scheduleSync: function(obj, dir) { - var directionMap = this._directionMap; - var existingDir = directionMap.get(obj); + /** + @method flush + @param {String} queueName + */ + flush: function(queueName) { + var queueNames, idx, len, queue, log; - // if we haven't scheduled the binding yet, schedule it - if (!existingDir) { - Ember.run.schedule('sync', this, this._sync, obj); - directionMap.set(obj, dir); + if (!this._queues) { return this; } // nothing to do + + function iter(item) { + invoke(item.target, item.method, item.args); } - // If both a 'back' and 'fwd' sync have been scheduled on the same object, - // default to a 'fwd' sync so that it remains deterministic. - if (existingDir === 'back' && dir === 'fwd') { - directionMap.set(obj, 'fwd'); + function tryable() { + forEach.call(queue, iter); } - }, - _sync: function(obj) { - var log = Ember.LOG_BINDINGS; + Ember.watch.flushPending(); // make sure all chained watchers are setup - // don't synchronize destroyed objects or disconnected bindings - if (obj.isDestroyed || !this._readyToSync) { return; } + if (queueName) { + while (this._queues && (queue = this._queues[queueName])) { + this._queues[queueName] = null; - // get the direction of the binding for the object we are - // synchronizing from - var directionMap = this._directionMap; - var direction = directionMap.get(obj); + // 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'); } - var fromPath = this._from, toPath = this._to; + Ember.beginPropertyChanges(); - directionMap.remove(obj); + Ember.tryFinally(tryable, Ember.endPropertyChanges); - // if we're synchronizing from the remote object... - if (direction === 'fwd') { - var fromValue = getWithGlobals(obj, this._from); - if (log) { - Ember.Logger.log(' ', this.toString(), '->', fromValue, obj); - } - if (this._oneWay) { - Ember.trySet(obj, toPath, fromValue); - } else { - Ember._suspendObserver(obj, toPath, this, this.toDidChange, function () { - Ember.trySet(obj, toPath, fromValue); - }); + if (log) { Ember.Logger.log('End: Flush Sync Queue'); } + + } else { + forEach.call(queue, iter); + } } - // if we're synchronizing *to* the remote object - } else if (direction === 'back') { - var toValue = get(obj, this._to); - if (log) { - Ember.Logger.log(' ', this.toString(), '<-', toValue, obj); - } - Ember._suspendObserver(obj, fromPath, this, this.fromDidChange, function () { - Ember.trySet(Ember.isGlobalPath(fromPath) ? window : obj, fromPath, toValue); - }); - } - } -}; + } else { + queueNames = Ember.run.queues; + len = queueNames.length; + idx = 0; -function mixinProperties(to, from) { - for (var key in from) { - if (from.hasOwnProperty(key)) { - to[key] = from[key]; - } - } -} + outerloop: + while (idx < len) { + queueName = queueNames[idx]; + queue = this._queues && this._queues[queueName]; + delete this._queues[queueName]; -mixinProperties(Binding, { + 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'); } - /** - See {{#crossLink "Ember.Binding/from"}}{{/crossLink}} + Ember.beginPropertyChanges(); - @method from - @static - */ - from: function() { - var C = this, binding = new C(); - return binding.from.apply(binding, arguments); - }, + Ember.tryFinally(tryable, Ember.endPropertyChanges); - /** - See {{#crossLink "Ember.Binding/to"}}{{/crossLink}} + if (log) { Ember.Logger.log('End: Flush Sync Queue'); } + } else { + forEach.call(queue, iter); + } + } - @method to - @static - */ - to: function() { - var C = this, binding = new C(); - return binding.to.apply(binding, arguments); - }, + // 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; + continue outerloop; + } + } - /** - Creates a new Binding instance and makes it apply in a single direction. - A one-way binding will relay changes on the "from" side object (supplied - as the `from` argument) the "to" side, but not the other way around. - This means that if you change the "to" side directly, the "from" side may have - a different value. + idx++; + } + } - See {{#crossLink "Binding/oneWay"}}{{/crossLink}} + timerMark = null; - @method oneWay - @param {String} from from path. - @param {Boolean} [flag] (Optional) passing nothing here will make the binding oneWay. You can - instead pass false to disable oneWay, making the binding two way again. - */ - oneWay: function(from, flag) { - var C = this, binding = new C(null, from); - return binding.oneWay(flag); + return this; } -}); +}; -/** - An Ember.Binding connects the properties of two objects so that whenever the - value of one property changes, the other property will be changed also. +Ember.RunLoop = RunLoop; - ## Automatic Creation of Bindings with `/^*Binding/`-named Properties - You do not usually create Binding objects directly but instead describe - bindings in your class or object definition using automatic binding detection. +// .......................................................... +// Ember.run - this is ideally the only public API the dev sees +// - Properties ending in a `Binding` suffix will be converted to Ember.Binding instances. - The value of this property should be a string representing a path to another object or - a custom binding instanced created using Binding helpers (see "Customizing Your Bindings"): +/** + Runs the passed target and method inside of a RunLoop, ensuring any + deferred actions including bindings and views updates are flushed at the + end. - valueBinding: "MyApp.someController.title" + Normally you should not need to invoke this method yourself. However if + you are implementing raw event handlers when interfacing with other + libraries or plugins, you should probably wrap all of your code inside this + call. - This will create a binding from `MyApp.someController.title` to the `value` - property of your object instance automatically. Now the two values will be - kept in sync. + ```javascript + Ember.run(function(){ + // code to be execute within a RunLoop + }); + ``` - ## One Way Bindings + @class run + @namespace Ember + @static + @constructor + @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. +*/ +Ember.run = function(target, method) { + var loop, + args = arguments; + run.begin(); - One especially useful binding customization you can use is the `oneWay()` - helper. This helper tells Ember that you are only interested in - receiving changes on the object you are binding from. For example, if you - are binding to a preference and you want to be notified if the preference - has changed, but your object will not be changing the preference itself, you - could do: + function tryable() { + if (target || method) { + return invoke(target, method, args, 2); + } + } - bigTitlesBinding: Ember.Binding.oneWay("MyApp.preferencesController.bigTitles") + return Ember.tryFinally(tryable, run.end); +}; - This way if the value of MyApp.preferencesController.bigTitles changes the - "bigTitles" property of your object will change also. However, if you - change the value of your "bigTitles" property, it will not update the - preferencesController. +var run = Ember.run; - One way bindings are almost twice as fast to setup and twice as fast to - execute because the binding only has to worry about changes to one side. - 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). +/** + Begins a new RunLoop. Any deferred actions invoked after the begin will + be buffered until you invoke a matching call to `Ember.run.end()`. This is + an lower-level way to use a RunLoop instead of using `Ember.run()`. - ## Adding Bindings Manually + ```javascript + Ember.run.begin(); + // code to be execute within a RunLoop + Ember.run.end(); + ``` - All of the examples above show you how to configure a custom binding, but - the result of these customizations will be a binding template, not a fully - active Binding instance. The binding will actually become active only when you - instantiate the object the binding belongs to. It is useful however, to - understand what actually happens when the binding is activated. + @method begin + @return {void} +*/ +Ember.run.begin = function() { + run.currentRunLoop = new RunLoop(run.currentRunLoop); +}; - For a binding to function it must have at least a "from" property and a "to" - property. The from property path points to the object/key that you want to - bind from while the to path points to the object/key you want to bind to. +/** + Ends a RunLoop. This must be called sometime after you call + `Ember.run.begin()` to flush any deferred actions. This is a lower-level way + to use a RunLoop instead of using `Ember.run()`. - When you define a custom binding, you are usually describing the property - you want to bind from (such as "MyApp.someController.value" in the examples - above). When your object is created, it will automatically assign the value - you want to bind "to" based on the name of your binding key. In the - examples above, during init, Ember objects will effectively call - something like this on your binding: + ```javascript + Ember.run.begin(); + // code to be execute within a RunLoop + Ember.run.end(); + ``` - binding = Ember.Binding.from(this.valueBinding).to("value"); + @method end + @return {void} +*/ +Ember.run.end = function() { + Ember.assert('must have a current run loop', run.currentRunLoop); - This creates a new binding instance based on the template you provide, and - sets the to path to the "value" property of the new object. Now that the - binding is fully configured with a "from" and a "to", it simply needs to be - connected to become active. This is done through the connect() method: + function tryable() { run.currentRunLoop.end(); } + function finalizer() { run.currentRunLoop = run.currentRunLoop.prev(); } - binding.connect(this); + Ember.tryFinally(tryable, finalizer); +}; - Note that when you connect a binding you pass the object you want it to be - connected to. This object will be used as the root for both the from and - to side of the binding when inspecting relative paths. This allows the - binding to be automatically inherited by subclassed objects as well. +/** + Array of named queues. This array determines the order in which queues + are flushed at the end of the RunLoop. You can define your own queues by + simply adding the queue name to this array. Normally you should not need + to inspect or modify this property. - Now that the binding is connected, it will observe both the from and to side - and relay changes. + @property queues + @type Array + @default ['sync', 'actions', 'destroy', 'timers'] +*/ +Ember.run.queues = ['sync', 'actions', 'destroy', 'timers']; - If you ever needed to do so (you almost never will, but it is useful to - understand this anyway), you could manually create an active binding by - using the Ember.bind() helper method. (This is the same method used by - to setup your bindings on objects): +/** + Adds the passed target/method and any optional arguments to the named + queue to be executed at the end of the RunLoop. If you have not already + started a RunLoop when calling this method one will be started for you + automatically. - Ember.bind(MyApp.anotherObject, "value", "MyApp.someController.value"); + At the end of a RunLoop, any methods scheduled in this way will be invoked. + Methods will be invoked in an order matching the named queues defined in + the `run.queues` property. - Both of these code fragments have the same effect as doing the most friendly - form of binding creation like so: + ```javascript + Ember.run.schedule('timers', this, function(){ + // this will be executed at the end of the RunLoop, when timers are run + console.log("scheduled on timers queue"); + }); - MyApp.anotherObject = Ember.Object.create({ - valueBinding: "MyApp.someController.value", + Ember.run.schedule('sync', this, function(){ + // this will be executed at the end of the RunLoop, when bindings are synced + console.log("scheduled on sync queue"); + }); - // OTHER CODE FOR THIS OBJECT... + // Note the functions will be run in order based on the run queues order. Output would be: + // scheduled on sync queue + // scheduled on timers queue + ``` - }); + @method schedule + @param {String} queue The name of the queue to schedule against. + Default queues are 'sync' and 'actions' + @param {Object} [target] target object to use as the context when invoking a method. + @param {String|Function} method The method to invoke. If you pass a string it + will be resolved on the target object at the time the scheduled item is + invoked allowing you to change the target function. + @param {Object} [arguments*] Optional arguments to be passed to the queued method. + @return {void} +*/ +Ember.run.schedule = function(queue, target, method) { + var loop = run.autorun(); + loop.schedule.apply(loop, arguments); +}; - Ember's built in binding creation method makes it easy to automatically - create bindings for you. You should always use the highest-level APIs - available, even if you understand how it works underneath. +var scheduledAutorun; +function autorun() { + scheduledAutorun = null; + if (run.currentRunLoop) { run.end(); } +} - @class Binding - @namespace Ember - @since Ember 0.9 -*/ -Ember.Binding = Binding; +// Used by global test teardown +Ember.run.hasScheduledTimers = function() { + return !!(scheduledAutorun || scheduledLater || scheduledNext); +}; +// Used by global test teardown +Ember.run.cancelTimers = function () { + if (scheduledAutorun) { + clearTimeout(scheduledAutorun); + scheduledAutorun = null; + } + if (scheduledLater) { + clearTimeout(scheduledLater); + scheduledLater = null; + } + if (scheduledNext) { + clearTimeout(scheduledNext); + scheduledNext = null; + } + timers = {}; +}; /** - Global helper method to create a new binding. Just pass the root object - along with a to and from path to create and connect the binding. + 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 bind - @for Ember - @param {Object} obj The root object of the transform. + @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); - @param {String} to The path to the 'to' side of the binding. - Must be relative to obj. + run.begin(); - @param {String} from The path to the 'from' side of the binding. - Must be relative to obj or a global path. + if (!scheduledAutorun) { + scheduledAutorun = setTimeout(autorun, 1); + } + } - @return {Ember.Binding} binding instance -*/ -Ember.bind = function(obj, to, from) { - return new Ember.Binding(to, from).connect(obj); + return run.currentRunLoop; }; /** - @method oneWay - @for Ember - @param {Object} obj The root object of the transform. + Immediately flushes any events scheduled in the 'sync' queue. Bindings + use this queue so this method is a useful way to immediately force all + bindings in the application to sync. - @param {String} to The path to the 'to' side of the binding. - Must be relative to obj. + You should call this method anytime you need any changed state to propagate + throughout the app immediately without repainting the UI. - @param {String} from The path to the 'from' side of the binding. - Must be relative to obj or a global path. + ```javascript + Ember.run.sync(); + ``` - @return {Ember.Binding} binding instance + @method sync + @return {void} */ -Ember.oneWay = function(obj, to, from) { - return new Ember.Binding(to, from).oneWay().connect(obj); +Ember.run.sync = function() { + run.autorun(); + run.currentRunLoop.flush('sync'); }; -})(); - - - -(function() { -/** -@module ember-metal -*/ +// .......................................................... +// TIMERS +// -var Mixin, REQUIRED, Alias, - classToString, superClassString, - a_map = Ember.ArrayPolyfills.map, - a_indexOf = Ember.ArrayPolyfills.indexOf, - a_forEach = Ember.ArrayPolyfills.forEach, - a_slice = [].slice, - EMPTY_META = {}, // dummy for non-writable meta - META_SKIP = { __emberproto__: true, __ember_count__: true }, - o_create = Ember.create, - defineProperty = Ember.defineProperty, - guidFor = Ember.guidFor; +var timers = {}; // active timers... -function mixinsMeta(obj) { - var m = Ember.meta(obj, true), ret = m.mixins; - if (!ret) { - ret = m.mixins = { __emberproto__: obj }; - } else if (ret.__emberproto__ !== obj) { - ret = m.mixins = o_create(ret); - ret.__emberproto__ = obj; +var scheduledLater; +function invokeLaterTimers() { + scheduledLater = null; + var now = (+ new Date()), earliest = -1; + 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]; + invoke(timer.target, timer.method, timer.args, 2); + } else { + if (earliest<0 || (timer.expires < earliest)) earliest=timer.expires; + } + } } - return ret; -} - -function initMixin(mixin, args) { - if (args && args.length > 0) { - mixin.mixins = a_map.call(args, function(x) { - if (x instanceof Mixin) { return x; } - // Note: Manually setup a primitive mixin here. This is the only - // way to actually get a primitive mixin. This way normal creation - // of mixins will give you combined mixins... - var mixin = new Mixin(); - mixin.properties = x; - return mixin; - }); - } - return mixin; + // schedule next timeout to fire... + if (earliest > 0) { scheduledLater = setTimeout(invokeLaterTimers, earliest-(+ new Date())); } } -function isMethod(obj) { - return 'function' === typeof obj && - obj.isMethod !== false && - obj !== Boolean && obj !== Object && obj !== Number && obj !== Array && obj !== Date && obj !== String; -} +/** + 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 + of milliseconds. -function mergeMixins(mixins, m, descs, values, base) { - var len = mixins.length, idx, mixin, guid, props, value, key, ovalue, concats; + You should use this method whenever you need to run some action after a + period of time instead of using `setTimeout()`. This method will ensure that + items that expire during the same script execution cycle all execute + together, which is often more efficient than using a real setTimeout. - function removeKeys(keyName) { - delete descs[keyName]; - delete values[keyName]; - } + ```javascript + Ember.run.later(myContext, function(){ + // code here will execute within a RunLoop in about 500ms with this == myContext + }, 500); + ``` - for(idx=0; idx < len; idx++) { - mixin = mixins[idx]; - Ember.assert('Expected hash or Mixin instance, got ' + Object.prototype.toString.call(mixin), typeof mixin === 'object' && mixin !== null && Object.prototype.toString.call(mixin) !== '[object Array]'); + @method later + @param {Object} [target] target of method to invoke + @param {Function|String} method The method to invoke. + If you pass a string it will be resolved on the + target at the time the method is invoked. + @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.later = function(target, method) { + var args, expires, timer, guid, wait; - if (mixin instanceof Mixin) { - guid = guidFor(mixin); - if (m[guid]) { continue; } - m[guid] = mixin; - props = mixin.properties; - } else { - props = mixin; // apply anonymous mixin properties - } + // 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(); + } - if (props) { - // reset before adding each new mixin to pickup concats from previous - concats = values.concatenatedProperties || base.concatenatedProperties; - if (props.concatenatedProperties) { - concats = concats ? concats.concat(props.concatenatedProperties) : props.concatenatedProperties; - } + expires = (+ new Date()) + wait; + timer = { target: target, method: method, expires: expires, args: args }; + guid = Ember.guidFor(timer); + timers[guid] = timer; + run.once(timers, invokeLaterTimers); + return guid; +}; - for (key in props) { - if (!props.hasOwnProperty(key)) { continue; } - value = props[key]; - if (value instanceof Ember.Descriptor) { - if (value === REQUIRED && descs[key]) { continue; } +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]; +} - descs[key] = value; - values[key] = undefined; - } else { - // impl super if needed... - if (isMethod(value)) { - ovalue = descs[key] === undefined && values[key]; - if (!ovalue) { ovalue = base[key]; } - if ('function' !== typeof ovalue) { ovalue = null; } - if (ovalue) { - var o = value.__ember_observes__, ob = value.__ember_observesBefore__; - value = Ember.wrap(value, ovalue); - value.__ember_observes__ = o; - value.__ember_observesBefore__ = ob; - } - } else if ((concats && a_indexOf.call(concats, key) >= 0) || key === 'concatenatedProperties') { - var baseValue = values[key] || base[key]; - value = baseValue ? baseValue.concat(value) : Ember.makeArray(value); - } +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; - descs[key] = undefined; - values[key] = value; - } - } + if (guid && timers[guid]) { + timers[guid].args = args; // replace args + } else { + timer = { + target: target, + method: method, + args: args, + tguid: tguid, + mguid: mguid + }; - // manually copy toString() because some JS engines do not enumerate it - if (props.hasOwnProperty('toString')) { - base.toString = props.toString; - } + guid = Ember.guidFor(timer); + timers[guid] = timer; + if (!onceTimers[tguid]) { onceTimers[tguid] = {}; } + onceTimers[tguid][mguid] = guid; // so it isn't scheduled more than once - } else if (mixin.mixins) { - mergeMixins(mixin.mixins, m, descs, values, base); - if (mixin._without) { a_forEach.call(mixin._without, removeKeys); } - } + run.schedule(queue, timer, invokeOnceTimer, guid, onceTimers); } -} -function writableReq(obj) { - var m = Ember.meta(obj), req = m.required; - if (!req || req.__emberproto__ !== obj) { - req = m.required = req ? o_create(req) : { __ember_count__: 0 }; - req.__emberproto__ = obj; - } - return req; + return guid; } -var IS_BINDING = Ember.IS_BINDING = /^.+Binding$/; +/** + Schedules an item to run one time during the current RunLoop. Calling + this method with the same target/method combination will have no effect. -function detectBinding(obj, key, value, m) { - if (IS_BINDING.test(key)) { - var bindings = m.bindings; - if (!bindings) { - bindings = m.bindings = { __emberproto__: obj }; - } else if (bindings.__emberproto__ !== obj) { - bindings = m.bindings = o_create(m.bindings); - bindings.__emberproto__ = obj; - } - bindings[key] = value; - } -} + Note that although you can pass optional arguments these will not be + considered when looking for duplicates. New arguments will replace previous + calls. -function connectBindings(obj, m) { - // TODO Mixin.apply(instance) should disconnect binding if exists - var bindings = m.bindings, key, binding, to; - if (bindings) { - for (key in bindings) { - binding = key !== '__emberproto__' && bindings[key]; - if (binding) { - to = key.slice(0, -7); // strip Binding off end - if (binding instanceof Ember.Binding) { - binding = binding.copy(); // copy prototypes' instance - binding.to(to); - } else { // binding is string path - binding = new Ember.Binding(to, binding); - } - binding.connect(obj); - obj[key] = binding; - } + ```javascript + Ember.run(function(){ + var doFoo = function() { foo(); } + Ember.run.once(myContext, doFoo); + Ember.run.once(myContext, doFoo); + // doFoo will only be executed once at the end of the RunLoop + }); + ``` + + @method once + @param {Object} [target] target of method to invoke + @param {Function|String} method The method to invoke. + If you pass a string it will be resolved on the + target at the time the method is invoked. + @param {Object} [args*] Optional arguments to pass to the timeout. + @return {Object} timer +*/ +Ember.run.once = function(target, method) { + return scheduleOnce('actions', target, method, slice.call(arguments, 2)); +}; + +Ember.run.scheduleOnce = function(queue, target, method, args) { + return scheduleOnce(queue, target, method, slice.call(arguments, 3)); +}; + +var scheduledNext; +function invokeNextTimers() { + scheduledNext = null; + for(var key in timers) { + if (!timers.hasOwnProperty(key)) { continue; } + var timer = timers[key]; + if (timer.next) { + delete timers[key]; + invoke(timer.target, timer.method, timer.args, 2); } - // mark as applied - m.bindings = { __emberproto__: obj }; } } -function finishPartial(obj, m) { - connectBindings(obj, m || Ember.meta(obj)); - return obj; -} - -function applyMixin(obj, mixins, partial) { - var descs = {}, values = {}, m = Ember.meta(obj), req = m.required, - key, value, desc, prevValue, paths, len, idx; - - // Go through all mixins and hashes passed in, and: - // - // * Handle concatenated properties - // * Set up _super wrapping if necessary - // * Set up computed property descriptors - // * Copying `toString` in broken browsers - mergeMixins(mixins, mixinsMeta(obj), descs, values, obj); +/** + Schedules an item to run after control has been returned to the system. + This is often equivalent to calling `setTimeout(function() {}, 1)`. - for(key in values) { - if (key === 'contructor') { continue; } - if (!values.hasOwnProperty(key)) { continue; } + ```javascript + Ember.run.next(myContext, function(){ + // code to be executed in the next RunLoop, which will be scheduled after the current one + }); + ``` - desc = descs[key]; - value = values[key]; + @method next + @param {Object} [target] target of method to invoke + @param {Function|String} method The method to invoke. + If you pass a string it will be resolved on the + target at the time the method is invoked. + @param {Object} [args*] Optional arguments to pass to the timeout. + @return {Object} timer +*/ +Ember.run.next = function(target, method) { + var guid, + timer = { + target: target, + method: method, + args: slice.call(arguments), + next: true + }; - if (desc === REQUIRED) { - if (!(key in obj)) { - Ember.assert('Required property not defined: '+key, !!partial); + guid = Ember.guidFor(timer); + timers[guid] = timer; - // for partial applies add to hash of required keys - req = writableReq(obj); - req.__ember_count__++; - req[key] = true; - } - } else { - while (desc && desc instanceof Alias) { - var altKey = desc.methodName; - if (descs[altKey] || values[altKey]) { - value = values[altKey]; - desc = descs[altKey]; - } else if (m.descs[altKey]) { - desc = m.descs[altKey]; - value = undefined; - } else { - desc = undefined; - value = obj[altKey]; - } - } + if (!scheduledNext) { scheduledNext = setTimeout(invokeNextTimers, 1); } + return guid; +}; - if (desc === undefined && value === undefined) { continue; } +/** + Cancels a scheduled item. Must be a value returned by `Ember.run.later()`, + `Ember.run.once()`, or `Ember.run.next()`. - prevValue = obj[key]; + ```javascript + var runNext = Ember.run.next(myContext, function(){ + // will not be executed + }); + Ember.run.cancel(runNext); - if ('function' === typeof prevValue) { - if ((paths = prevValue.__ember_observesBefore__)) { - len = paths.length; - for (idx=0; idx < len; idx++) { - Ember.removeBeforeObserver(obj, paths[idx], null, key); - } - } else if ((paths = prevValue.__ember_observes__)) { - len = paths.length; - for (idx=0; idx < len; idx++) { - Ember.removeObserver(obj, paths[idx], null, key); - } - } - } + var runLater = Ember.run.later(myContext, function(){ + // will not be executed + }, 500); + Ember.run.cancel(runLater); - detectBinding(obj, key, value, m); + var runOnce = Ember.run.once(myContext, function(){ + // will not be executed + }); + Ember.run.cancel(runOnce); + ``` - defineProperty(obj, key, desc, value, m); + @method cancel + @param {Object} timer Timer object to cancel + @return {void} +*/ +Ember.run.cancel = function(timer) { + delete timers[timer]; +}; - if ('function' === typeof value) { - if (paths = value.__ember_observesBefore__) { - len = paths.length; - for (idx=0; idx < len; idx++) { - Ember.addBeforeObserver(obj, paths[idx], null, key); - } - } else if (paths = value.__ember_observes__) { - len = paths.length; - for (idx=0; idx < len; idx++) { - Ember.addObserver(obj, paths[idx], null, key); - } - } - } +})(); - if (req && req[key]) { - req = writableReq(obj); - req.__ember_count__--; - req[key] = false; - } - } - } - if (!partial) { // don't apply to prototype - finishPartial(obj, m); - } - // Make sure no required attrs remain - if (!partial && req && req.__ember_count__>0) { - var keys = []; - for (key in req) { - if (META_SKIP[key]) { continue; } - keys.push(key); - } - // TODO: Remove surrounding if clause from production build - Ember.assert('Required properties not defined: '+keys.join(',')); - } - return obj; -} +(function() { +// Ember.Logger +// get, set, trySet +// guidFor, isArray, meta +// addObserver, removeObserver +// Ember.run.schedule +/** +@module ember-metal +*/ + +// .......................................................... +// CONSTANTS +// /** - @method mixin + Debug parameter you can turn on. This will log all bindings that fire to + the console. This should be disabled in production code. Note that you + can also enable this from the console or temporarily. + + @property LOG_BINDINGS @for Ember - @param obj - @param mixins* - @return obj + @type Boolean + @default false */ -Ember.mixin = function(obj) { - var args = a_slice.call(arguments, 1); - applyMixin(obj, args, false); - return obj; -}; +Ember.LOG_BINDINGS = false || !!Ember.ENV.LOG_BINDINGS; -/** - The `Ember.Mixin` class allows you to create mixins, whose properties can be - added to other classes. For instance, +var get = Ember.get, + set = Ember.set, + guidFor = Ember.guidFor, + isGlobalPath = Ember.isGlobalPath; - App.Editable = Ember.Mixin.create({ - edit: function() { - console.log('starting to edit'); - this.set('isEditing', true); - }, - isEditing: false - }); - // Mix mixins into classes by passing them as the first arguments to - // .extend or .create. - App.CommentView = Ember.View.extend(App.Editable, { - template: Ember.Handlebars.compile('{{#if isEditing}}...{{else}}...{{/if}}') - }); +function getWithGlobals(obj, path) { + return get(isGlobalPath(path) ? Ember.lookup : obj, path); +} - commentView = App.CommentView.create(); - commentView.edit(); // => outputs 'starting to edit' +// .......................................................... +// BINDING +// - Note that Mixins are created with `Ember.Mixin.create`, not - `Ember.Mixin.extend`. +var Binding = function(toPath, fromPath) { + this._direction = 'fwd'; + this._from = fromPath; + this._to = toPath; + this._directionMap = Ember.Map.create(); +}; - @class Mixin - @namespace Ember +/** +@class Binding +@namespace Ember */ -Ember.Mixin = function() { return initMixin(this, arguments); }; -Mixin = Ember.Mixin; +Binding.prototype = { + /** + This copies the Binding so it can be connected to another object. -Mixin._apply = applyMixin; + @method copy + @return {Ember.Binding} + */ + copy: function () { + var copy = new Binding(this._to, this._from); + if (this._oneWay) { copy._oneWay = true; } + return copy; + }, -Mixin.applyPartial = function(obj) { - var args = a_slice.call(arguments, 1); - return applyMixin(obj, args, true); -}; + // .......................................................... + // CONFIG + // -Mixin.finishPartial = finishPartial; + /** + This will set `from` property path to the specified value. It will not + attempt to resolve this property path to an actual object until you + connect the binding. -/** - @method create - @static - @param arguments* -*/ -Mixin.create = function() { - classToString.processed = false; - var M = this; - return initMixin(new M(), arguments); -}; + The binding will search for the property path starting at the root object + you pass when you `connect()` the binding. It follows the same rules as + `get()` - see that method for more information. -var MixinPrototype = Mixin.prototype; + @method from + @param {String} propertyPath the property path to connect to + @return {Ember.Binding} `this` + */ + from: function(path) { + this._from = path; + return this; + }, -/** - @method reopen - @param arguments* -*/ -MixinPrototype.reopen = function() { - var mixin, tmp; + /** + This will set the `to` property path to the specified value. It will not + attempt to resolve this property path to an actual object until you + connect the binding. - if (this.properties) { - mixin = Mixin.create(); - mixin.properties = this.properties; - delete this.properties; - this.mixins = [mixin]; - } else if (!this.mixins) { - this.mixins = []; - } + The binding will search for the property path starting at the root object + you pass when you `connect()` the binding. It follows the same rules as + `get()` - see that method for more information. - var len = arguments.length, mixins = this.mixins, idx; + @method to + @param {String|Tuple} propertyPath A property path or tuple + @return {Ember.Binding} `this` + */ + to: function(path) { + this._to = path; + return this; + }, - for(idx=0; idx < len; idx++) { - mixin = arguments[idx]; - Ember.assert('Expected hash or Mixin instance, got ' + Object.prototype.toString.call(mixin), typeof mixin === 'object' && mixin !== null && Object.prototype.toString.call(mixin) !== '[object Array]'); + /** + Configures the binding as one way. A one-way binding will relay changes + on the `from` side to the `to` side, but not the other way around. This + means that if you change the `to` side directly, the `from` side may have + a different value. - if (mixin instanceof Mixin) { - mixins.push(mixin); - } else { - tmp = Mixin.create(); - tmp.properties = mixin; - mixins.push(tmp); - } - } + @method oneWay + @return {Ember.Binding} `this` + */ + oneWay: function() { + this._oneWay = true; + return this; + }, - return this; -}; + toString: function() { + var oneWay = this._oneWay ? '[oneWay]' : ''; + return "Ember.Binding<" + guidFor(this) + ">(" + this._from + " -> " + this._to + ")" + oneWay; + }, -/** - @method apply - @param obj - @return applied object -*/ -MixinPrototype.apply = function(obj) { - return applyMixin(obj, [this], false); -}; + // .......................................................... + // CONNECT AND SYNC + // -MixinPrototype.applyPartial = function(obj) { - return applyMixin(obj, [this], true); -}; + /** + Attempts to connect this binding instance so that it can receive and relay + changes. This method will raise an exception if you have not set the + from/to properties yet. -function _detect(curMixin, targetMixin, seen) { - var guid = guidFor(curMixin); + @method connect + @param {Object} obj The root object for this binding. + @return {Ember.Binding} `this` + */ + connect: function(obj) { + Ember.assert('Must pass a valid object to Ember.Binding.connect()', !!obj); - if (seen[guid]) { return false; } - seen[guid] = true; + var fromPath = this._from, toPath = this._to; + Ember.trySet(obj, toPath, getWithGlobals(obj, fromPath)); - if (curMixin === targetMixin) { return true; } - var mixins = curMixin.mixins, loc = mixins ? mixins.length : 0; - while (--loc >= 0) { - if (_detect(mixins[loc], targetMixin, seen)) { return true; } - } - return false; -} + // add an observer on the object to be notified when the binding should be updated + Ember.addObserver(obj, fromPath, this, this.fromDidChange); -/** - @method detect - @param obj - @return {Boolean} -*/ -MixinPrototype.detect = function(obj) { - if (!obj) { return false; } - if (obj instanceof Mixin) { return _detect(obj, this, {}); } - var mixins = Ember.meta(obj, false).mixins; - if (mixins) { - return !!mixins[guidFor(this)]; - } - return false; -}; + // if the binding is a two-way binding, also set up an observer on the target + if (!this._oneWay) { Ember.addObserver(obj, toPath, this, this.toDidChange); } -MixinPrototype.without = function() { - var ret = new Mixin(this); - ret._without = a_slice.call(arguments); - return ret; -}; + this._readyToSync = true; -function _keys(ret, mixin, seen) { - if (seen[guidFor(mixin)]) { return; } - seen[guidFor(mixin)] = true; + return this; + }, - if (mixin.properties) { - var props = mixin.properties; - for (var key in props) { - if (props.hasOwnProperty(key)) { ret[key] = true; } - } - } else if (mixin.mixins) { - a_forEach.call(mixin.mixins, function(x) { _keys(ret, x, seen); }); - } -} + /** + Disconnects the binding instance. Changes will no longer be relayed. You + will not usually need to call this method. -MixinPrototype.keys = function() { - var keys = {}, seen = {}, ret = []; - _keys(keys, this, seen); - for(var key in keys) { - if (keys.hasOwnProperty(key)) { ret.push(key); } - } - return ret; -}; + @method disconnect + @param {Object} obj The root object you passed when connecting the binding. + @return {Ember.Binding} `this` + */ + disconnect: function(obj) { + Ember.assert('Must pass a valid object to Ember.Binding.disconnect()', !!obj); -/* make Mixins have nice displayNames */ + var twoWay = !this._oneWay; -var NAME_KEY = Ember.GUID_KEY+'_name'; -var get = Ember.get; + // remove an observer on the object so we're no longer notified of + // changes that should update bindings. + Ember.removeObserver(obj, this._from, this, this.fromDidChange); -function processNames(paths, root, seen) { - var idx = paths.length; - for(var key in root) { - if (!root.hasOwnProperty || !root.hasOwnProperty(key)) { continue; } - var obj = root[key]; - paths[idx] = key; + // if the binding is two-way, remove the observer from the target as well + if (twoWay) { Ember.removeObserver(obj, this._to, this, this.toDidChange); } - if (obj && obj.toString === classToString) { - obj[NAME_KEY] = paths.join('.'); - } else if (obj && get(obj, 'isNamespace')) { - if (seen[guidFor(obj)]) { continue; } - seen[guidFor(obj)] = true; - processNames(paths, obj, seen); - } - } - paths.length = idx; // cut out last item -} + this._readyToSync = false; // disable scheduled syncs... + return this; + }, -function findNamespaces() { - var Namespace = Ember.Namespace, obj, isNamespace; + // .......................................................... + // PRIVATE + // - if (Namespace.PROCESSED) { return; } + /* called when the from side changes */ + fromDidChange: function(target) { + this._scheduleSync(target, 'fwd'); + }, - for (var prop in window) { - // get(window.globalStorage, 'isNamespace') would try to read the storage for domain isNamespace and cause exception in Firefox. - // globalStorage is a storage obsoleted by the WhatWG storage specification. See https://developer.mozilla.org/en/DOM/Storage#globalStorage - if (prop === "globalStorage" && window.StorageList && window.globalStorage instanceof window.StorageList) { continue; } - // Unfortunately, some versions of IE don't support window.hasOwnProperty - if (window.hasOwnProperty && !window.hasOwnProperty(prop)) { continue; } + /* called when the to side changes */ + toDidChange: function(target) { + this._scheduleSync(target, 'back'); + }, - // At times we are not allowed to access certain properties for security reasons. - // There are also times where even if we can access them, we are not allowed to access their properties. - try { - obj = window[prop]; - isNamespace = obj && get(obj, 'isNamespace'); - } catch (e) { - continue; + _scheduleSync: function(obj, dir) { + var directionMap = this._directionMap; + var existingDir = directionMap.get(obj); + + // if we haven't scheduled the binding yet, schedule it + if (!existingDir) { + Ember.run.schedule('sync', this, this._sync, obj); + directionMap.set(obj, dir); } - if (isNamespace) { - Ember.deprecate("Namespaces should not begin with lowercase.", /^[A-Z]/.test(prop)); - obj[NAME_KEY] = prop; + // If both a 'back' and 'fwd' sync have been scheduled on the same object, + // default to a 'fwd' sync so that it remains deterministic. + if (existingDir === 'back' && dir === 'fwd') { + directionMap.set(obj, 'fwd'); } - } -} + }, -/** - @private - @method identifyNamespaces - @for Ember -*/ -Ember.identifyNamespaces = findNamespaces; + _sync: function(obj) { + var log = Ember.LOG_BINDINGS; -superClassString = function(mixin) { - var superclass = mixin.superclass; - if (superclass) { - if (superclass[NAME_KEY]) { return superclass[NAME_KEY]; } - else { return superClassString(superclass); } - } else { - return; - } -}; + // don't synchronize destroyed objects or disconnected bindings + if (obj.isDestroyed || !this._readyToSync) { return; } -classToString = function() { - var Namespace = Ember.Namespace, namespace; + // get the direction of the binding for the object we are + // synchronizing from + var directionMap = this._directionMap; + var direction = directionMap.get(obj); - // TODO: Namespace should really be in Metal - if (Namespace) { - if (!this[NAME_KEY] && !classToString.processed) { - if (!Namespace.PROCESSED) { - findNamespaces(); - Namespace.PROCESSED = true; - } + var fromPath = this._from, toPath = this._to; - classToString.processed = true; + directionMap.remove(obj); - var namespaces = Namespace.NAMESPACES; - for (var i=0, l=namespaces.length; i', fromValue, obj); + } + if (this._oneWay) { + Ember.trySet(obj, toPath, fromValue); + } else { + Ember._suspendObserver(obj, toPath, this, this.toDidChange, function () { + Ember.trySet(obj, toPath, fromValue); + }); + } + // if we're synchronizing *to* the remote object + } else if (direction === 'back') { + var toValue = get(obj, this._to); + if (log) { + Ember.Logger.log(' ', this.toString(), '<-', toValue, obj); } + Ember._suspendObserver(obj, fromPath, this, this.fromDidChange, function () { + Ember.trySet(Ember.isGlobalPath(fromPath) ? Ember.lookup : obj, fromPath, toValue); + }); } } - if (this[NAME_KEY]) { - return this[NAME_KEY]; - } else { - var str = superClassString(this); - if (str) { - return "(subclass of " + str + ")"; - } else { - return "(unknown mixin)"; +}; + +function mixinProperties(to, from) { + for (var key in from) { + if (from.hasOwnProperty(key)) { + to[key] = from[key]; } } -}; +} -MixinPrototype.toString = classToString; +mixinProperties(Binding, { -// returns the mixins currently applied to the specified object -// TODO: Make Ember.mixin -Mixin.mixins = function(obj) { - var ret = [], mixins = Ember.meta(obj, false).mixins, key, mixin; - if (mixins) { - for(key in mixins) { - if (META_SKIP[key]) { continue; } - mixin = mixins[key]; + /** + See {{#crossLink "Ember.Binding/from"}}{{/crossLink}} - // skip primitive mixins since these are always anonymous - if (!mixin.properties) { ret.push(mixins[key]); } - } - } - return ret; -}; + @method from + @static + */ + from: function() { + var C = this, binding = new C(); + return binding.from.apply(binding, arguments); + }, -REQUIRED = new Ember.Descriptor(); -REQUIRED.toString = function() { return '(Required Property)'; }; + /** + See {{#crossLink "Ember.Binding/to"}}{{/crossLink}} -/** - Denotes a required property for a mixin + @method to + @static + */ + to: function() { + var C = this, binding = new C(); + return binding.to.apply(binding, arguments); + }, - @method required - @for Ember -*/ -Ember.required = function() { - return REQUIRED; -}; + /** + Creates a new Binding instance and makes it apply in a single direction. + A one-way binding will relay changes on the `from` side object (supplied + as the `from` argument) the `to` side, but not the other way around. + This means that if you change the "to" side directly, the "from" side may have + a different value. -Alias = function(methodName) { - this.methodName = methodName; -}; -Alias.prototype = new Ember.Descriptor(); + See {{#crossLink "Binding/oneWay"}}{{/crossLink}} + + @method oneWay + @param {String} from from path. + @param {Boolean} [flag] (Optional) passing nothing here will make the + binding `oneWay`. You can instead pass `false` to disable `oneWay`, making the + binding two way again. + */ + oneWay: function(from, flag) { + var C = this, binding = new C(null, from); + return binding.oneWay(flag); + } + +}); /** - Makes a property or method available via an additional name. + An `Ember.Binding` connects the properties of two objects so that whenever + the value of one property changes, the other property will be changed also. - App.PaintSample = Ember.Object.extend({ - color: 'red', - colour: Ember.alias('color'), - name: function(){ - return "Zed"; - }, - moniker: Ember.alias("name") - }); - var paintSample = App.PaintSample.create() - paintSample.get('colour'); //=> 'red' - paintSample.moniker(); //=> 'Zed' + ## Automatic Creation of Bindings with `/^*Binding/`-named Properties - @method alias - @for Ember - @param {String} methodName name of the method or property to alias - @return {Ember.Descriptor} -*/ -Ember.alias = function(methodName) { - return new Alias(methodName); -}; + You do not usually create Binding objects directly but instead describe + bindings in your class or object definition using automatic binding + detection. -// .......................................................... -// OBSERVER HELPER -// + Properties ending in a `Binding` suffix will be converted to `Ember.Binding` + instances. The value of this property should be a string representing a path + to another object or a custom binding instanced created using Binding helpers + (see "Customizing Your Bindings"): -/** - @method observer - @for Ember - @param {Function} func - @param {String} propertyNames* - @return func -*/ -Ember.observer = function(func) { - var paths = a_slice.call(arguments, 1); - func.__ember_observes__ = paths; - return func; -}; + ``` + valueBinding: "MyApp.someController.title" + ``` -// If observers ever become asynchronous, Ember.immediateObserver -// must remain synchronous. -/** - @method immediateObserver - @for Ember - @param {Function} func - @param {String} propertyNames* - @return func -*/ -Ember.immediateObserver = function() { - for (var i=0, l=arguments.length; i 'undefined' - Ember.typeOf(null); => 'null' - Ember.typeOf(undefined); => 'undefined' - Ember.typeOf('michael'); => 'string' - Ember.typeOf(101); => 'number' - Ember.typeOf(true); => 'boolean' - Ember.typeOf(Ember.makeArray); => 'function' - Ember.typeOf([1,2,90]); => 'array' - Ember.typeOf(Ember.Object.extend()); => 'class' - Ember.typeOf(Ember.Object.create()); => 'instance' - Ember.typeOf(new Error('teamocil')); => 'error' - - // "normal" JavaScript object - Ember.typeOf({a: 'b'}); => 'object' + Both of these code fragments have the same effect as doing the most friendly + form of binding creation like so: - @method typeOf - @for Ember - @param item {Object} the item to check - @return {String} the type -*/ -Ember.typeOf = function(item) { - var ret; + ```javascript + MyApp.anotherObject = Ember.Object.create({ + valueBinding: "MyApp.someController.value", - ret = (item === null || item === undefined) ? String(item) : TYPE_MAP[toString.call(item)] || 'object'; + // OTHER CODE FOR THIS OBJECT... + }); + ``` - if (ret === 'function') { - if (Ember.Object && Ember.Object.detect(item)) ret = 'class'; - } else if (ret === 'object') { - if (item instanceof Error) ret = 'error'; - else if (Ember.Object && item instanceof Ember.Object) ret = 'instance'; - else ret = 'object'; - } + Ember's built in binding creation method makes it easy to automatically + create bindings for you. You should always use the highest-level APIs + available, even if you understand how it works underneath. - return ret; -}; + @class Binding + @namespace Ember + @since Ember 0.9 +*/ +Ember.Binding = Binding; -/** - Returns true if the passed value is null or undefined. This avoids errors - from JSLint complaining about use of ==, which can be technically - confusing. - Ember.none(); => true - Ember.none(null); => true - Ember.none(undefined); => true - Ember.none(''); => false - Ember.none([]); => false - Ember.none(function(){}); => false +/** + Global helper method to create a new binding. Just pass the root object + along with a `to` and `from` path to create and connect the binding. - @method none + @method bind @for Ember - @param {Object} obj Value to test - @return {Boolean} + @param {Object} obj The root object of the transform. + @param {String} to The path to the 'to' side of the binding. + Must be relative to obj. + @param {String} from The path to the 'from' side of the binding. + Must be relative to obj or a global path. + @return {Ember.Binding} binding instance */ -Ember.none = function(obj) { - return obj === null || obj === undefined; +Ember.bind = function(obj, to, from) { + return new Ember.Binding(to, from).connect(obj); }; /** - Verifies that a value is null or an empty string | array | function. - - Constrains the rules on `Ember.none` by returning false for empty - string and empty arrays. - - Ember.empty(); => true - Ember.empty(null); => true - Ember.empty(undefined); => true - Ember.empty(''); => true - Ember.empty([]); => true - Ember.empty('tobias fünke'); => false - Ember.empty([0,1,2]); => false - - @method empty + @method oneWay @for Ember - @param {Object} obj Value to test - @return {Boolean} + @param {Object} obj The root object of the transform. + @param {String} to The path to the 'to' side of the binding. + Must be relative to obj. + @param {String} from The path to the 'from' side of the binding. + Must be relative to obj or a global path. + @return {Ember.Binding} binding instance */ -Ember.empty = function(obj) { - return obj === null || obj === undefined || (obj.length === 0 && typeof obj !== 'function') || (typeof obj === 'object' && Ember.get(obj, 'length') === 0); +Ember.oneWay = function(obj, to, from) { + return new Ember.Binding(to, from).oneWay().connect(obj); }; +})(); + + + +(function() { /** - This will compare two javascript values of possibly different types. - It will tell you which one is greater than the other by returning: +@module ember-metal +*/ - - -1 if the first is smaller than the second, - - 0 if both are equal, - - 1 if the first is greater than the second. +var Mixin, REQUIRED, Alias, + a_map = Ember.ArrayPolyfills.map, + a_indexOf = Ember.ArrayPolyfills.indexOf, + a_forEach = Ember.ArrayPolyfills.forEach, + a_slice = [].slice, + EMPTY_META = {}, // dummy for non-writable meta + o_create = Ember.create, + defineProperty = Ember.defineProperty, + guidFor = Ember.guidFor; - The order is calculated based on Ember.ORDER_DEFINITION, if types are different. - In case they have the same type an appropriate comparison for this type is made. +function mixinsMeta(obj) { + var m = Ember.meta(obj, true), ret = m.mixins; + if (!ret) { + ret = m.mixins = {}; + } else if (!m.hasOwnProperty('mixins')) { + ret = m.mixins = o_create(ret); + } + return ret; +} - Ember.compare('hello', 'hello'); => 0 - Ember.compare('abc', 'dfg'); => -1 - Ember.compare(2, 1); => 1 +function initMixin(mixin, args) { + if (args && args.length > 0) { + mixin.mixins = a_map.call(args, function(x) { + if (x instanceof Mixin) { return x; } - @method compare - @for Ember - @param {Object} v First value to compare - @param {Object} w Second value to compare - @return {Number} -1 if v < w, 0 if v = w and 1 if v > w. -*/ -Ember.compare = function compare(v, w) { - if (v === w) { return 0; } + // Note: Manually setup a primitive mixin here. This is the only + // way to actually get a primitive mixin. This way normal creation + // of mixins will give you combined mixins... + var mixin = new Mixin(); + mixin.properties = x; + return mixin; + }); + } + return mixin; +} - var type1 = Ember.typeOf(v); - var type2 = Ember.typeOf(w); +function isMethod(obj) { + return 'function' === typeof obj && + obj.isMethod !== false && + obj !== Boolean && obj !== Object && obj !== Number && obj !== Array && obj !== Date && obj !== String; +} - var Comparable = Ember.Comparable; - if (Comparable) { - if (type1==='instance' && Comparable.detect(v.constructor)) { - return v.constructor.compare(v, w); - } +var CONTINUE = {}; - if (type2 === 'instance' && Comparable.detect(w.constructor)) { - return 1-w.constructor.compare(w, v); - } +function mixinProperties(mixinsMeta, mixin) { + var guid; + + if (mixin instanceof Mixin) { + guid = guidFor(mixin); + if (mixinsMeta[guid]) { return CONTINUE; } + mixinsMeta[guid] = mixin; + return mixin.properties; + } else { + return mixin; // apply anonymous mixin properties } +} - // If we haven't yet generated a reverse-mapping of Ember.ORDER_DEFINITION, - // do so now. - var mapping = Ember.ORDER_DEFINITION_MAPPING; - if (!mapping) { - var order = Ember.ORDER_DEFINITION; - mapping = Ember.ORDER_DEFINITION_MAPPING = {}; - var idx, len; - for (idx = 0, len = order.length; idx < len; ++idx) { - mapping[order[idx]] = idx; - } +function concatenatedProperties(props, values, base) { + var concats; - // We no longer need Ember.ORDER_DEFINITION. - delete Ember.ORDER_DEFINITION; + // reset before adding each new mixin to pickup concats from previous + concats = values.concatenatedProperties || base.concatenatedProperties; + if (props.concatenatedProperties) { + concats = concats ? concats.concat(props.concatenatedProperties) : props.concatenatedProperties; } - var type1Index = mapping[type1]; - var type2Index = mapping[type2]; + return concats; +} - if (type1Index < type2Index) { return -1; } - if (type1Index > type2Index) { return 1; } +function giveDescriptorSuper(meta, key, property, values, descs) { + var superProperty; - // types are equal - so we have to check values now - switch (type1) { - case 'boolean': - case 'number': - if (v < w) { return -1; } - if (v > w) { return 1; } - return 0; + // Computed properties override methods, and do not call super to them + if (values[key] === undefined) { + // Find the original descriptor in a parent mixin + superProperty = descs[key]; + } - case 'string': - var comp = v.localeCompare(w); - if (comp < 0) { return -1; } - if (comp > 0) { return 1; } - return 0; + // If we didn't find the original descriptor in a parent mixin, find + // it on the original object. + superProperty = superProperty || meta.descs[key]; - case 'array': - var vLen = v.length; - var wLen = w.length; - var l = Math.min(vLen, wLen); - var r = 0; - var i = 0; - while (r === 0 && i < l) { - r = compare(v[i],w[i]); - i++; - } - if (r !== 0) { return r; } + if (!superProperty || !(superProperty instanceof Ember.ComputedProperty)) { + return property; + } - // all elements are equal now - // shorter array should be ordered first - if (vLen < wLen) { return -1; } - if (vLen > wLen) { return 1; } - // arrays are equal now - return 0; + // Since multiple mixins may inherit from the same parent, we need + // to clone the computed property so that other mixins do not receive + // the wrapped version. + property = o_create(property); + property.func = Ember.wrap(property.func, superProperty.func); - case 'instance': - if (Ember.Comparable && Ember.Comparable.detect(v)) { - return v.compare(v, w); - } - return 0; + return property; +} - case 'date': - var vNum = v.getTime(); - var wNum = w.getTime(); - if (vNum < wNum) { return -1; } - if (vNum > wNum) { return 1; } - return 0; +function giveMethodSuper(obj, key, method, values, descs) { + var superMethod; - default: - return 0; + // Methods overwrite computed properties, and do not call super to them. + if (descs[key] === undefined) { + // Find the original method in a parent mixin + superMethod = values[key]; } -}; -function _copy(obj, deep, seen, copies) { - var ret, loc, key; + // If we didn't find the original value in a parent mixin, find it in + // the original object + superMethod = superMethod || obj[key]; - // primitive data types are immutable, just return them. - if ('object' !== typeof obj || obj===null) return obj; + // Only wrap the new method if the original method was a function + if ('function' !== typeof superMethod) { + return method; + } - // avoid cyclical loops - if (deep && (loc=indexOf(seen, obj))>=0) return copies[loc]; + return Ember.wrap(method, superMethod); +} - Ember.assert('Cannot clone an Ember.Object that does not implement Ember.Copyable', !(obj instanceof Ember.Object) || (Ember.Copyable && Ember.Copyable.detect(obj))); +function applyConcatenatedProperties(obj, key, value, values) { + var baseValue = values[key] || obj[key]; - // IMPORTANT: this specific test will detect a native array only. Any other - // object will need to implement Copyable. - if (Ember.typeOf(obj) === 'array') { - ret = obj.slice(); - if (deep) { - loc = ret.length; - while(--loc>=0) ret[loc] = _copy(ret[loc], deep, seen, copies); + if (baseValue) { + if ('function' === typeof baseValue.concat) { + return baseValue.concat(value); + } else { + return Ember.makeArray(baseValue).concat(value); } - } else if (Ember.Copyable && Ember.Copyable.detect(obj)) { - ret = obj.copy(deep, seen, copies); } else { - ret = {}; - for(key in obj) { - if (!obj.hasOwnProperty(key)) continue; - ret[key] = deep ? _copy(obj[key], deep, seen, copies) : obj[key]; + return Ember.makeArray(value); + } +} + +function addNormalizedProperty(base, key, value, meta, descs, values, concats) { + if (value instanceof Ember.Descriptor) { + if (value === REQUIRED && descs[key]) { return CONTINUE; } + + // Wrap descriptor function to implement + // _super() if needed + if (value.func) { + value = giveDescriptorSuper(meta, key, value, values, descs); + } + + descs[key] = value; + values[key] = undefined; + } else { + // impl super if needed... + if (isMethod(value)) { + value = giveMethodSuper(base, key, value, values, descs); + } else if ((concats && a_indexOf.call(concats, key) >= 0) || key === 'concatenatedProperties') { + value = applyConcatenatedProperties(base, key, value, values); } + + descs[key] = undefined; + values[key] = value; } +} - if (deep) { - seen.push(obj); - copies.push(ret); +function mergeMixins(mixins, m, descs, values, base) { + var mixin, props, key, concats, meta; + + function removeKeys(keyName) { + delete descs[keyName]; + delete values[keyName]; } - return ret; -} + for(var i=0, l=mixins.length; i true - Ember.isEqual(1, 2); => false - Ember.isEqual([4,2], [4,2]); => false +function finishPartial(obj, m) { + connectBindings(obj, m || Ember.meta(obj)); + return obj; +} - @method isEqual - @for Ember - @param {Object} a first object to compare - @param {Object} b second object to compare - @return {Boolean} -*/ -Ember.isEqual = function(a, b) { - if (a && 'function'===typeof a.isEqual) return a.isEqual(b); - return a === b; -}; +function followAlias(obj, desc, m, descs, values) { + var altKey = desc.methodName, value; + if (descs[altKey] || values[altKey]) { + value = values[altKey]; + desc = descs[altKey]; + } else if (m.descs[altKey]) { + desc = m.descs[altKey]; + value = undefined; + } else { + desc = undefined; + value = obj[altKey]; + } -// Used by Ember.compare -Ember.ORDER_DEFINITION = Ember.ENV.ORDER_DEFINITION || [ - 'undefined', - 'null', - 'boolean', - 'number', - 'string', - 'array', - 'object', - 'instance', - 'function', - 'class', - 'date' -]; + return { desc: desc, value: value }; +} -/** - Returns all of the keys defined on an object or hash. This is useful - when inspecting objects for debugging. On browsers that support it, this - uses the native Object.keys implementation. +function updateObservers(obj, key, observer, observerKey, method) { + if ('function' !== typeof observer) { return; } - @method keys - @for Ember - @param {Object} obj - @return {Array} Array containing keys of obj -*/ -Ember.keys = Object.keys; + var paths = observer[observerKey]; -if (!Ember.keys) { - Ember.keys = function(obj) { - var ret = []; - for(var key in obj) { - if (obj.hasOwnProperty(key)) { ret.push(key); } + if (paths) { + for (var i=0, l=paths.length; i= 0) { + if (_detect(mixins[loc], targetMixin, seen)) { return true; } + } + return false; +} + +/** + @method detect + @param obj + @return {Boolean} +*/ +MixinPrototype.detect = function(obj) { + if (!obj) { return false; } + if (obj instanceof Mixin) { return _detect(obj, this, {}); } + var mixins = Ember.meta(obj, false).mixins; + if (mixins) { + return !!mixins[guidFor(this)]; + } + return false; +}; + +MixinPrototype.without = function() { + var ret = new Mixin(this); + ret._without = a_slice.call(arguments); + return ret; +}; + +function _keys(ret, mixin, seen) { + if (seen[guidFor(mixin)]) { return; } + seen[guidFor(mixin)] = true; + + if (mixin.properties) { + var props = mixin.properties; + for (var key in props) { + if (props.hasOwnProperty(key)) { ret[key] = true; } + } + } else if (mixin.mixins) { + a_forEach.call(mixin.mixins, function(x) { _keys(ret, x, seen); }); + } +} + +MixinPrototype.keys = function() { + var keys = {}, seen = {}, ret = []; + _keys(keys, this, seen); + for(var key in keys) { + if (keys.hasOwnProperty(key)) { ret.push(key); } + } + return ret; +}; + +// returns the mixins currently applied to the specified object +// TODO: Make Ember.mixin +Mixin.mixins = function(obj) { + var mixins = Ember.meta(obj, false).mixins, ret = []; + + if (!mixins) { return ret; } + + for (var key in mixins) { + var mixin = mixins[key]; + + // skip primitive mixins since these are always anonymous + if (!mixin.properties) { ret.push(mixin); } + } + + return ret; +}; + +REQUIRED = new Ember.Descriptor(); +REQUIRED.toString = function() { return '(Required Property)'; }; + +/** + Denotes a required property for a mixin + + @method required + @for Ember +*/ +Ember.required = function() { + return REQUIRED; +}; + +Alias = function(methodName) { + this.methodName = methodName; +}; +Alias.prototype = new Ember.Descriptor(); + +/** + Makes a property or method available via an additional name. + + ```javascript + App.PaintSample = Ember.Object.extend({ + color: 'red', + colour: Ember.alias('color'), + name: function(){ + return "Zed"; + }, + moniker: Ember.alias("name") + }); + + var paintSample = App.PaintSample.create() + paintSample.get('colour'); // 'red' + paintSample.moniker(); // 'Zed' + ``` + + @method alias + @for Ember + @param {String} methodName name of the method or property to alias + @return {Ember.Descriptor} + @deprecated Use `Ember.aliasMethod` or `Ember.computed.alias` instead +*/ +Ember.alias = function(methodName) { + return new Alias(methodName); +}; + +Ember.deprecateFunc("Ember.alias is deprecated. Please use Ember.aliasMethod or Ember.computed.alias instead.", Ember.alias); + +/** + Makes a method available via an additional name. + + ```javascript + App.Person = Ember.Object.extend({ + name: function(){ + return 'Tomhuda Katzdale'; + }, + moniker: Ember.aliasMethod('name') + }); + + var goodGuy = App.Person.create() + ``` + + @method aliasMethod + @for Ember + @param {String} methodName name of the method to alias + @return {Ember.Descriptor} +*/ +Ember.aliasMethod = function(methodName) { + return new Alias(methodName); +}; + +// .......................................................... +// OBSERVER HELPER +// + +/** + @method observer + @for Ember + @param {Function} func + @param {String} propertyNames* + @return func +*/ +Ember.observer = function(func) { + var paths = a_slice.call(arguments, 1); + func.__ember_observes__ = paths; + return func; +}; + +// If observers ever become asynchronous, Ember.immediateObserver +// must remain synchronous. +/** + @method immediateObserver + @for Ember + @param {Function} func + @param {String} propertyNames* + @return func +*/ +Ember.immediateObserver = function() { + for (var i=0, l=arguments.length; i w. +*/ +Ember.compare = function compare(v, w) { + if (v === w) { return 0; } + + var type1 = Ember.typeOf(v); + var type2 = Ember.typeOf(w); + + var Comparable = Ember.Comparable; + if (Comparable) { + if (type1==='instance' && Comparable.detect(v.constructor)) { + return v.constructor.compare(v, w); + } + + if (type2 === 'instance' && Comparable.detect(w.constructor)) { + return 1-w.constructor.compare(w, v); + } + } + + // If we haven't yet generated a reverse-mapping of Ember.ORDER_DEFINITION, + // do so now. + var mapping = Ember.ORDER_DEFINITION_MAPPING; + if (!mapping) { + var order = Ember.ORDER_DEFINITION; + mapping = Ember.ORDER_DEFINITION_MAPPING = {}; + var idx, len; + for (idx = 0, len = order.length; idx < len; ++idx) { + mapping[order[idx]] = idx; + } + + // We no longer need Ember.ORDER_DEFINITION. + delete Ember.ORDER_DEFINITION; + } + + var type1Index = mapping[type1]; + var type2Index = mapping[type2]; + + if (type1Index < type2Index) { return -1; } + if (type1Index > type2Index) { return 1; } + + // types are equal - so we have to check values now + switch (type1) { + case 'boolean': + case 'number': + if (v < w) { return -1; } + if (v > w) { return 1; } + return 0; + + case 'string': + var comp = v.localeCompare(w); + if (comp < 0) { return -1; } + if (comp > 0) { return 1; } + return 0; + + case 'array': + var vLen = v.length; + var wLen = w.length; + var l = Math.min(vLen, wLen); + var r = 0; + var i = 0; + while (r === 0 && i < l) { + r = compare(v[i],w[i]); + i++; + } + if (r !== 0) { return r; } + + // all elements are equal now + // shorter array should be ordered first + if (vLen < wLen) { return -1; } + if (vLen > wLen) { return 1; } + // arrays are equal now + return 0; + + case 'instance': + if (Ember.Comparable && Ember.Comparable.detect(v)) { + return v.compare(v, w); + } + return 0; + + case 'date': + var vNum = v.getTime(); + var wNum = w.getTime(); + if (vNum < wNum) { return -1; } + if (vNum > wNum) { return 1; } + return 0; + + default: + return 0; + } +}; + +function _copy(obj, deep, seen, copies) { + var ret, loc, key; + + // primitive data types are immutable, just return them. + if ('object' !== typeof obj || obj===null) return obj; + + // avoid cyclical loops + if (deep && (loc=indexOf(seen, obj))>=0) return copies[loc]; + + Ember.assert('Cannot clone an Ember.Object that does not implement Ember.Copyable', !(obj instanceof Ember.Object) || (Ember.Copyable && Ember.Copyable.detect(obj))); + + // IMPORTANT: this specific test will detect a native array only. Any other + // object will need to implement Copyable. + if (Ember.typeOf(obj) === 'array') { + ret = obj.slice(); + if (deep) { + loc = ret.length; + while(--loc>=0) ret[loc] = _copy(ret[loc], deep, seen, copies); + } + } else if (Ember.Copyable && Ember.Copyable.detect(obj)) { + ret = obj.copy(deep, seen, copies); + } else { + ret = {}; + for(key in obj) { + if (!obj.hasOwnProperty(key)) continue; + + // Prevents browsers that don't respect non-enumerability from + // copying internal Ember properties + if (key.substring(0,2) === '__') continue; + + ret[key] = deep ? _copy(obj[key], deep, seen, copies) : obj[key]; + } + } + + if (deep) { + seen.push(obj); + copies.push(ret); + } + + return ret; +} + +/** + Creates a clone of the passed object. This function can take just about + any type of object and create a clone of it, including primitive values + (which are not actually cloned because they are immutable). + + If the passed object implements the `clone()` method, then this function + will simply call that method and return the result. + + @method copy + @for Ember + @param {Object} object The object to clone + @param {Boolean} deep If true, a deep copy of the object is made + @return {Object} The cloned object +*/ +Ember.copy = function(obj, deep) { + // fast paths + if ('object' !== typeof obj || obj===null) return obj; // can't copy primitives + if (Ember.Copyable && Ember.Copyable.detect(obj)) return obj.copy(deep); + return _copy(obj, deep, deep ? [] : null, deep ? [] : null); +}; + +/** + Convenience method to inspect an object. This method will attempt to + convert the object into a useful string description. + + It is a pretty simple implementation. If you want something more robust, + use something like JSDump: https://github.com/NV/jsDump + + @method inspect + @for Ember + @param {Object} obj The object you want to inspect. + @return {String} A description of the object +*/ +Ember.inspect = function(obj) { + if (typeof obj !== 'object' || obj === null) { + return obj + ''; + } + + var v, ret = []; + for(var key in obj) { + if (obj.hasOwnProperty(key)) { + v = obj[key]; + if (v === 'toString') { continue; } // ignore useless items + if (Ember.typeOf(v) === 'function') { v = "function() { ... }"; } + ret.push(key + ": " + v); + } + } + return "{" + ret.join(", ") + "}"; +}; + +/** + Compares two objects, returning true if they are logically equal. This is + a deeper comparison than a simple triple equal. For sets it will compare the + internal objects. For any other object that implements `isEqual()` it will + respect that method. + + ```javascript + Ember.isEqual('hello', 'hello'); // true + Ember.isEqual(1, 2); // false + Ember.isEqual([4,2], [4,2]); // false + ``` + + @method isEqual + @for Ember + @param {Object} a first object to compare + @param {Object} b second object to compare + @return {Boolean} +*/ +Ember.isEqual = function(a, b) { + if (a && 'function'===typeof a.isEqual) return a.isEqual(b); + return a === b; +}; + +// Used by Ember.compare +Ember.ORDER_DEFINITION = Ember.ENV.ORDER_DEFINITION || [ + 'undefined', + 'null', + 'boolean', + 'number', + 'string', + 'array', + 'object', + 'instance', + 'function', + 'class', + 'date' +]; + +/** + Returns all of the keys defined on an object or hash. This is useful + when inspecting objects for debugging. On browsers that support it, this + uses the native `Object.keys` implementation. + + @method keys + @for Ember + @param {Object} obj + @return {Array} Array containing keys of obj +*/ +Ember.keys = Object.keys; + +if (!Ember.keys) { + Ember.keys = function(obj) { + var ret = []; + for(var key in obj) { + if (obj.hasOwnProperty(key)) { ret.push(key); } + } + return ret; + }; +} + +// .......................................................... +// ERROR +// + +var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; + +/** + A subclass of the JavaScript Error object for use in Ember. + + @class Error + @namespace Ember + @extends Error + @constructor +*/ +Ember.Error = function() { + var tmp = Error.prototype.constructor.apply(this, arguments); + + // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. + for (var idx = 0; idx < errorProps.length; idx++) { + this[errorProps[idx]] = tmp[errorProps[idx]]; + } +}; + +Ember.Error.prototype = Ember.create(Error.prototype); + +})(); + + + +(function() { +/** +@module ember +@submodule ember-runtime +*/ + +var STRING_DASHERIZE_REGEXP = (/[ _]/g); +var STRING_DASHERIZE_CACHE = {}; +var STRING_DECAMELIZE_REGEXP = (/([a-z])([A-Z])/g); +var STRING_CAMELIZE_REGEXP = (/(\-|_|\.|\s)+(.)?/g); +var STRING_UNDERSCORE_REGEXP_1 = (/([a-z\d])([A-Z]+)/g); +var STRING_UNDERSCORE_REGEXP_2 = (/\-|\s+/g); + +/** + Defines the hash of localized strings for the current language. Used by + the `Ember.String.loc()` helper. To localize, add string values to this + hash. + + @property STRINGS + @for Ember + @type Hash +*/ +Ember.STRINGS = {}; + +/** + Defines string helper methods including string formatting and localization. + Unless `Ember.EXTEND_PROTOTYPES.String` is `false` these methods will also be + added to the `String.prototype` as well. + + @class String + @namespace Ember + @static +*/ +Ember.String = { + + /** + Apply formatting options to the string. This will look for occurrences + of "%@" in your string and substitute them with the arguments you pass into + this method. If you want to control the specific order of replacement, + you can add a number after the key as well to indicate which argument + you want to insert. + + Ordered insertions are most useful when building loc strings where values + you need to insert may appear in different orders. + + ```javascript + "Hello %@ %@".fmt('John', 'Doe'); // "Hello John Doe" + "Hello %@2, %@1".fmt('John', 'Doe'); // "Hello Doe, John" + ``` + + @method fmt + @param {Object...} [args] + @return {String} formatted string + */ + fmt: function(str, formats) { + // first, replace any ORDERED replacements. + var idx = 0; // the current index for non-numerical replacements + return str.replace(/%@([0-9]+)?/g, function(s, argIndex) { + argIndex = (argIndex) ? parseInt(argIndex,0) - 1 : idx++ ; + s = formats[argIndex]; + return ((s === null) ? '(null)' : (s === undefined) ? '' : s).toString(); + }) ; + }, + + /** + Formats the passed string, but first looks up the string in the localized + strings hash. This is a convenient way to localize text. See + `Ember.String.fmt()` for more information on formatting. + + Note that it is traditional but not required to prefix localized string + keys with an underscore or other character so you can easily identify + localized strings. + + ```javascript + Ember.STRINGS = { + '_Hello World': 'Bonjour le monde', + '_Hello %@ %@': 'Bonjour %@ %@' + }; + + Ember.String.loc("_Hello World"); // 'Bonjour le monde'; + Ember.String.loc("_Hello %@ %@", ["John", "Smith"]); // "Bonjour John Smith"; + ``` + + @method loc + @param {String} str The string to format + @param {Array} formats Optional array of parameters to interpolate into string. + @return {String} formatted string + */ + loc: function(str, formats) { + str = Ember.STRINGS[str] || str; + return Ember.String.fmt(str, formats) ; + }, + + /** + Splits a string into separate units separated by spaces, eliminating any + empty strings in the process. This is a convenience method for split that + is mostly useful when applied to the `String.prototype`. + + ```javascript + Ember.String.w("alpha beta gamma").forEach(function(key) { + console.log(key); + }); + + // > alpha + // > beta + // > gamma + ``` + + @method w + @param {String} str The string to split + @return {String} split string + */ + w: function(str) { return str.split(/\s+/); }, + + /** + Converts a camelized string into all lower case separated by underscores. + + ```javascript + 'innerHTML'.decamelize(); // 'inner_html' + 'action_name'.decamelize(); // 'action_name' + 'css-class-name'.decamelize(); // 'css-class-name' + 'my favorite items'.decamelize(); // 'my favorite items' + ``` + + @method decamelize + @param {String} str The string to decamelize. + @return {String} the decamelized string. + */ + decamelize: function(str) { + return str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase(); + }, + + /** + Replaces underscores or spaces with dashes. + + ```javascript + 'innerHTML'.dasherize(); // 'inner-html' + 'action_name'.dasherize(); // 'action-name' + 'css-class-name'.dasherize(); // 'css-class-name' + 'my favorite items'.dasherize(); // 'my-favorite-items' + ``` + + @method dasherize + @param {String} str The string to dasherize. + @return {String} the dasherized string. + */ + dasherize: function(str) { + var cache = STRING_DASHERIZE_CACHE, + ret = cache[str]; + + if (ret) { + return ret; + } else { + ret = Ember.String.decamelize(str).replace(STRING_DASHERIZE_REGEXP,'-'); + cache[str] = ret; + } + + return ret; + }, + + /** + Returns the lowerCaseCamel form of a string. + + ```javascript + 'innerHTML'.camelize(); // 'innerHTML' + 'action_name'.camelize(); // 'actionName' + 'css-class-name'.camelize(); // 'cssClassName' + 'my favorite items'.camelize(); // 'myFavoriteItems' + ``` + + @method camelize + @param {String} str The string to camelize. + @return {String} the camelized string. + */ + camelize: function(str) { + return str.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) { + return chr ? chr.toUpperCase() : ''; + }); + }, + + /** + Returns the UpperCamelCase form of a string. + + ```javascript + 'innerHTML'.classify(); // 'InnerHTML' + 'action_name'.classify(); // 'ActionName' + 'css-class-name'.classify(); // 'CssClassName' + 'my favorite items'.classify(); // 'MyFavoriteItems' + ``` + + @method classify + @param {String} str the string to classify + @return {String} the classified string + */ + classify: function(str) { + var parts = str.split("."), + out = []; + + for (var i=0, l=parts.length; i 'InnerHTML' + 'action_name'.capitalize() => 'Action_name' + 'css-class-name'.capitalize() => 'Css-class-name' + 'my favorite items'.capitalize() => 'My favorite items' + + @method capitalize + @param {String} str + @return {String} + */ + capitalize: function(str) { + return str.charAt(0).toUpperCase() + str.substr(1); + } + +}; + +})(); + + + +(function() { +/** +@module ember +@submodule ember-runtime +*/ + + + +var fmt = Ember.String.fmt, + w = Ember.String.w, + loc = Ember.String.loc, + camelize = Ember.String.camelize, + decamelize = Ember.String.decamelize, + dasherize = Ember.String.dasherize, + underscore = Ember.String.underscore, + capitalize = Ember.String.capitalize, + classify = Ember.String.classify; + +if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { + + /** + See {{#crossLink "Ember.String/fmt"}}{{/crossLink}} + + @method fmt + @for String + */ + String.prototype.fmt = function() { + return fmt(this, arguments); + }; + + /** + See {{#crossLink "Ember.String/w"}}{{/crossLink}} + + @method w + @for String + */ + String.prototype.w = function() { + return w(this); + }; + + /** + See {{#crossLink "Ember.String/loc"}}{{/crossLink}} + + @method loc + @for String + */ + String.prototype.loc = function() { + return loc(this, arguments); + }; + + /** + See {{#crossLink "Ember.String/camelize"}}{{/crossLink}} + + @method camelize + @for String + */ + String.prototype.camelize = function() { + return camelize(this); + }; + + /** + See {{#crossLink "Ember.String/decamelize"}}{{/crossLink}} + + @method decamelize + @for String + */ + String.prototype.decamelize = function() { + return decamelize(this); + }; + + /** + See {{#crossLink "Ember.String/dasherize"}}{{/crossLink}} + + @method dasherize + @for String + */ + String.prototype.dasherize = function() { + return dasherize(this); + }; + + /** + See {{#crossLink "Ember.String/underscore"}}{{/crossLink}} + + @method underscore + @for String + */ + String.prototype.underscore = function() { + return underscore(this); + }; + + /** + See {{#crossLink "Ember.String/classify"}}{{/crossLink}} + + @method classify + @for String + */ + String.prototype.classify = function() { + return classify(this); + }; + + /** + See {{#crossLink "Ember.String/capitalize"}}{{/crossLink}} + + @method capitalize + @for String + */ + String.prototype.capitalize = function() { + return capitalize(this); + }; + +} + + +})(); + + + +(function() { +/** +@module ember +@submodule ember-runtime +*/ + +var a_slice = Array.prototype.slice; + +if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Function) { + + /** + The `property` extension of Javascript's Function prototype is available + when `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Function` is + `true`, which is the default. + + Computed properties allow you to treat a function like a property: + + ```javascript + MyApp.president = Ember.Object.create({ + firstName: "Barack", + lastName: "Obama", + + fullName: function() { + return this.get('firstName') + ' ' + this.get('lastName'); + + // Call this flag to mark the function as a property + }.property() + }); + + MyApp.president.get('fullName'); // "Barack Obama" + ``` + + Treating a function like a property is useful because they can work with + bindings, just like any other property. + + Many computed properties have dependencies on other properties. For + example, in the above example, the `fullName` property depends on + `firstName` and `lastName` to determine its value. You can tell Ember + about these dependencies like this: + + ```javascript + MyApp.president = Ember.Object.create({ + firstName: "Barack", + lastName: "Obama", + + fullName: function() { + return this.get('firstName') + ' ' + this.get('lastName'); + + // Tell Ember.js that this computed property depends on firstName + // and lastName + }.property('firstName', 'lastName') + }); + ``` + + Make sure you list these dependencies so Ember knows when to update + bindings that connect to a computed property. Changing a dependency + will not immediately trigger an update of the computed property, but + will instead clear the cache so that it is updated when the next `get` + is called on the property. + + See {{#crossLink "Ember.ComputedProperty"}}{{/crossLink}}, + {{#crossLink "Ember/computed"}}{{/crossLink}} + + @method property + @for Function + */ + Function.prototype.property = function() { + var ret = Ember.computed(this); + return ret.property.apply(ret, arguments); + }; + + /** + The `observes` extension of Javascript's Function prototype is available + when `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Function` is + true, which is the default. + + You can observe property changes simply by adding the `observes` + call to the end of your method declarations in classes that you write. + For example: + + ```javascript + Ember.Object.create({ + valueObserver: function() { + // Executes whenever the "value" property changes + }.observes('value') + }); + ``` + + See {{#crossLink "Ember.Observable/observes"}}{{/crossLink}} + + @method observes + @for Function + */ + Function.prototype.observes = function() { + this.__ember_observes__ = a_slice.call(arguments); + return this; + }; + + /** + The `observesBefore` extension of Javascript's Function prototype is + available when `Ember.EXTEND_PROTOTYPES` or + `Ember.EXTEND_PROTOTYPES.Function` is true, which is the default. + + You can get notified when a property changes is about to happen by + by adding the `observesBefore` call to the end of your method + declarations in classes that you write. For example: + + ```javascript + Ember.Object.create({ + valueObserver: function() { + // Executes whenever the "value" property is about to change + }.observesBefore('value') + }); + ``` + + See {{#crossLink "Ember.Observable/observesBefore"}}{{/crossLink}} + + @method observesBefore + @for Function + */ + Function.prototype.observesBefore = function() { + this.__ember_observesBefore__ = a_slice.call(arguments); + return this; + }; + +} + + +})(); + + + +(function() { + +})(); + + + +(function() { +/** +@module ember +@submodule ember-runtime +*/ + +// .......................................................... +// HELPERS +// + +var get = Ember.get, set = Ember.set; +var a_slice = Array.prototype.slice; +var a_indexOf = Ember.EnumerableUtils.indexOf; + +var contexts = []; + +function popCtx() { + return contexts.length===0 ? {} : contexts.pop(); +} + +function pushCtx(ctx) { + contexts.push(ctx); + return null; +} + +function iter(key, value) { + var valueProvided = arguments.length === 2; + + function i(item) { + var cur = get(item, key); + return valueProvided ? value===cur : !!cur; + } + return i ; +} + +/** + This mixin defines the common interface implemented by enumerable objects + in Ember. Most of these methods follow the standard Array iteration + API defined up to JavaScript 1.8 (excluding language-specific features that + cannot be emulated in older versions of JavaScript). + + This mixin is applied automatically to the Array class on page load, so you + can use any of these methods on simple arrays. If Array already implements + one of these methods, the mixin will not override them. + + ## Writing Your Own Enumerable + + To make your own custom class enumerable, you need two items: + + 1. You must have a length property. This property should change whenever + the number of items in your enumerable object changes. If you using this + with an `Ember.Object` subclass, you should be sure to change the length + property using `set().` + + 2. If you must implement `nextObject().` See documentation. + + Once you have these two methods implement, apply the `Ember.Enumerable` mixin + to your class and you will be able to enumerate the contents of your object + like any other collection. + + ## Using Ember Enumeration with Other Libraries + + Many other libraries provide some kind of iterator or enumeration like + facility. This is often where the most common API conflicts occur. + Ember's API is designed to be as friendly as possible with other + libraries by implementing only methods that mostly correspond to the + JavaScript 1.8 API. + + @class Enumerable + @namespace Ember + @extends Ember.Mixin + @since Ember 0.9 +*/ +Ember.Enumerable = Ember.Mixin.create( + /** @scope Ember.Enumerable.prototype */ { + + // compatibility + isEnumerable: true, + + /** + Implement this method to make your class enumerable. + + This method will be call repeatedly during enumeration. The index value + will always begin with 0 and increment monotonically. You don't have to + rely on the index value to determine what object to return, but you should + always check the value and start from the beginning when you see the + requested index is 0. + + The `previousObject` is the object that was returned from the last call + to `nextObject` for the current iteration. This is a useful way to + manage iteration if you are tracing a linked list, for example. + + Finally the context parameter will always contain a hash you can use as + a "scratchpad" to maintain any other state you need in order to iterate + properly. The context object is reused and is not reset between + iterations so make sure you setup the context with a fresh state whenever + the index parameter is 0. + + Generally iterators will continue to call `nextObject` until the index + reaches the your current length-1. If you run out of data before this + time for some reason, you should simply return undefined. + + The default implementation of this method simply looks up the index. + This works great on any Array-like objects. + + @method nextObject + @param {Number} index the current index of the iteration + @param {Object} previousObject the value returned by the last call to + `nextObject`. + @param {Object} context a context object you can use to maintain state. + @return {Object} the next object in the iteration or undefined + */ + nextObject: Ember.required(Function), + + /** + Helper method returns the first object from a collection. This is usually + used by bindings and other parts of the framework to extract a single + object if the enumerable contains only one item. + + If you override this method, you should implement it so that it will + always return the same value each time it is called. If your enumerable + contains only one object, this method should always return that object. + If your enumerable is empty, this method should return `undefined`. + + ```javascript + var arr = ["a", "b", "c"]; + arr.firstObject(); // "a" + + var arr = []; + arr.firstObject(); // undefined + ``` + + @property firstObject + @return {Object} the object or undefined + */ + firstObject: Ember.computed(function() { + if (get(this, 'length')===0) return undefined ; + + // handle generic enumerables + var context = popCtx(), ret; + ret = this.nextObject(0, null, context); + pushCtx(context); + return ret ; + }).property('[]'), + + /** + Helper method returns the last object from a collection. If your enumerable + contains only one object, this method should always return that object. + If your enumerable is empty, this method should return `undefined`. + + ```javascript + var arr = ["a", "b", "c"]; + arr.lastObject(); // "c" + + var arr = []; + arr.lastObject(); // undefined + ``` + + @property lastObject + @return {Object} the last object or undefined + */ + lastObject: Ember.computed(function() { + var len = get(this, 'length'); + if (len===0) return undefined ; + var context = popCtx(), idx=0, cur, last = null; + do { + last = cur; + cur = this.nextObject(idx++, last, context); + } while (cur !== undefined); + pushCtx(context); + return last; + }).property('[]'), + + /** + Returns `true` if the passed object can be found in the receiver. The + default version will iterate through the enumerable until the object + is found. You may want to override this with a more efficient version. + + ```javascript + var arr = ["a", "b", "c"]; + arr.contains("a"); // true + arr.contains("z"); // false + ``` + + @method contains + @param {Object} obj The object to search for. + @return {Boolean} `true` if object is found in enumerable. + */ + contains: function(obj) { + return this.find(function(item) { return item===obj; }) !== undefined; + }, + + /** + Iterates through the enumerable, calling the passed function on each + item. This method corresponds to the `forEach()` method defined in + JavaScript 1.6. + + The callback method you provide should have the following signature (all + parameters are optional): + + ```javascript + function(item, index, enumerable); + ``` + + - `item` is the current item in the iteration. + - `index` is the current index in the iteration. + - `enumerable` is the enumerable object itself. + + Note that in addition to a callback, you can also pass an optional target + object that will be set as `this` on the context. This is a good way + to give your iterator function access to the current object. + + @method forEach + @param {Function} callback The callback to execute + @param {Object} [target] The target object to use + @return {Object} receiver + */ + forEach: function(callback, target) { + if (typeof callback !== "function") throw new TypeError() ; + var len = get(this, 'length'), last = null, context = popCtx(); + + if (target === undefined) target = null; + + for(var idx=0;idx1) args = a_slice.call(arguments, 1); + + this.forEach(function(x, idx) { + var method = x && x[methodName]; + if ('function' === typeof method) { + ret[idx] = args ? method.apply(x, args) : method.call(x); + } + }, this); + + return ret; + }, + + /** + Simply converts the enumerable into a genuine array. The order is not + guaranteed. Corresponds to the method implemented by Prototype. + + @method toArray + @return {Array} the enumerable as an array. + */ + toArray: function() { + var ret = []; + this.forEach(function(o, idx) { ret[idx] = o; }); + return ret ; + }, + + /** + Returns a copy of the array with all null elements removed. + + ```javascript + var arr = ["a", null, "c", null]; + arr.compact(); // ["a", "c"] + ``` + + @method compact + @return {Array} the array without null elements. + */ + compact: function() { return this.without(null); }, + + /** + Returns a new enumerable that excludes the passed value. The default + implementation returns an array regardless of the receiver type unless + the receiver does not contain the value. + + ```javascript + var arr = ["a", "b", "a", "c"]; + arr.without("a"); // ["b", "c"] + ``` + + @method without + @param {Object} value + @return {Ember.Enumerable} + */ + without: function(value) { + if (!this.contains(value)) return this; // nothing to do + var ret = [] ; + this.forEach(function(k) { + if (k !== value) ret[ret.length] = k; + }) ; + return ret ; + }, + + /** + Returns a new enumerable that contains only unique values. The default + implementation returns an array regardless of the receiver type. + + ```javascript + var arr = ["a", "a", "b", "b"]; + arr.uniq(); // ["a", "b"] + ``` + + @method uniq + @return {Ember.Enumerable} + */ + uniq: function() { + var ret = []; + this.forEach(function(k){ + if (a_indexOf(ret, k)<0) ret.push(k); + }); + return ret; + }, + + /** + This property will trigger anytime the enumerable's content changes. + You can observe this property to be notified of changes to the enumerables + content. + + For plain enumerables, this property is read only. `Ember.Array` overrides + this method. + + @property [] + @type Ember.Array + */ + '[]': Ember.computed(function(key, value) { + return this; + }), + + // .......................................................... + // ENUMERABLE OBSERVERS + // + + /** + Registers an enumerable observer. Must implement `Ember.EnumerableObserver` + mixin. + + @method addEnumerableObserver + @param target {Object} + @param opts {Hash} + */ + addEnumerableObserver: function(target, opts) { + var willChange = (opts && opts.willChange) || 'enumerableWillChange', + didChange = (opts && opts.didChange) || 'enumerableDidChange'; + + var hasObservers = get(this, 'hasEnumerableObservers'); + if (!hasObservers) Ember.propertyWillChange(this, 'hasEnumerableObservers'); + Ember.addListener(this, '@enumerable:before', target, willChange); + Ember.addListener(this, '@enumerable:change', target, didChange); + if (!hasObservers) Ember.propertyDidChange(this, 'hasEnumerableObservers'); + return this; + }, + + /** + Removes a registered enumerable observer. + + @method removeEnumerableObserver + @param target {Object} + @param [opts] {Hash} + */ + removeEnumerableObserver: function(target, opts) { + var willChange = (opts && opts.willChange) || 'enumerableWillChange', + didChange = (opts && opts.didChange) || 'enumerableDidChange'; + + var hasObservers = get(this, 'hasEnumerableObservers'); + if (hasObservers) Ember.propertyWillChange(this, 'hasEnumerableObservers'); + Ember.removeListener(this, '@enumerable:before', target, willChange); + Ember.removeListener(this, '@enumerable:change', target, didChange); + if (hasObservers) Ember.propertyDidChange(this, 'hasEnumerableObservers'); + return this; + }, + + /** + Becomes true whenever the array currently has observers watching changes + on the array. + + @property hasEnumerableObservers + @type Boolean + */ + hasEnumerableObservers: Ember.computed(function() { + return Ember.hasListeners(this, '@enumerable:change') || Ember.hasListeners(this, '@enumerable:before'); + }), + + + /** + Invoke this method just before the contents of your enumerable will + change. You can either omit the parameters completely or pass the objects + to be removed or added if available or just a count. + + @method enumerableContentWillChange + @param {Ember.Enumerable|Number} removing An enumerable of the objects to + be removed or the number of items to be removed. + @param {Ember.Enumerable|Number} adding An enumerable of the objects to be + added or the number of items to be added. + @chainable + */ + enumerableContentWillChange: function(removing, adding) { + + var removeCnt, addCnt, hasDelta; + + if ('number' === typeof removing) removeCnt = removing; + else if (removing) removeCnt = get(removing, 'length'); + else removeCnt = removing = -1; + + if ('number' === typeof adding) addCnt = adding; + else if (adding) addCnt = get(adding,'length'); + else addCnt = adding = -1; + + hasDelta = addCnt<0 || removeCnt<0 || addCnt-removeCnt!==0; + + if (removing === -1) removing = null; + if (adding === -1) adding = null; + + Ember.propertyWillChange(this, '[]'); + if (hasDelta) Ember.propertyWillChange(this, 'length'); + Ember.sendEvent(this, '@enumerable:before', [this, removing, adding]); + + return this; + }, + + /** + Invoke this method when the contents of your enumerable has changed. + This will notify any observers watching for content changes. If your are + implementing an ordered enumerable (such as an array), also pass the + start and end values where the content changed so that it can be used to + notify range observers. + + @method enumerableContentDidChange + @param {Number} [start] optional start offset for the content change. + For unordered enumerables, you should always pass -1. + @param {Ember.Enumerable|Number} removing An enumerable of the objects to + be removed or the number of items to be removed. + @param {Ember.Enumerable|Number} adding An enumerable of the objects to + be added or the number of items to be added. + @chainable + */ + enumerableContentDidChange: function(removing, adding) { + var notify = this.propertyDidChange, removeCnt, addCnt, hasDelta; + + if ('number' === typeof removing) removeCnt = removing; + else if (removing) removeCnt = get(removing, 'length'); + else removeCnt = removing = -1; + + if ('number' === typeof adding) addCnt = adding; + else if (adding) addCnt = get(adding, 'length'); + else addCnt = adding = -1; + + hasDelta = addCnt<0 || removeCnt<0 || addCnt-removeCnt!==0; + + if (removing === -1) removing = null; + if (adding === -1) adding = null; + + Ember.sendEvent(this, '@enumerable:change', [this, removing, adding]); + if (hasDelta) Ember.propertyDidChange(this, 'length'); + Ember.propertyDidChange(this, '[]'); + + return this ; + } + +}) ; + +})(); + + + +(function() { +/** +@module ember +@submodule ember-runtime +*/ + +// .......................................................... +// HELPERS +// + +var get = Ember.get, set = Ember.set, meta = Ember.meta, map = Ember.EnumerableUtils.map, cacheFor = Ember.cacheFor; + +function none(obj) { return obj===null || obj===undefined; } + +// .......................................................... +// ARRAY +// +/** + This module implements Observer-friendly Array-like behavior. This mixin is + picked up by the Array class as well as other controllers, etc. that want to + appear to be arrays. + + Unlike `Ember.Enumerable,` this mixin defines methods specifically for + collections that provide index-ordered access to their contents. When you + are designing code that needs to accept any kind of Array-like object, you + should use these methods instead of Array primitives because these will + properly notify observers of changes to the array. + + Although these methods are efficient, they do add a layer of indirection to + your application so it is a good idea to use them only when you need the + flexibility of using both true JavaScript arrays and "virtual" arrays such + as controllers and collections. + + 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 + `.observes('*myProperty.[]')`. + + To support `Ember.Array` in your own class, you must override two + primitives to use it: `replace()` and `objectAt()`. + + Note that the Ember.Array mixin also incorporates the `Ember.Enumerable` + mixin. All `Ember.Array`-like objects are also enumerable. + + @class Array + @namespace Ember + @extends Ember.Mixin + @uses Ember.Enumerable + @since Ember 0.9.0 +*/ +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. + + @property {Number} length + */ + length: Ember.required(), + + /** + Returns the object at the given `index`. If the given `index` is negative + or is greater or equal than the array length, returns `undefined`. + + This is one of the primitives you must implement to support `Ember.Array`. + If your object supports retrieving the value of an array item using `get()` + (i.e. `myArray.get(0)`), then you do not need to implement this method + yourself. + + ```javascript + var arr = ['a', 'b', 'c', 'd']; + arr.objectAt(0); // "a" + arr.objectAt(3); // "d" + arr.objectAt(-1); // undefined + arr.objectAt(4); // undefined + arr.objectAt(5); // undefined + ``` + + @method objectAt + @param {Number} idx The index of the item to return. + */ + objectAt: function(idx) { + if ((idx < 0) || (idx>=get(this, 'length'))) return undefined ; + return get(this, idx); + }, + + /** + This returns the objects at the specified indexes, using `objectAt`. + + ```javascript + var arr = ['a', 'b', 'c', 'd']; + arr.objectsAt([0, 1, 2]); // ["a", "b", "c"] + arr.objectsAt([2, 3, 4]); // ["c", "d", undefined] + ``` + + @method objectsAt + @param {Array} indexes An array of indexes of items to return. + */ + objectsAt: function(indexes) { + var self = this; + return map(indexes, function(idx){ return self.objectAt(idx); }); + }, + + // overrides Ember.Enumerable version + nextObject: function(idx) { + return this.objectAt(idx); + }, + + /** + This is the handler for the special array content property. If you get + this property, it will return this. If you set this property it a new + array, it will replace the current content. + + This property overrides the default property defined in `Ember.Enumerable`. + + @property [] + */ + '[]': Ember.computed(function(key, value) { + if (value !== undefined) this.replace(0, get(this, 'length'), value) ; + return this ; + }), + + firstObject: Ember.computed(function() { + return this.objectAt(0); + }), + + lastObject: Ember.computed(function() { + return this.objectAt(get(this, 'length')-1); + }), + + // optimized version from Enumerable + contains: function(obj){ + return this.indexOf(obj) >= 0; + }, + + // Add any extra methods to Ember.Array that are native to the built-in Array. + /** + Returns a new array that is a slice of the receiver. This implementation + uses the observable array methods to retrieve the objects for the new + slice. + + ```javascript + var arr = ['red', 'green', 'blue']; + arr.slice(0); // ['red', 'green', 'blue'] + arr.slice(0, 2); // ['red', 'green'] + arr.slice(1, 100); // ['green', 'blue'] + ``` + + @method slice + @param beginIndex {Integer} (Optional) index to begin slicing from. + @param endIndex {Integer} (Optional) index to end the slice at. + @return {Array} New array with specified slice + */ + slice: function(beginIndex, endIndex) { + var ret = []; + var length = get(this, 'length') ; + if (none(beginIndex)) beginIndex = 0 ; + if (none(endIndex) || (endIndex > length)) endIndex = length ; + while(beginIndex < endIndex) { + ret[ret.length] = this.objectAt(beginIndex++) ; + } + return ret ; + }, + + /** + Returns the index of the given object's first occurrence. + If no `startAt` argument is given, the starting location to + search is 0. If it's negative, will count backward from + the end of the array. Returns -1 if no match is found. + + ```javascript + var arr = ["a", "b", "c", "d", "a"]; + arr.indexOf("a"); // 0 + arr.indexOf("z"); // -1 + arr.indexOf("a", 2); // 4 + arr.indexOf("a", -1); // 4 + arr.indexOf("b", 3); // -1 + arr.indexOf("a", 100); // -1 + ```javascript + + @method indexOf + @param {Object} object the item to search for + @param {Number} startAt optional starting location to search, default 0 + @return {Number} index or -1 if not found + */ + indexOf: function(object, startAt) { + var idx, len = get(this, 'length'); + + if (startAt === undefined) startAt = 0; + if (startAt < 0) startAt += len; + + for(idx=startAt;idx= len) startAt = len-1; + if (startAt < 0) startAt += len; + + for(idx=startAt;idx>=0;idx--) { + if (this.objectAt(idx) === object) return idx ; + } + return -1; + }, + + // .......................................................... + // ARRAY OBSERVERS + // + + /** + 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 + called just before the array is modified. + * `arrayDidChange(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. + + 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 + target. + + @method addArrayObserver + @param {Object} target The observer object. + @param {Hash} opts Optional hash of configuration options including + `willChange`, `didChange`, and a `context` option. + @return {Ember.Array} receiver + */ + addArrayObserver: function(target, opts) { + var willChange = (opts && opts.willChange) || 'arrayWillChange', + didChange = (opts && opts.didChange) || 'arrayDidChange'; + + var hasObservers = get(this, 'hasArrayObservers'); + if (!hasObservers) Ember.propertyWillChange(this, 'hasArrayObservers'); + Ember.addListener(this, '@array:before', target, willChange); + Ember.addListener(this, '@array:change', target, didChange); + if (!hasObservers) Ember.propertyDidChange(this, 'hasArrayObservers'); + return this; + }, + + /** + Removes an array observer from the object if the observer is current + registered. Calling this method multiple times with the same object will + have no effect. + + @method removeArrayObserver + @param {Object} target The object observing the array. + @return {Ember.Array} receiver + */ + removeArrayObserver: function(target, opts) { + var willChange = (opts && opts.willChange) || 'arrayWillChange', + didChange = (opts && opts.didChange) || 'arrayDidChange'; + + var hasObservers = get(this, 'hasArrayObservers'); + if (hasObservers) Ember.propertyWillChange(this, 'hasArrayObservers'); + Ember.removeListener(this, '@array:before', target, willChange); + Ember.removeListener(this, '@array:change', target, didChange); + if (hasObservers) Ember.propertyDidChange(this, 'hasArrayObservers'); + return this; + }, + + /** + Becomes true whenever the array currently has observers watching changes + on the array. + + @property Boolean + */ + hasArrayObservers: Ember.computed(function() { + return Ember.hasListeners(this, '@array:change') || Ember.hasListeners(this, '@array:before'); + }), + + /** + If you are implementing an object that supports `Ember.Array`, call this + method just before the array content changes to notify any observers and + invalidate any related properties. Pass the starting index of the change + as well as a delta of the amounts to change. + + @method arrayContentWillChange + @param {Number} startIdx The starting index in the array that will change. + @param {Number} removeAmt The number of items that will be removed. If you + pass `null` assumes 0 + @param {Number} addAmt The number of items that will be added If you + pass `null` assumes 0. + @return {Ember.Array} receiver + */ + arrayContentWillChange: function(startIdx, removeAmt, addAmt) { + + // if no args are passed assume everything changes + if (startIdx===undefined) { + startIdx = 0; + removeAmt = addAmt = -1; + } else { + if (removeAmt === undefined) removeAmt=-1; + if (addAmt === undefined) addAmt=-1; + } + + // Make sure the @each proxy is set up if anyone is observing @each + if (Ember.isWatching(this, '@each')) { get(this, '@each'); } + + Ember.sendEvent(this, '@array:before', [this, startIdx, removeAmt, addAmt]); + + var removing, lim; + if (startIdx>=0 && removeAmt>=0 && get(this, 'hasEnumerableObservers')) { + removing = []; + lim = startIdx+removeAmt; + for(var idx=startIdx;idx=0 && addAmt>=0 && get(this, 'hasEnumerableObservers')) { + adding = []; + lim = startIdx+addAmt; + for(var idx=startIdx;idx "Hello John Doe" - "Hello %@2, %@1".fmt('John', 'Doe') => "Hello Doe, John" + walk like a duck. Indicates that the object can be compared. - @method fmt - @param {Object...} [args] - @return {String} formatted string + @property isComparable + @type Boolean + @default true */ - fmt: function(str, formats) { - // first, replace any ORDERED replacements. - var idx = 0; // the current index for non-numerical replacements - return str.replace(/%@([0-9]+)?/g, function(s, argIndex) { - argIndex = (argIndex) ? parseInt(argIndex,0) - 1 : idx++ ; - s = formats[argIndex]; - return ((s === null) ? '(null)' : (s === undefined) ? '' : s).toString(); - }) ; - }, + isComparable: true, /** - Formats the passed string, but first looks up the string in the localized - strings hash. This is a convenient way to localize text. See - `Ember.String.fmt()` for more information on formatting. - - Note that it is traditional but not required to prefix localized string - keys with an underscore or other character so you can easily identify - localized strings. - - Ember.STRINGS = { - '_Hello World': 'Bonjour le monde', - '_Hello %@ %@': 'Bonjour %@ %@' - }; + Override to return the result of the comparison of the two parameters. The + compare method should return: - Ember.String.loc("_Hello World"); - => 'Bonjour le monde'; + - `-1` if `a < b` + - `0` if `a == b` + - `1` if `a > b` - Ember.String.loc("_Hello %@ %@", ["John", "Smith"]); - => "Bonjour John Smith"; + Default implementation raises an exception. - @method loc - @param {String} str The string to format - @param {Array} formats Optional array of parameters to interpolate into string. - @return {String} formatted string + @method compare + @param a {Object} the first object to compare + @param b {Object} the second object to compare + @return {Integer} the result of the comparison */ - loc: function(str, formats) { - str = Ember.STRINGS[str] || str; - return Ember.String.fmt(str, formats) ; - }, + compare: Ember.required(Function) - /** - Splits a string into separate units separated by spaces, eliminating any - empty strings in the process. This is a convenience method for split that - is mostly useful when applied to the String.prototype. +}); - Ember.String.w("alpha beta gamma").forEach(function(key) { - console.log(key); - }); - > alpha - > beta - > gamma - @method w - @param {String} str The string to split - @return {String} split string - */ - w: function(str) { return str.split(/\s+/); }, +})(); - /** - Converts a camelized string into all lower case separated by underscores. - - 'innerHTML'.decamelize() => 'inner_html' - 'action_name'.decamelize() => 'action_name' - 'css-class-name'.decamelize() => 'css-class-name' - 'my favorite items'.decamelize() => 'my favorite items' - @method decamelize - @param {String} str The string to decamelize. - @return {String} the decamelized string. - */ - decamelize: function(str) { - return str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase(); - }, - /** - Replaces underscores or spaces with dashes. - - 'innerHTML'.dasherize() => 'inner-html' - 'action_name'.dasherize() => 'action-name' - 'css-class-name'.dasherize() => 'css-class-name' - 'my favorite items'.dasherize() => 'my-favorite-items' +(function() { +/** +@module ember +@submodule ember-runtime +*/ - @method dasherize - @param {String} str The string to dasherize. - @return {String} the dasherized string. - */ - dasherize: function(str) { - var cache = STRING_DASHERIZE_CACHE, - ret = cache[str]; - if (ret) { - return ret; - } else { - ret = Ember.String.decamelize(str).replace(STRING_DASHERIZE_REGEXP,'-'); - cache[str] = ret; - } - return ret; - }, +var get = Ember.get, set = Ember.set; - /** - Returns the lowerCaseCamel form of a string. +/** + Implements some standard methods for copying an object. Add this mixin to + any object you create that can create a copy of itself. This mixin is + added automatically to the built-in array. - 'innerHTML'.camelize() => 'innerHTML' - 'action_name'.camelize() => 'actionName' - 'css-class-name'.camelize() => 'cssClassName' - 'my favorite items'.camelize() => 'myFavoriteItems' + You should generally implement the `copy()` method to return a copy of the + receiver. - @method camelize - @param {String} str The string to camelize. - @return {String} the camelized string. - */ - camelize: function(str) { - return str.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) { - return chr ? chr.toUpperCase() : ''; - }); - }, + Note that `frozenCopy()` will only work if you also implement + `Ember.Freezable`. - /** - Returns the UpperCamelCase form of a string. + @class Copyable + @namespace Ember + @extends Ember.Mixin + @since Ember 0.9 +*/ +Ember.Copyable = Ember.Mixin.create( +/** @scope Ember.Copyable.prototype */ { - 'innerHTML'.classify() => 'InnerHTML' - 'action_name'.classify() => 'ActionName' - 'css-class-name'.classify() => 'CssClassName' - 'my favorite items'.classify() => 'MyFavoriteItems' + /** + Override to return a copy of the receiver. Default implementation raises + an exception. - @method classify - @param {String} str the string to classify - @return {String} the classified string + @method copy + @param deep {Boolean} if `true`, a deep copy of the object should be made + @return {Object} copy of receiver */ - classify: function(str) { - var camelized = Ember.String.camelize(str); - return camelized.charAt(0).toUpperCase() + camelized.substr(1); - }, + copy: Ember.required(Function), /** - More general than decamelize. Returns the lower_case_and_underscored - form of a string. + If the object implements `Ember.Freezable`, then this will return a new + copy if the object is not frozen and the receiver if the object is frozen. - 'innerHTML'.underscore() => 'inner_html' - 'action_name'.underscore() => 'action_name' - 'css-class-name'.underscore() => 'css_class_name' - 'my favorite items'.underscore() => 'my_favorite_items' + Raises an exception if you try to call this method on a object that does + not support freezing. - @property underscore - @param {String} str The string to underscore. - @return {String} the underscored string. + You should use this method whenever you want a copy of a freezable object + since a freezable object can simply return itself without actually + consuming more memory. + + @method frozenCopy + @return {Object} copy of receiver or receiver */ - underscore: function(str) { - return str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2'). - replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase(); + frozenCopy: function() { + if (Ember.Freezable && Ember.Freezable.detect(this)) { + return get(this, 'isFrozen') ? this : this.copy().freeze(); + } else { + throw new Error(Ember.String.fmt("%@ does not support freezing", [this])); + } } -}; +}); })(); @@ -5947,89 +8548,93 @@ Ember.String = { */ +var get = Ember.get, set = Ember.set; -var fmt = Ember.String.fmt, - w = Ember.String.w, - loc = Ember.String.loc, - camelize = Ember.String.camelize, - decamelize = Ember.String.decamelize, - dasherize = Ember.String.dasherize, - underscore = Ember.String.underscore; - -if (Ember.EXTEND_PROTOTYPES) { - - /** - See {{#crossLink "Ember.String/fmt"}}{{/crossLink}} +/** + The `Ember.Freezable` mixin implements some basic methods for marking an + object as frozen. Once an object is frozen it should be read only. No changes + may be made the internal state of the object. - @method fmt - @for String - */ - String.prototype.fmt = function() { - return fmt(this, arguments); - }; + ## Enforcement - /** - See {{#crossLink "Ember.String/w"}}{{/crossLink}} + To fully support freezing in your subclass, you must include this mixin and + override any method that might alter any property on the object to instead + raise an exception. You can check the state of an object by checking the + `isFrozen` property. - @method w - @for String - */ - String.prototype.w = function() { - return w(this); - }; + Although future versions of JavaScript may support language-level freezing + object objects, that is not the case today. Even if an object is freezable, + it is still technically possible to modify the object, even though it could + break other parts of your application that do not expect a frozen object to + change. It is, therefore, very important that you always respect the + `isFrozen` property on all freezable objects. - /** - See {{#crossLink "Ember.String/loc"}}{{/crossLink}} + ## Example Usage - @method loc - @for String - */ - String.prototype.loc = function() { - return loc(this, arguments); - }; + The example below shows a simple object that implement the `Ember.Freezable` + protocol. - /** - See {{#crossLink "Ember.String/camelize"}}{{/crossLink}} + ```javascript + Contact = Ember.Object.extend(Ember.Freezable, { + firstName: null, + lastName: null, - @method camelize - @for String - */ - String.prototype.camelize = function() { - return camelize(this); - }; + // swaps the names + swapNames: function() { + if (this.get('isFrozen')) throw Ember.FROZEN_ERROR; + var tmp = this.get('firstName'); + this.set('firstName', this.get('lastName')); + this.set('lastName', tmp); + return this; + } - /** - See {{#crossLink "Ember.String/decamelize"}}{{/crossLink}} + }); - @method decamelize - @for String - */ - String.prototype.decamelize = function() { - return decamelize(this); - }; + c = Context.create({ firstName: "John", lastName: "Doe" }); + c.swapNames(); // returns c + c.freeze(); + c.swapNames(); // EXCEPTION + ``` + + ## Copying + + Usually the `Ember.Freezable` protocol is implemented in cooperation with the + `Ember.Copyable` protocol, which defines a `frozenCopy()` method that will + return a frozen object, if the object implements this method as well. + + @class Freezable + @namespace Ember + @extends Ember.Mixin + @since Ember 0.9 +*/ +Ember.Freezable = Ember.Mixin.create( +/** @scope Ember.Freezable.prototype */ { /** - See {{#crossLink "Ember.String/dasherize"}}{{/crossLink}} + Set to `true` when the object is frozen. Use this property to detect + whether your object is frozen or not. - @method dasherize - @for String + @property isFrozen + @type Boolean */ - String.prototype.dasherize = function() { - return dasherize(this); - }; + isFrozen: false, /** - See {{#crossLink "Ember.String/underscore"}}{{/crossLink}} + Freezes the object. Once this method has been called the object should + no longer allow any properties to be edited. - @method underscore - @for String + @method freeze + @return {Object} receiver */ - String.prototype.underscore = function() { - return underscore(this); - }; + freeze: function() { + if (get(this, 'isFrozen')) return this; + set(this, 'isFrozen', true); + return this; + } -} +}); +Ember.FROZEN_ERROR = "Frozen object cannot be modified."; })(); @@ -6041,122 +8646,113 @@ if (Ember.EXTEND_PROTOTYPES) { @submodule ember-runtime */ -var a_slice = Array.prototype.slice; +var forEach = Ember.EnumerableUtils.forEach; -if (Ember.EXTEND_PROTOTYPES) { +/** + This mixin defines the API for modifying generic enumerables. These methods + can be applied to an object regardless of whether it is ordered or + unordered. - /** - The `property` extension of Javascript's Function prototype is available - when Ember.EXTEND_PROTOTYPES is true, which is the default. + Note that an Enumerable can change even if it does not implement this mixin. + For example, a MappedEnumerable cannot be directly modified but if its + underlying enumerable changes, it will change also. - Computed properties allow you to treat a function like a property: + ## Adding Objects - MyApp.president = Ember.Object.create({ - firstName: "Barack", - lastName: "Obama", + To add an object to an enumerable, use the `addObject()` method. This + method will only add the object to the enumerable if the object is not + already present and the object if of a type supported by the enumerable. - fullName: function() { - return this.get('firstName') + ' ' + this.get('lastName'); + ```javascript + set.addObject(contact); + ``` - // Call this flag to mark the function as a property - }.property() - }); + ## Removing Objects - MyApp.president.get('fullName'); => "Barack Obama" + To remove an object form an enumerable, use the `removeObject()` method. This + will only remove the object if it is already in the enumerable, otherwise + this method has no effect. - Treating a function like a property is useful because they can work with - bindings, just like any other property. + ```javascript + set.removeObject(contact); + ``` - Many computed properties have dependencies on other properties. For - example, in the above example, the `fullName` property depends on - `firstName` and `lastName` to determine its value. You can tell Ember.js - about these dependencies like this: + ## Implementing In Your Own Code - MyApp.president = Ember.Object.create({ - firstName: "Barack", - lastName: "Obama", + If you are implementing an object and want to support this API, just include + this mixin in your class and implement the required methods. In your unit + tests, be sure to apply the Ember.MutableEnumerableTests to your object. - fullName: function() { - return this.get('firstName') + ' ' + this.get('lastName'); + @class MutableEnumerable + @namespace Ember + @extends Ember.Mixin + @uses Ember.Enumerable +*/ +Ember.MutableEnumerable = Ember.Mixin.create(Ember.Enumerable, + /** @scope Ember.MutableEnumerable.prototype */ { - // Tell Ember.js that this computed property depends on firstName - // and lastName - }.property('firstName', 'lastName') - }); + /** + __Required.__ You must implement this method to apply this mixin. - Make sure you list these dependencies so Ember.js knows when to update - bindings that connect to a computed property. Changing a dependency - will not immediately trigger an update of the computed property, but - will instead clear the cache so that it is updated when the next `get` - is called on the property. + Attempts to add the passed object to the receiver if the object is not + already present in the collection. If the object is present, this method + has no effect. - See {{#crossLink "Ember.ComputedProperty"}}{{/crossLink}}, - {{#crossLink "Ember/computed"}}{{/crossLink}} + If the passed object is of a type not supported by the receiver + then this method should raise an exception. - @method property - @for Function + @method addObject + @param {Object} object The object to add to the enumerable. + @return {Object} the passed object */ - Function.prototype.property = function() { - var ret = Ember.computed(this); - return ret.property.apply(ret, arguments); - }; + addObject: Ember.required(Function), /** - The `observes` extension of Javascript's Function prototype is available - when Ember.EXTEND_PROTOTYPES is true, which is the default. - - You can observe property changes simply by adding the `observes` - call to the end of your method declarations in classes that you write. - For example: - - Ember.Object.create({ - valueObserver: function() { - // Executes whenever the "value" property changes - }.observes('value') - }); - - See {{#crossLink "Ember.Observable/observes"}}{{/crossLink}} + Adds each object in the passed enumerable to the receiver. - @method observes - @for Function + @method addObjects + @param {Ember.Enumerable} objects the objects to add. + @return {Object} receiver */ - Function.prototype.observes = function() { - this.__ember_observes__ = a_slice.call(arguments); + addObjects: function(objects) { + Ember.beginPropertyChanges(this); + forEach(objects, function(obj) { this.addObject(obj); }, this); + Ember.endPropertyChanges(this); return this; - }; + }, /** - The `observesBefore` extension of Javascript's Function prototype is - available when Ember.EXTEND_PROTOTYPES is true, which is the default. - - You can get notified when a property changes is about to happen by - by adding the `observesBefore` call to the end of your method - declarations in classes that you write. For example: + __Required.__ You must implement this method to apply this mixin. - Ember.Object.create({ - valueObserver: function() { - // Executes whenever the "value" property is about to change - }.observesBefore('value') - }); + Attempts to remove the passed object from the receiver collection if the + object is in present in the collection. If the object is not present, + this method has no effect. - See {{#crossLink "Ember.Observable/observesBefore"}}{{/crossLink}} + If the passed object is of a type not supported by the receiver + then this method should raise an exception. - @method observesBefore - @for Function + @method removeObject + @param {Object} object The object to remove from the enumerable. + @return {Object} the passed object */ - Function.prototype.observesBefore = function() { - this.__ember_observesBefore__ = a_slice.call(arguments); - return this; - }; - -} - + removeObject: Ember.required(Function), -})(); + /** + Removes each objects in the passed enumerable from the receiver. + @method removeObjects + @param {Ember.Enumerable} objects the objects to remove + @return {Object} receiver + */ + removeObjects: function(objects) { + Ember.beginPropertyChanges(this); + forEach(objects, function(obj) { this.removeObject(obj); }, this); + Ember.endPropertyChanges(this); + return this; + } -(function() { +}); })(); @@ -6167,777 +8763,881 @@ if (Ember.EXTEND_PROTOTYPES) { @module ember @submodule ember-runtime */ - // .......................................................... -// HELPERS +// CONSTANTS // -var get = Ember.get, set = Ember.set; -var a_slice = Array.prototype.slice; -var a_indexOf = Ember.EnumerableUtils.indexOf; - -var contexts = []; - -function popCtx() { - return contexts.length===0 ? {} : contexts.pop(); -} - -function pushCtx(ctx) { - contexts.push(ctx); - return null; -} +var OUT_OF_RANGE_EXCEPTION = "Index out of range" ; +var EMPTY = []; -function iter(key, value) { - var valueProvided = arguments.length === 2; +// .......................................................... +// HELPERS +// - function i(item) { - var cur = get(item, key); - return valueProvided ? value===cur : !!cur; - } - return i ; -} +var get = Ember.get, set = Ember.set, forEach = Ember.EnumerableUtils.forEach; /** - This mixin defines the common interface implemented by enumerable objects - in Ember. Most of these methods follow the standard Array iteration - API defined up to JavaScript 1.8 (excluding language-specific features that - cannot be emulated in older versions of JavaScript). + This mixin defines the API for modifying array-like objects. These methods + can be applied only to a collection that keeps its items in an ordered set. - This mixin is applied automatically to the Array class on page load, so you - can use any of these methods on simple arrays. If Array already implements - one of these methods, the mixin will not override them. + Note that an Array can change even if it does not implement this mixin. + For example, one might implement a SparseArray that cannot be directly + modified, but if its underlying enumerable changes, it will change also. - h3. Writing Your Own Enumerable + @class MutableArray + @namespace Ember + @extends Ember.Mixin + @uses Ember.Array + @uses Ember.MutableEnumerable +*/ +Ember.MutableArray = Ember.Mixin.create(Ember.Array, Ember.MutableEnumerable, + /** @scope Ember.MutableArray.prototype */ { - To make your own custom class enumerable, you need two items: + /** + __Required.__ You must implement this method to apply this mixin. - 1. You must have a length property. This property should change whenever - the number of items in your enumerable object changes. If you using this - with an Ember.Object subclass, you should be sure to change the length - property using set(). + This is one of the primitives you must implement to support `Ember.Array`. + You should replace amt objects started at idx with the objects in the + passed array. You should also call `this.enumerableContentDidChange()` - 2. If you must implement nextObject(). See documentation. + @method replace + @param {Number} idx Starting index in the array to replace. If + idx >= length, then append to the end of the array. + @param {Number} amt Number of elements that should be removed from + the array, starting at *idx*. + @param {Array} objects An array of zero or more objects that should be + inserted into the array at *idx* + */ + replace: Ember.required(), - Once you have these two methods implement, apply the Ember.Enumerable mixin - to your class and you will be able to enumerate the contents of your object - like any other collection. + /** + Remove all elements from self. This is useful if you + want to reuse an existing array without having to recreate it. - h3. Using Ember Enumeration with Other Libraries + ```javascript + var colors = ["red", "green", "blue"]; + color.length(); // 3 + colors.clear(); // [] + colors.length(); // 0 + ``` - Many other libraries provide some kind of iterator or enumeration like - facility. This is often where the most common API conflicts occur. - Ember's API is designed to be as friendly as possible with other - libraries by implementing only methods that mostly correspond to the - JavaScript 1.8 API. + @method clear + @return {Ember.Array} An empty Array. + */ + clear: function () { + var len = get(this, 'length'); + if (len === 0) return this; + this.replace(0, len, EMPTY); + return this; + }, - @class Enumerable - @namespace Ember - @extends Ember.Mixin - @since Ember 0.9 -*/ -Ember.Enumerable = Ember.Mixin.create( - /** @scope Ember.Enumerable.prototype */ { + /** + This will use the primitive `replace()` method to insert an object at the + specified index. - // compatibility - isEnumerable: true, + ```javascript + var colors = ["red", "green", "blue"]; + colors.insertAt(2, "yellow"); // ["red", "green", "yellow", "blue"] + colors.insertAt(5, "orange"); // Error: Index out of range + ```javascript + + @method insertAt + @param {Number} idx index of insert the object at. + @param {Object} object object to insert + */ + insertAt: function(idx, object) { + if (idx > get(this, 'length')) throw new Error(OUT_OF_RANGE_EXCEPTION) ; + this.replace(idx, 0, [object]) ; + return this ; + }, /** - Implement this method to make your class enumerable. + Remove an object at the specified index using the `replace()` primitive + method. You can pass either a single index, or a start and a length. - This method will be call repeatedly during enumeration. The index value - will always begin with 0 and increment monotonically. You don't have to - rely on the index value to determine what object to return, but you should - always check the value and start from the beginning when you see the - requested index is 0. + If you pass a start and length that is beyond the + length this method will throw an `Ember.OUT_OF_RANGE_EXCEPTION` - The previousObject is the object that was returned from the last call - to nextObject for the current iteration. This is a useful way to - manage iteration if you are tracing a linked list, for example. + ```javascript + var colors = ["red", "green", "blue", "yellow", "orange"]; + colors.removeAt(0); // ["green", "blue", "yellow", "orange"] + colors.removeAt(2, 2); // ["green", "blue"] + colors.removeAt(4, 2); // Error: Index out of range + ``` - Finally the context parameter will always contain a hash you can use as - a "scratchpad" to maintain any other state you need in order to iterate - properly. The context object is reused and is not reset between - iterations so make sure you setup the context with a fresh state whenever - the index parameter is 0. + @method removeAt + @param {Number} start index, start of range + @param {Number} len length of passing range + @return {Object} receiver + */ + removeAt: function(start, len) { + if ('number' === typeof start) { - Generally iterators will continue to call nextObject until the index - reaches the your current length-1. If you run out of data before this - time for some reason, you should simply return undefined. + if ((start < 0) || (start >= get(this, 'length'))) { + throw new Error(OUT_OF_RANGE_EXCEPTION); + } - The default implementation of this method simply looks up the index. - This works great on any Array-like objects. + // fast case + if (len === undefined) len = 1; + this.replace(start, len, EMPTY); + } - @method nextObject - @param {Number} index the current index of the iteration - @param {Object} previousObject the value returned by the last call to nextObject. - @param {Object} context a context object you can use to maintain state. - @return {Object} the next object in the iteration or undefined + return this ; + }, + + /** + Push the object onto the end of the array. Works just like `push()` but it + is KVO-compliant. + + ```javascript + var colors = ["red", "green", "blue"]; + colors.pushObject("black"); // ["red", "green", "blue", "black"] + colors.pushObject(["yellow", "orange"]); // ["red", "green", "blue", "black", ["yellow", "orange"]] + ``` + + @method pushObject + @param {anything} obj object to push */ - nextObject: Ember.required(Function), + pushObject: function(obj) { + this.insertAt(get(this, 'length'), obj) ; + return obj ; + }, /** - Helper method returns the first object from a collection. This is usually - used by bindings and other parts of the framework to extract a single - object if the enumerable contains only one item. + Add the objects in the passed numerable to the end of the array. Defers + notifying observers of the change until all objects are added. - If you override this method, you should implement it so that it will - always return the same value each time it is called. If your enumerable - contains only one object, this method should always return that object. - If your enumerable is empty, this method should return undefined. + ```javascript + var colors = ["red", "green", "blue"]; + colors.pushObjects("black"); // ["red", "green", "blue", "black"] + colors.pushObjects(["yellow", "orange"]); // ["red", "green", "blue", "black", "yellow", "orange"] + ``` - var arr = ["a", "b", "c"]; - arr.firstObject(); => "a" + @method pushObjects + @param {Ember.Enumerable} objects the objects to add + @return {Ember.Array} receiver + */ + pushObjects: function(objects) { + this.replace(get(this, 'length'), 0, objects); + return this; + }, - var arr = []; - arr.firstObject(); => undefined + /** + Pop object from array or nil if none are left. Works just like `pop()` but + it is KVO-compliant. - @property firstObject - @return {Object} the object or undefined + ```javascript + var colors = ["red", "green", "blue"]; + colors.popObject(); // "blue" + console.log(colors); // ["red", "green"] + ``` + + @method popObject + @return object */ - firstObject: Ember.computed(function() { - if (get(this, 'length')===0) return undefined ; + popObject: function() { + var len = get(this, 'length') ; + if (len === 0) return null ; - // handle generic enumerables - var context = popCtx(), ret; - ret = this.nextObject(0, null, context); - pushCtx(context); + var ret = this.objectAt(len-1) ; + this.removeAt(len-1, 1) ; return ret ; - }).property('[]').cacheable(), + }, /** - Helper method returns the last object from a collection. If your enumerable - contains only one object, this method should always return that object. - If your enumerable is empty, this method should return undefined. + Shift an object from start of array or nil if none are left. Works just + like `shift()` but it is KVO-compliant. - var arr = ["a", "b", "c"]; - arr.lastObject(); => "c" + ```javascript + var colors = ["red", "green", "blue"]; + colors.shiftObject(); // "red" + console.log(colors); // ["green", "blue"] + ``` - var arr = []; - arr.lastObject(); => undefined + @method shiftObject + @return object + */ + shiftObject: function() { + if (get(this, 'length') === 0) return null ; + var ret = this.objectAt(0) ; + this.removeAt(0) ; + return ret ; + }, - @property lastObject - @return {Object} the last object or undefined + /** + Unshift an object to start of array. Works just like `unshift()` but it is + KVO-compliant. + + ```javascript + var colors = ["red", "green", "blue"]; + colors.unshiftObject("yellow"); // ["yellow", "red", "green", "blue"] + colors.unshiftObject(["black", "white"]); // [["black", "white"], "yellow", "red", "green", "blue"] + ``` + + @method unshiftObject + @param {anything} obj object to unshift */ - lastObject: Ember.computed(function() { - var len = get(this, 'length'); - if (len===0) return undefined ; - var context = popCtx(), idx=0, cur, last = null; - do { - last = cur; - cur = this.nextObject(idx++, last, context); - } while (cur !== undefined); - pushCtx(context); - return last; - }).property('[]').cacheable(), + unshiftObject: function(obj) { + this.insertAt(0, obj) ; + return obj ; + }, /** - Returns true if the passed object can be found in the receiver. The - default version will iterate through the enumerable until the object - is found. You may want to override this with a more efficient version. + Adds the named objects to the beginning of the array. Defers notifying + observers until all objects have been added. - var arr = ["a", "b", "c"]; - arr.contains("a"); => true - arr.contains("z"); => false + ```javascript + var colors = ["red", "green", "blue"]; + colors.unshiftObjects(["black", "white"]); // ["black", "white", "red", "green", "blue"] + colors.unshiftObjects("yellow"); // Type Error: 'undefined' is not a function + ``` - @method contains - @param {Object} obj The object to search for. - @return {Boolean} true if object is found in enumerable. + @method unshiftObjects + @param {Ember.Enumerable} objects the objects to add + @return {Ember.Array} receiver */ - contains: function(obj) { - return this.find(function(item) { return item===obj; }) !== undefined; + unshiftObjects: function(objects) { + this.replace(0, 0, objects); + return this; }, /** - Iterates through the enumerable, calling the passed function on each - item. This method corresponds to the forEach() method defined in - JavaScript 1.6. + Reverse objects in the array. Works just like `reverse()` but it is + KVO-compliant. - The callback method you provide should have the following signature (all - parameters are optional): + @method reverseObjects + @return {Ember.Array} receiver + */ + reverseObjects: function() { + var len = get(this, 'length'); + if (len === 0) return this; + var objects = this.toArray().reverse(); + this.replace(0, len, objects); + return this; + }, - function(item, index, enumerable); + /** + Replace all the the receiver's content with content of the argument. + If argument is an empty array receiver will be cleared. - - *item* is the current item in the iteration. - - *index* is the current index in the iteration - - *enumerable* is the enumerable object itself. + ```javascript + var colors = ["red", "green", "blue"]; + colors.setObjects(["black", "white"]); // ["black", "white"] + colors.setObjects([]); // [] + ``` - Note that in addition to a callback, you can also pass an optional target - object that will be set as "this" on the context. This is a good way - to give your iterator function access to the current object. + @method setObjects + @param {Ember.Array} objects array whose content will be used for replacing + the content of the receiver + @return {Ember.Array} receiver with the new content + */ + setObjects: function(objects) { + if (objects.length === 0) return this.clear(); - @method forEach - @param {Function} callback The callback to execute - @param {Object} [target] The target object to use - @return {Object} receiver - */ - forEach: function(callback, target) { - if (typeof callback !== "function") throw new TypeError() ; - var len = get(this, 'length'), last = null, context = popCtx(); + var len = get(this, 'length'); + this.replace(0, len, objects); + return this; + }, - if (target === undefined) target = null; + // .......................................................... + // IMPLEMENT Ember.MutableEnumerable + // - for(var idx=0;idx= 0) { + var curObject = this.objectAt(loc) ; + if (curObject === obj) this.removeAt(loc) ; } - last = null ; - context = pushCtx(context); return this ; }, - /** - Alias for mapProperty + addObject: function(obj) { + if (!this.contains(obj)) this.pushObject(obj); + return this ; + } - @method getEach - @param {String} key name of the property - @return {Array} The mapped array. - */ - getEach: function(key) { - return this.mapProperty(key); - }, +}); - /** - Sets the value on the named property for each member. This is more - efficient than using other methods defined on this helper. If the object - implements Ember.Observable, the value will be changed to set(), otherwise - it will be set directly. null objects are skipped. - @method setEach - @param {String} key The key to set - @param {Object} value The object to set - @return {Object} receiver - */ - setEach: function(key, value) { - return this.forEach(function(item) { - set(item, key, value); - }); - }, +})(); - /** - Maps all of the items in the enumeration to another value, returning - a new array. This method corresponds to map() defined in JavaScript 1.6. - The callback method you provide should have the following signature (all - parameters are optional): - function(item, index, enumerable); +(function() { +/** +@module ember +@submodule ember-runtime +*/ + +var get = Ember.get, set = Ember.set, defineProperty = Ember.defineProperty; + +/** + ## Overview + + This mixin provides properties and property observing functionality, core + features of the Ember object model. + + Properties and observers allow one object to observe changes to a + property on another object. This is one of the fundamental ways that + models, controllers and views communicate with each other in an Ember + application. + + Any object that has this mixin applied can be used in observer + operations. That includes `Ember.Object` and most objects you will + interact with as you write your Ember application. + + Note that you will not generally apply this mixin to classes yourself, + but you will use the features provided by this module frequently, so it + is important to understand how to use it. + + ## Using `get()` and `set()` + + Because of Ember's support for bindings and observers, you will always + access properties using the get method, and set properties using the + set method. This allows the observing objects to be notified and + computed properties to be handled properly. + + More documentation about `get` and `set` are below. + + ## Observing Property Changes + + You typically observe property changes simply by adding the `observes` + call to the end of your method declarations in classes that you write. + For example: + + ```javascript + Ember.Object.create({ + valueObserver: function() { + // Executes whenever the "value" property changes + }.observes('value') + }); + ``` + + Although this is the most common way to add an observer, this capability + is actually built into the `Ember.Object` class on top of two methods + defined in this mixin: `addObserver` and `removeObserver`. You can use + these two methods to add and remove observers yourself if you need to + do so at runtime. - - *item* is the current item in the iteration. - - *index* is the current index in the iteration - - *enumerable* is the enumerable object itself. + To add an observer for a property, call: - It should return the mapped value. + ```javascript + object.addObserver('propertyKey', targetObject, targetAction) + ``` - Note that in addition to a callback, you can also pass an optional target - object that will be set as "this" on the context. This is a good way - to give your iterator function access to the current object. + This will call the `targetAction` method on the `targetObject` to be called + whenever the value of the `propertyKey` changes. - @method map - @param {Function} callback The callback to execute - @param {Object} [target] The target object to use - @return {Array} The mapped array. - */ - map: function(callback, target) { - var ret = []; - this.forEach(function(x, idx, i) { - ret[idx] = callback.call(target, x, idx,i); - }); - return ret ; - }, + Note that if `propertyKey` is a computed property, the observer will be + called when any of the property dependencies are changed, even if the + resulting value of the computed property is unchanged. This is necessary + because computed properties are not computed until `get` is called. - /** - Similar to map, this specialized function returns the value of the named - property on all items in the enumeration. + @class Observable + @namespace Ember + @extends Ember.Mixin +*/ +Ember.Observable = Ember.Mixin.create(/** @scope Ember.Observable.prototype */ { - @method mapProperty - @param {String} key name of the property - @return {Array} The mapped array. - */ - mapProperty: function(key) { - return this.map(function(next) { - return get(next, key); - }); - }, + // compatibility + isObserverable: true, /** - Returns an array with all of the items in the enumeration that the passed - function returns true for. This method corresponds to filter() defined in - JavaScript 1.6. + Retrieves the value of a property from the object. - The callback method you provide should have the following signature (all - parameters are optional): + This method is usually similar to using `object[keyName]` or `object.keyName`, + however it supports both computed properties and the unknownProperty + handler. - function(item, index, enumerable); + Because `get` unifies the syntax for accessing all these kinds + of properties, it can make many refactorings easier, such as replacing a + simple property with a computed property, or vice versa. - - *item* is the current item in the iteration. - - *index* is the current index in the iteration - - *enumerable* is the enumerable object itself. + ### Computed Properties - It should return the true to include the item in the results, false otherwise. + Computed properties are methods defined with the `property` modifier + declared at the end, such as: - Note that in addition to a callback, you can also pass an optional target - object that will be set as "this" on the context. This is a good way - to give your iterator function access to the current object. + ```javascript + fullName: function() { + return this.getEach('firstName', 'lastName').compact().join(' '); + }.property('firstName', 'lastName') + ``` - @method filter - @param {Function} callback The callback to execute - @param {Object} [target] The target object to use - @return {Array} A filtered array. - */ - filter: function(callback, target) { - var ret = []; - this.forEach(function(x, idx, i) { - if (callback.call(target, x, idx, i)) ret.push(x); - }); - return ret ; - }, + When you call `get` on a computed property, the function will be + called and the return value will be returned instead of the function + itself. - /** - Returns an array with just the items with the matched property. You - can pass an optional second argument with the target value. Otherwise - this will match any property that evaluates to true. + ### Unknown Properties - @method filterProperty - @param {String} key the property to test - @param {String} [value] optional value to test against. - @return {Array} filtered array + Likewise, if you try to call `get` on a property whose value is + `undefined`, the `unknownProperty()` method will be called on the object. + If this method returns any value other than `undefined`, it will be returned + instead. This allows you to implement "virtual" properties that are + not defined upfront. + + @method get + @param {String} key The property to retrieve + @return {Object} The property value or undefined. */ - filterProperty: function(key, value) { - return this.filter(iter.apply(this, arguments)); + get: function(keyName) { + return get(this, keyName); }, /** - Returns the first item in the array for which the callback returns true. - This method works similar to the filter() method defined in JavaScript 1.6 - except that it will stop working on the array once a match is found. - - The callback method you provide should have the following signature (all - parameters are optional): - - function(item, index, enumerable); + To get multiple properties at once, call `getProperties` + with a list of strings or an array: - - *item* is the current item in the iteration. - - *index* is the current index in the iteration - - *enumerable* is the enumerable object itself. + ```javascript + record.getProperties('firstName', 'lastName', 'zipCode'); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } + ``` - It should return the true to include the item in the results, false otherwise. + is equivalent to: - Note that in addition to a callback, you can also pass an optional target - object that will be set as "this" on the context. This is a good way - to give your iterator function access to the current object. + ```javascript + record.getProperties(['firstName', 'lastName', 'zipCode']); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } + ``` - @method find - @param {Function} callback The callback to execute - @param {Object} [target] The target object to use - @return {Object} Found item or null. + @method getProperties + @param {String...|Array} list of keys to get + @return {Hash} */ - find: function(callback, target) { - var len = get(this, 'length') ; - if (target === undefined) target = null; - - var last = null, next, found = false, ret ; - var context = popCtx(); - for(var idx=0;idx1) args = a_slice.call(arguments, 1); + ```javascript + fooDidChange: function(sender, key, value, context, rev) { }; + ``` - this.forEach(function(x, idx) { - var method = x && x[methodName]; - if ('function' === typeof method) { - ret[idx] = args ? method.apply(x, args) : method.call(x); - } - }, this); + Usually you will not need the value, context or revision parameters at + the end. In this case, it is common to write observer methods that take + only a sender and key value as parameters or, if you aren't interested in + any of these values, to write an observer that has no parameters at all. - return ret; + @method addObserver + @param {String} key The key to observer + @param {Object} target The target object to invoke + @param {String|Function} method The method to invoke. + @return {Ember.Object} self + */ + addObserver: function(key, target, method) { + Ember.addObserver(this, key, target, method); }, /** - Simply converts the enumerable into a genuine array. The order is not - guaranteed. Corresponds to the method implemented by Prototype. + Remove an observer you have previously registered on this object. Pass + the same key, target, and method you passed to `addObserver()` and your + target will no longer receive notifications. - @method toArray - @return {Array} the enumerable as an array. + @method removeObserver + @param {String} key The key to observer + @param {Object} target The target object to invoke + @param {String|Function} method The method to invoke. + @return {Ember.Observable} receiver */ - toArray: function() { - var ret = []; - this.forEach(function(o, idx) { ret[idx] = o; }); - return ret ; + removeObserver: function(key, target, method) { + Ember.removeObserver(this, key, target, method); }, /** - Returns a copy of the array with all null elements removed. - - var arr = ["a", null, "c", null]; - arr.compact(); => ["a", "c"] + Returns `true` if the object currently has observers registered for a + particular key. You can use this method to potentially defer performing + an expensive action until someone begins observing a particular property + on the object. - @method compact - @return {Array} the array without null elements. + @method hasObserverFor + @param {String} key Key to check + @return {Boolean} */ - compact: function() { return this.without(null); }, + hasObserverFor: function(key) { + return Ember.hasListeners(this, key+':change'); + }, /** - Returns a new enumerable that excludes the passed value. The default - implementation returns an array regardless of the receiver type unless - the receiver does not contain the value. - - var arr = ["a", "b", "a", "c"]; - arr.without("a"); => ["b", "c"] - - @method without - @param {Object} value - @return {Ember.Enumerable} + @deprecated + @method getPath + @param {String} path The property path to retrieve + @return {Object} The property value or undefined. */ - without: function(value) { - if (!this.contains(value)) return this; // nothing to do - var ret = [] ; - this.forEach(function(k) { - if (k !== value) ret[ret.length] = k; - }) ; - return ret ; + getPath: function(path) { + Ember.deprecate("getPath is deprecated since get now supports paths"); + return this.get(path); }, /** - Returns a new enumerable that contains only unique values. The default - implementation returns an array regardless of the receiver type. - - var arr = ["a", "a", "b", "b"]; - arr.uniq(); => ["a", "b"] - - @method uniq - @return {Ember.Enumerable} + @deprecated + @method setPath + @param {String} path The path to the property that will be set + @param {Object} value The value to set or `null`. + @return {Ember.Observable} */ - uniq: function() { - var ret = []; - this.forEach(function(k){ - if (a_indexOf(ret, k)<0) ret.push(k); - }); - return ret; + setPath: function(path, value) { + Ember.deprecate("setPath is deprecated since set now supports paths"); + return this.set(path, value); }, /** - This property will trigger anytime the enumerable's content changes. - You can observe this property to be notified of changes to the enumerables - content. + Retrieves the value of a property, or a default value in the case that the + property returns `undefined`. - For plain enumerables, this property is read only. Ember.Array overrides - this method. + ```javascript + person.getWithDefault('lastName', 'Doe'); + ``` - @property [] - @type Ember.Array + @method getWithDefault + @param {String} keyName The name of the property to retrieve + @param {Object} defaultValue The value to return if the property value is undefined + @return {Object} The property value or the defaultValue. */ - '[]': Ember.computed(function(key, value) { - return this; - }).property().cacheable(), - - // .......................................................... - // ENUMERABLE OBSERVERS - // + getWithDefault: function(keyName, defaultValue) { + return Ember.getWithDefault(this, keyName, defaultValue); + }, /** - Registers an enumerable observer. Must implement Ember.EnumerableObserver - mixin. + Set the value of a property to the current value plus some amount. - @method addEnumerableObserver - @param target {Object} - @param opts {Hash} - */ - addEnumerableObserver: function(target, opts) { - var willChange = (opts && opts.willChange) || 'enumerableWillChange', - didChange = (opts && opts.didChange) || 'enumerableDidChange'; + ```javascript + person.incrementProperty('age'); + team.incrementProperty('score', 2); + ``` - var hasObservers = get(this, 'hasEnumerableObservers'); - if (!hasObservers) Ember.propertyWillChange(this, 'hasEnumerableObservers'); - Ember.addListener(this, '@enumerable:before', target, willChange); - Ember.addListener(this, '@enumerable:change', target, didChange); - if (!hasObservers) Ember.propertyDidChange(this, 'hasEnumerableObservers'); - return this; + @method incrementProperty + @param {String} keyName The name of the property to increment + @param {Object} increment The amount to increment by. Defaults to 1 + @return {Object} The new property value + */ + incrementProperty: function(keyName, increment) { + if (!increment) { increment = 1; } + set(this, keyName, (get(this, keyName) || 0)+increment); + return get(this, keyName); }, /** - Removes a registered enumerable observer. + Set the value of a property to the current value minus some amount. - @method removeEnumerableObserver - @param target {Object} - @param [opts] {Hash} - */ - removeEnumerableObserver: function(target, opts) { - var willChange = (opts && opts.willChange) || 'enumerableWillChange', - didChange = (opts && opts.didChange) || 'enumerableDidChange'; + ```javascript + player.decrementProperty('lives'); + orc.decrementProperty('health', 5); + ``` - var hasObservers = get(this, 'hasEnumerableObservers'); - if (hasObservers) Ember.propertyWillChange(this, 'hasEnumerableObservers'); - Ember.removeListener(this, '@enumerable:before', target, willChange); - Ember.removeListener(this, '@enumerable:change', target, didChange); - if (hasObservers) Ember.propertyDidChange(this, 'hasEnumerableObservers'); - return this; + @method decrementProperty + @param {String} keyName The name of the property to decrement + @param {Object} increment The amount to decrement by. Defaults to 1 + @return {Object} The new property value + */ + decrementProperty: function(keyName, increment) { + if (!increment) { increment = 1; } + set(this, keyName, (get(this, keyName) || 0)-increment); + return get(this, keyName); }, /** - Becomes true whenever the array currently has observers watching changes - on the array. + Set the value of a boolean property to the opposite of it's + current value. - @property hasEnumerableObservers - @type Boolean - */ - hasEnumerableObservers: Ember.computed(function() { - return Ember.hasListeners(this, '@enumerable:change') || Ember.hasListeners(this, '@enumerable:before'); - }).property().cacheable(), + ```javascript + starship.toggleProperty('warpDriveEnaged'); + ``` + @method toggleProperty + @param {String} keyName The name of the property to toggle + @return {Object} The new property value + */ + toggleProperty: function(keyName) { + set(this, keyName, !get(this, keyName)); + return get(this, keyName); + }, /** - Invoke this method just before the contents of your enumerable will - change. You can either omit the parameters completely or pass the objects - to be removed or added if available or just a count. + Returns the cached value of a computed property, if it exists. + This allows you to inspect the value of a computed property + without accidentally invoking it if it is intended to be + generated lazily. - @method enumerableContentWillChange - @param {Ember.Enumerable|Number} removing An enumerable of the objects to - be removed or the number of items to be removed. - @param {Ember.Enumerable|Number} adding An enumerable of the objects to be - added or the number of items to be added. - @chainable + @method cacheFor + @param {String} keyName + @return {Object} The cached value of the computed property, if any */ - enumerableContentWillChange: function(removing, adding) { - - var removeCnt, addCnt, hasDelta; + cacheFor: function(keyName) { + return Ember.cacheFor(this, keyName); + }, - if ('number' === typeof removing) removeCnt = removing; - else if (removing) removeCnt = get(removing, 'length'); - else removeCnt = removing = -1; + // intended for debugging purposes + observersForKey: function(keyName) { + return Ember.observersFor(this, keyName); + } +}); - if ('number' === typeof adding) addCnt = adding; - else if (adding) addCnt = get(adding,'length'); - else addCnt = adding = -1; - hasDelta = addCnt<0 || removeCnt<0 || addCnt-removeCnt!==0; +})(); - if (removing === -1) removing = null; - if (adding === -1) adding = null; - Ember.propertyWillChange(this, '[]'); - if (hasDelta) Ember.propertyWillChange(this, 'length'); - Ember.sendEvent(this, '@enumerable:before', [this, removing, adding]); - return this; - }, +(function() { +/** +@module ember +@submodule ember-runtime +*/ - /** - Invoke this method when the contents of your enumerable has changed. - This will notify any observers watching for content changes. If your are - implementing an ordered enumerable (such as an array), also pass the - start and end values where the content changed so that it can be used to - notify range observers. +var get = Ember.get, set = Ember.set; - @method enumerableContentDidChange - @param {Number} [start] optional start offset for the content change. - For unordered enumerables, you should always pass -1. - @param {Ember.Enumerable|Number} removing An enumerable of the objects to - be removed or the number of items to be removed. - @param {Ember.Enumerable|Number} adding An enumerable of the objects to - be added or the number of items to be added. - @chainable - */ - enumerableContentDidChange: function(removing, adding) { - var notify = this.propertyDidChange, removeCnt, addCnt, hasDelta; +/** +@class TargetActionSupport +@namespace Ember +@extends Ember.Mixin +*/ +Ember.TargetActionSupport = Ember.Mixin.create({ + target: null, + action: null, - if ('number' === typeof removing) removeCnt = removing; - else if (removing) removeCnt = get(removing, 'length'); - else removeCnt = removing = -1; + targetObject: Ember.computed(function() { + var target = get(this, 'target'); - if ('number' === typeof adding) addCnt = adding; - else if (adding) addCnt = get(adding, 'length'); - else addCnt = adding = -1; + if (Ember.typeOf(target) === "string") { + var value = get(this, target); + if (value === undefined) { value = get(Ember.lookup, target); } + return value; + } else { + return target; + } + }).property('target'), - hasDelta = addCnt<0 || removeCnt<0 || addCnt-removeCnt!==0; + triggerAction: function() { + var action = get(this, 'action'), + target = get(this, 'targetObject'); - if (removing === -1) removing = null; - if (adding === -1) adding = null; + if (target && action) { + var ret; - Ember.sendEvent(this, '@enumerable:change', [this, removing, adding]); - if (hasDelta) Ember.propertyDidChange(this, 'length'); - Ember.propertyDidChange(this, '[]'); + if (typeof target.send === 'function') { + ret = target.send(action, this); + } else { + if (typeof action === 'string') { + action = target[action]; + } + ret = action.call(target, this); + } + if (ret !== false) ret = true; - return this ; + return ret; + } else { + return false; + } } - -}) ; - - - +}); })(); @@ -6949,614 +9649,689 @@ Ember.Enumerable = Ember.Mixin.create( @submodule ember-runtime */ -// .......................................................... -// HELPERS -// - -var get = Ember.get, set = Ember.set, meta = Ember.meta, map = Ember.EnumerableUtils.map, cacheFor = Ember.cacheFor; - -function none(obj) { return obj===null || obj===undefined; } - -// .......................................................... -// ARRAY -// /** - This module implements Observer-friendly Array-like behavior. This mixin is - picked up by the Array class as well as other controllers, etc. that want to - appear to be arrays. + This mixin allows for Ember objects to subscribe to and emit events. - Unlike Ember.Enumerable, this mixin defines methods specifically for - collections that provide index-ordered access to their contents. When you - are designing code that needs to accept any kind of Array-like object, you - should use these methods instead of Array primitives because these will - properly notify observers of changes to the array. + ```javascript + App.Person = Ember.Object.extend(Ember.Evented, { + greet: function() { + // ... + this.trigger('greet'); + } + }); - Although these methods are efficient, they do add a layer of indirection to - your application so it is a good idea to use them only when you need the - flexibility of using both true JavaScript arrays and "virtual" arrays such - as controllers and collections. + var person = App.Person.create(); - 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 - .observes('*myProperty.[]') . + person.on('greet', function() { + console.log('Our person has greeted'); + }); - To support Ember.Array in your own class, you must override two - primitives to use it: replace() and objectAt(). + person.greet(); - Note that the Ember.Array mixin also incorporates the Ember.Enumerable mixin. All - Ember.Array-like objects are also enumerable. + // outputs: 'Our person has greeted' + ``` - @class Array + @class Evented @namespace Ember @extends Ember.Mixin - @uses Ember.Enumerable - @since Ember 0.9.0 -*/ -Ember.Array = Ember.Mixin.create(Ember.Enumerable, /** @scope Ember.Array.prototype */ { - - // compatibility - isSCArray: true, + */ +Ember.Evented = Ember.Mixin.create({ /** - Your array must support the length property. Your replace methods should - set this property whenever it changes. + Subscribes to a named event with given function. - @property {Number} length + ```javascript + person.on('didLoad', function() { + // fired once the person has loaded + }); + ``` + + An optional target can be passed in as the 2nd argument that will + be set as the "this" for the callback. This is a good way to give your + function access to the object triggering the event. When the target + parameter is used the callback becomes the third argument. + + @method on + @param {String} name The name of the event + @param {Object} [target] The "this" binding for the callback + @param {Function} method The callback to execute */ - length: Ember.required(), + on: function(name, target, method) { + Ember.addListener(this, name, target, method); + }, /** - Returns the object at the given index. If the given index is negative or - is greater or equal than the array length, returns `undefined`. - - This is one of the primitives you must implement to support `Ember.Array`. - If your object supports retrieving the value of an array item using `get()` - (i.e. `myArray.get(0)`), then you do not need to implement this method - yourself. + Subscribes a function to a named event and then cancels the subscription + after the first time the event is triggered. It is good to use ``one`` when + you only care about the first time an event has taken place. - var arr = ['a', 'b', 'c', 'd']; - arr.objectAt(0); => "a" - arr.objectAt(3); => "d" - arr.objectAt(-1); => undefined - arr.objectAt(4); => undefined - arr.objectAt(5); => undefined + This function takes an optional 2nd argument that will become the "this" + value for the callback. If this argument is passed then the 3rd argument + becomes the function. - @method objectAt - @param {Number} idx - The index of the item to return. + @method one + @param {String} name The name of the event + @param {Object} [target] The "this" binding for the callback + @param {Function} method The callback to execute */ - objectAt: function(idx) { - if ((idx < 0) || (idx>=get(this, 'length'))) return undefined ; - return get(this, idx); + one: function(name, target, method) { + if (!method) { + method = target; + target = null; + } + + Ember.addListener(this, name, target, method, true); }, /** - This returns the objects at the specified indexes, using `objectAt`. + Triggers a named event for the object. Any additional arguments + will be passed as parameters to the functions that are subscribed to the + event. - var arr = ['a', 'b', 'c', 'd']; - arr.objectsAt([0, 1, 2]) => ["a", "b", "c"] - arr.objectsAt([2, 3, 4]) => ["c", "d", undefined] + ```javascript + person.on('didEat', food) { + console.log('person ate some ' + food); + }); - @method objectsAt - @param {Array} indexes - An array of indexes of items to return. - */ - objectsAt: function(indexes) { - var self = this; - return map(indexes, function(idx){ return self.objectAt(idx); }); + person.trigger('didEat', 'broccoli'); + + // outputs: person ate some broccoli + ``` + @method trigger + @param {String} name The name of the event + @param {Object...} args Optional arguments to pass on + */ + trigger: function(name) { + var args = [], i, l; + for (i = 1, l = arguments.length; i < l; i++) { + args.push(arguments[i]); + } + Ember.sendEvent(this, name, args); }, - // overrides Ember.Enumerable version - nextObject: function(idx) { - return this.objectAt(idx); + fire: function(name) { + Ember.deprecate("Ember.Evented#fire() has been deprecated in favor of trigger() for compatibility with jQuery. It will be removed in 1.0. Please update your code to call trigger() instead."); + this.trigger.apply(this, arguments); }, /** - This is the handler for the special array content property. If you get - this property, it will return this. If you set this property it a new - array, it will replace the current content. - - This property overrides the default property defined in Ember.Enumerable. + Cancels subscription for give name, target, and method. - @property [] + @method off + @param {String} name The name of the event + @param {Object} target The target of the subscription + @param {Function} method The function of the subscription */ - '[]': Ember.computed(function(key, value) { - if (value !== undefined) this.replace(0, get(this, 'length'), value) ; - return this ; - }).property().cacheable(), + off: function(name, target, method) { + Ember.removeListener(this, name, target, method); + }, + + /** + Checks to see if object has any subscriptions for named event. + + @method has + @param {String} name The name of the event + @return {Boolean} does the object have a subscription for event + */ + has: function(name) { + return Ember.hasListeners(this, name); + } +}); + +})(); + + + +(function() { +var RSVP = requireModule("rsvp"); + +RSVP.async = function(callback, binding) { + Ember.run.schedule('actions', binding, callback); +}; + +/** +@module ember +@submodule ember-runtime +*/ - firstObject: Ember.computed(function() { - return this.objectAt(0); - }).property().cacheable(), +var get = Ember.get, + slice = Array.prototype.slice; - lastObject: Ember.computed(function() { - return this.objectAt(get(this, 'length')-1); - }).property().cacheable(), +/** + @class Deferred + @namespace Ember + @extends Ember.Mixin + */ +Ember.DeferredMixin = Ember.Mixin.create({ + /** + Add handlers to be called when the Deferred object is resolved or rejected. - // optimized version from Enumerable - contains: function(obj){ - return this.indexOf(obj) >= 0; + @method then + @param {Function} doneCallback a callback function to be called when done + @param {Function} failCallback a callback function to be called when failed + */ + then: function(doneCallback, failCallback) { + var promise = get(this, 'promise'); + return promise.then.apply(promise, arguments); }, - // Add any extra methods to Ember.Array that are native to the built-in Array. /** - Returns a new array that is a slice of the receiver. This implementation - uses the observable array methods to retrieve the objects for the new - slice. - - var arr = ['red', 'green', 'blue']; - arr.slice(0); => ['red', 'green', 'blue'] - arr.slice(0, 2); => ['red', 'green'] - arr.slice(1, 100); => ['green', 'blue'] + Resolve a Deferred object and call any `doneCallbacks` with the given args. - @method slice - @param beginIndex {Integer} (Optional) index to begin slicing from. - @param endIndex {Integer} (Optional) index to end the slice at. - @return {Array} New array with specified slice + @method resolve */ - slice: function(beginIndex, endIndex) { - var ret = []; - var length = get(this, 'length') ; - if (none(beginIndex)) beginIndex = 0 ; - if (none(endIndex) || (endIndex > length)) endIndex = length ; - while(beginIndex < endIndex) { - ret[ret.length] = this.objectAt(beginIndex++) ; - } - return ret ; + resolve: function(value) { + get(this, 'promise').resolve(value); }, /** - Returns the index of the given object's first occurrence. - If no startAt argument is given, the starting location to - search is 0. If it's negative, will count backward from - the end of the array. Returns -1 if no match is found. + Reject a Deferred object and call any `failCallbacks` with the given args. - var arr = ["a", "b", "c", "d", "a"]; - arr.indexOf("a"); => 0 - arr.indexOf("z"); => -1 - arr.indexOf("a", 2); => 4 - arr.indexOf("a", -1); => 4 - arr.indexOf("b", 3); => -1 - arr.indexOf("a", 100); => -1 - - @method indexOf - @param {Object} object the item to search for - @param {Number} startAt optional starting location to search, default 0 - @return {Number} index or -1 if not found + @method reject */ - indexOf: function(object, startAt) { - var idx, len = get(this, 'length'); + reject: function(value) { + get(this, 'promise').reject(value); + }, - if (startAt === undefined) startAt = 0; - if (startAt < 0) startAt += len; + promise: Ember.computed(function() { + return new RSVP.Promise(); + }) +}); - for(idx=startAt;idx 4 - arr.lastIndexOf("z"); => -1 - arr.lastIndexOf("a", 2); => 0 - arr.lastIndexOf("a", -1); => 4 - arr.lastIndexOf("b", 3); => 1 - arr.lastIndexOf("a", 100); => 4 - @method lastIndexOf - @param {Object} object the item to search for - @param {Number} startAt optional starting location to search, default 0 - @return {Number} index or -1 if not found - */ - lastIndexOf: function(object, startAt) { - var idx, len = get(this, 'length'); - if (startAt === undefined || startAt >= len) startAt = len-1; - if (startAt < 0) startAt += len; +(function() { - for(idx=startAt;idx>=0;idx--) { - if (this.objectAt(idx) === object) return idx ; - } - return -1; - }, +})(); - // .......................................................... - // ARRAY OBSERVERS - // - /** - 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 - called just before the array is modified. - * `arrayDidChange(start, removeCount, addCount)` - This method will be - called just after the array is modified. +(function() { +Ember.Container = requireModule('container'); +Ember.Container.set = Ember.set; - 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. +})(); - 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 - target. - @method addArrayObserver - @param {Object} target The observer object. - @param {Hash} opts Optional hash of configuration options including - willChange, didChange, and a context option. - @return {Ember.Array} receiver - */ - addArrayObserver: function(target, opts) { - var willChange = (opts && opts.willChange) || 'arrayWillChange', - didChange = (opts && opts.didChange) || 'arrayDidChange'; - var hasObservers = get(this, 'hasArrayObservers'); - if (!hasObservers) Ember.propertyWillChange(this, 'hasArrayObservers'); - Ember.addListener(this, '@array:before', target, willChange); - Ember.addListener(this, '@array:change', target, didChange); - if (!hasObservers) Ember.propertyDidChange(this, 'hasArrayObservers'); - return this; - }, +(function() { +/** +@module ember +@submodule ember-runtime +*/ - /** - Removes an array observer from the object if the observer is current - registered. Calling this method multiple times with the same object will - have no effect. - @method removeArrayObserver - @param {Object} target The object observing the array. - @return {Ember.Array} receiver - */ - removeArrayObserver: function(target, opts) { - var willChange = (opts && opts.willChange) || 'arrayWillChange', - didChange = (opts && opts.didChange) || 'arrayDidChange'; +// NOTE: this object should never be included directly. Instead use Ember. +// Ember.Object. We only define this separately so that Ember.Set can depend on it - var hasObservers = get(this, 'hasArrayObservers'); - if (hasObservers) Ember.propertyWillChange(this, 'hasArrayObservers'); - Ember.removeListener(this, '@array:before', target, willChange); - Ember.removeListener(this, '@array:change', target, didChange); - if (hasObservers) Ember.propertyDidChange(this, 'hasArrayObservers'); - return this; - }, - /** - Becomes true whenever the array currently has observers watching changes - on the array. +var set = Ember.set, get = Ember.get, + o_create = Ember.create, + o_defineProperty = Ember.platform.defineProperty, + a_slice = Array.prototype.slice, + GUID_KEY = Ember.GUID_KEY, + guidFor = Ember.guidFor, + generateGuid = Ember.generateGuid, + meta = Ember.meta, + rewatch = Ember.rewatch, + finishChains = Ember.finishChains, + destroy = Ember.destroy, + schedule = Ember.run.schedule, + Mixin = Ember.Mixin, + applyMixin = Mixin._apply, + finishPartial = Mixin.finishPartial, + reopen = Mixin.prototype.reopen, + MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER, + indexOf = Ember.EnumerableUtils.indexOf; - @property Boolean - */ - hasArrayObservers: Ember.computed(function() { - return Ember.hasListeners(this, '@array:change') || Ember.hasListeners(this, '@array:before'); - }).property().cacheable(), +var undefinedDescriptor = { + configurable: true, + writable: true, + enumerable: false, + value: undefined +}; - /** - If you are implementing an object that supports Ember.Array, call this - method just before the array content changes to notify any observers and - invalidate any related properties. Pass the starting index of the change - as well as a delta of the amounts to change. +function makeCtor() { - @method arrayContentWillChange - @param {Number} startIdx The starting index in the array that will change. - @param {Number} removeAmt The number of items that will be removed. If you pass null assumes 0 - @param {Number} addAmt The number of items that will be added. If you pass null assumes 0. - @return {Ember.Array} receiver - */ - arrayContentWillChange: function(startIdx, removeAmt, addAmt) { + // Note: avoid accessing any properties on the object since it makes the + // method a lot faster. This is glue code so we want it to be as fast as + // possible. - // if no args are passed assume everything changes - if (startIdx===undefined) { - startIdx = 0; - removeAmt = addAmt = -1; - } else { - if (removeAmt === undefined) removeAmt=-1; - if (addAmt === undefined) addAmt=-1; + var wasApplied = false, initMixins, initProperties; + + var Class = function() { + if (!wasApplied) { + Class.proto(); // prepare prototype... + } + o_defineProperty(this, GUID_KEY, undefinedDescriptor); + o_defineProperty(this, '_super', undefinedDescriptor); + var m = meta(this); + m.proto = this; + if (initMixins) { + // capture locally so we can clear the closed over variable + var mixins = initMixins; + initMixins = null; + this.reopen.apply(this, mixins); } + if (initProperties) { + // capture locally so we can clear the closed over variable + var props = initProperties; + initProperties = null; - // Make sure the @each proxy is set up if anyone is observing @each - if (Ember.isWatching(this, '@each')) { get(this, '@each'); } + var concatenatedProperties = this.concatenatedProperties; - Ember.sendEvent(this, '@array:before', [this, startIdx, removeAmt, addAmt]); + for (var i = 0, l = props.length; i < l; i++) { + var properties = props[i]; + for (var keyName in properties) { + if (!properties.hasOwnProperty(keyName)) { continue; } - var removing, lim; - if (startIdx>=0 && removeAmt>=0 && get(this, 'hasEnumerableObservers')) { - removing = []; - lim = startIdx+removeAmt; - for(var idx=startIdx;idx= 0) { + var baseValue = this[keyName]; + + if (baseValue) { + if ('function' === typeof baseValue.concat) { + value = baseValue.concat(value); + } else { + value = Ember.makeArray(baseValue).concat(value); + } + } else { + value = Ember.makeArray(value); + } + } + + if (desc) { + desc.set(this, keyName, value); + } else { + if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) { + this.setUnknownProperty(keyName, value); + } else if (MANDATORY_SETTER) { + Ember.defineProperty(this, keyName, null, value); // setup mandatory setter + } else { + this[keyName] = value; + } + } + } + } + } + finishPartial(this, m); + delete m.proto; + finishChains(this); + this.init.apply(this, arguments); + }; + + Class.toString = Mixin.prototype.toString; + Class.willReopen = function() { + if (wasApplied) { + Class.PrototypeMixin = Mixin.create(Class.PrototypeMixin); } - var adding, lim; - if (startIdx>=0 && addAmt>=0 && get(this, 'hasEnumerableObservers')) { - adding = []; - lim = startIdx+addAmt; - for(var idx=startIdx;idx b` + If you try to set a property on a destroyed object, an exception will be + raised. - Default implementation raises an exception. + Note that destruction is scheduled for the end of the run loop and does not + happen immediately. - @method compare - @param a {Object} the first object to compare - @param b {Object} the second object to compare - @return {Integer} the result of the comparison + @method destroy + @return {Ember.Object} receiver */ - compare: Ember.required(Function) + destroy: function() { + if (this.isDestroying) { return; } -}); + this.isDestroying = true; + if (this.willDestroy) { this.willDestroy(); } -})(); + schedule('destroy', this, this._scheduledDestroy); + return this; + }, + /** + @private + Invoked by the run loop to actually destroy the object. This is + scheduled for execution by the `destroy` method. -(function() { -/** -@module ember -@submodule ember-runtime -*/ + @method _scheduledDestroy + */ + _scheduledDestroy: function() { + destroy(this); + set(this, 'isDestroyed', true); + if (this.didDestroy) { this.didDestroy(); } + }, + bind: function(to, from) { + if (!(from instanceof Ember.Binding)) { from = Ember.Binding.from(from); } + from.to(to).connect(this); + return from; + }, -var get = Ember.get, set = Ember.set; + /** + Returns a string representation which attempts to provide more information + than Javascript's `toString` typically does, in a generic way for all Ember + objects. -/** - Implements some standard methods for copying an object. Add this mixin to - any object you create that can create a copy of itself. This mixin is - added automatically to the built-in array. + App.Person = Em.Object.extend() + person = App.Person.create() + person.toString() //=> "" - You should generally implement the copy() method to return a copy of the - receiver. + If the object's class is not defined on an Ember namespace, it will + indicate it is a subclass of the registered superclass: - Note that frozenCopy() will only work if you also implement Ember.Freezable. + Student = App.Person.extend() + student = Student.create() + student.toString() //=> "<(subclass of App.Person):ember1025>" - @class Copyable - @namespace Ember - @extends Ember.Mixin - @since Ember 0.9 -*/ -Ember.Copyable = Ember.Mixin.create( -/** @scope Ember.Copyable.prototype */ { + If the method `toStringExtension` is defined, its return value will be + included in the output. - /** - Override to return a copy of the receiver. Default implementation raises - an exception. + App.Teacher = App.Person.extend({ + toStringExtension: function(){ + return this.get('fullName'); + } + }); + teacher = App.Teacher.create() + teacher.toString(); // #=> "" - @method copy - @param deep {Boolean} if true, a deep copy of the object should be made - @return {Object} copy of receiver + @method toString + @return {String} string representation */ - copy: Ember.required(Function), + toString: function toString() { + var hasToStringExtension = typeof this.toStringExtension === 'function', + extension = hasToStringExtension ? ":" + this.toStringExtension() : ''; + var ret = '<'+this.constructor.toString()+':'+guidFor(this)+extension+'>'; + this.toString = makeToString(ret); + return ret; + } +}); - /** - If the object implements Ember.Freezable, then this will return a new copy - if the object is not frozen and the receiver if the object is frozen. +function makeToString(ret) { + return function() { return ret; }; +} - Raises an exception if you try to call this method on a object that does - not support freezing. +if (Ember.config.overridePrototypeMixin) { + Ember.config.overridePrototypeMixin(CoreObject.PrototypeMixin); +} - You should use this method whenever you want a copy of a freezable object - since a freezable object can simply return itself without actually - consuming more memory. +CoreObject.__super__ = null; - @method frozenCopy - @return {Object} copy of receiver or receiver - */ - frozenCopy: function() { - if (Ember.Freezable && Ember.Freezable.detect(this)) { - return get(this, 'isFrozen') ? this : this.copy().freeze(); - } else { - throw new Error(Ember.String.fmt("%@ does not support freezing", [this])); - } - } -}); +var ClassMixin = Mixin.create({ + ClassMixin: Ember.required(), + PrototypeMixin: Ember.required(), + isClass: true, -})(); + isMethod: false, + extend: function() { + var Class = makeCtor(), proto; + Class.ClassMixin = Mixin.create(this.ClassMixin); + Class.PrototypeMixin = Mixin.create(this.PrototypeMixin); + Class.ClassMixin.ownerConstructor = Class; + Class.PrototypeMixin.ownerConstructor = Class; -(function() { -/** -@module ember -@submodule ember-runtime -*/ + reopen.apply(Class.PrototypeMixin, arguments); + Class.superclass = this; + Class.__super__ = this.prototype; -var get = Ember.get, set = Ember.set; + proto = Class.prototype = o_create(this.prototype); + proto.constructor = Class; + generateGuid(proto, 'ember'); + meta(proto).proto = proto; // this will disable observers on prototype -/** - The Ember.Freezable mixin implements some basic methods for marking an object - as frozen. Once an object is frozen it should be read only. No changes - may be made the internal state of the object. + Class.ClassMixin.apply(Class); + return Class; + }, - ## Enforcement + createWithMixins: function() { + var C = this; + if (arguments.length>0) { this._initMixins(arguments); } + return new C(); + }, - To fully support freezing in your subclass, you must include this mixin and - override any method that might alter any property on the object to instead - raise an exception. You can check the state of an object by checking the - isFrozen property. + create: function() { + var C = this; + if (arguments.length>0) { this._initProperties(arguments); } + return new C(); + }, - Although future versions of JavaScript may support language-level freezing - object objects, that is not the case today. Even if an object is freezable, - it is still technically possible to modify the object, even though it could - break other parts of your application that do not expect a frozen object to - change. It is, therefore, very important that you always respect the - isFrozen property on all freezable objects. + reopen: function() { + this.willReopen(); + reopen.apply(this.PrototypeMixin, arguments); + return this; + }, - ## Example Usage + reopenClass: function() { + reopen.apply(this.ClassMixin, arguments); + applyMixin(this, arguments, false); + return this; + }, - The example below shows a simple object that implement the Ember.Freezable - protocol. + detect: function(obj) { + if ('function' !== typeof obj) { return false; } + while(obj) { + if (obj===this) { return true; } + obj = obj.superclass; + } + return false; + }, - Contact = Ember.Object.extend(Ember.Freezable, { + detectInstance: function(obj) { + return obj instanceof this; + }, - firstName: null, + /** + In some cases, you may want to annotate computed properties with additional + metadata about how they function or what values they operate on. For + example, computed property functions may close over variables that are then + no longer available for introspection. - lastName: null, + You can pass a hash of these values to a computed property like this: - // swaps the names - swapNames: function() { - if (this.get('isFrozen')) throw Ember.FROZEN_ERROR; - var tmp = this.get('firstName'); - this.set('firstName', this.get('lastName')); - this.set('lastName', tmp); - return this; - } + ```javascript + person: function() { + var personId = this.get('personId'); + return App.Person.create({ id: personId }); + }.property().meta({ type: App.Person }) + ``` - }); + Once you've done this, you can retrieve the values saved to the computed + property from your class like this: - c = Context.create({ firstName: "John", lastName: "Doe" }); - c.swapNames(); => returns c - c.freeze(); - c.swapNames(); => EXCEPTION + ```javascript + MyClass.metaForProperty('person'); + ``` - ## Copying + This will return the original hash that was passed to `meta()`. - Usually the Ember.Freezable protocol is implemented in cooperation with the - Ember.Copyable protocol, which defines a frozenCopy() method that will return - a frozen object, if the object implements this method as well. + @method metaForProperty + @param key {String} property name + */ + metaForProperty: function(key) { + var desc = meta(this.proto(), false).descs[key]; - @class Freezable - @namespace Ember - @extends Ember.Mixin - @since Ember 0.9 -*/ -Ember.Freezable = Ember.Mixin.create( -/** @scope Ember.Freezable.prototype */ { + Ember.assert("metaForProperty() could not find a computed property with key '"+key+"'.", !!desc && desc instanceof Ember.ComputedProperty); + return desc._meta || {}; + }, /** - Set to true when the object is frozen. Use this property to detect whether - your object is frozen or not. + Iterate over each computed property for the class, passing its name + and any associated metadata (see `metaForProperty`) to the callback. - @property isFrozen - @type Boolean + @method eachComputedProperty + @param {Function} callback + @param {Object} binding */ - isFrozen: false, + eachComputedProperty: function(callback, binding) { + var proto = this.proto(), + descs = meta(proto).descs, + empty = {}, + property; - /** - Freezes the object. Once this method has been called the object should - no longer allow any properties to be edited. + for (var name in descs) { + property = descs[name]; - @method freeze - @return {Object} receiver - */ - freeze: function() { - if (get(this, 'isFrozen')) return this; - set(this, 'isFrozen', true); - return this; + if (property instanceof Ember.ComputedProperty) { + callback.call(binding || this, name, property._meta || empty); + } + } } }); -Ember.FROZEN_ERROR = "Frozen object cannot be modified."; +if (Ember.config.overrideClassMixin) { + Ember.config.overrideClassMixin(ClassMixin); +} + +CoreObject.ClassMixin = ClassMixin; +ClassMixin.apply(CoreObject); + +/** + @class CoreObject + @namespace Ember +*/ +Ember.CoreObject = CoreObject; })(); @@ -7568,396 +10343,453 @@ Ember.FROZEN_ERROR = "Frozen object cannot be modified."; @submodule ember-runtime */ -var forEach = Ember.EnumerableUtils.forEach; +var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor, none = Ember.isNone; /** - This mixin defines the API for modifying generic enumerables. These methods - can be applied to an object regardless of whether it is ordered or - unordered. + An unordered collection of objects. - Note that an Enumerable can change even if it does not implement this mixin. - For example, a MappedEnumerable cannot be directly modified but if its - underlying enumerable changes, it will change also. + A Set works a bit like an array except that its items are not ordered. You + can create a set to efficiently test for membership for an object. You can + also iterate through a set just like an array, even accessing objects by + index, however there is no guarantee as to their order. - ## Adding Objects + All Sets are observable via the Enumerable Observer API - which works + on any enumerable object including both Sets and Arrays. - To add an object to an enumerable, use the addObject() method. This - method will only add the object to the enumerable if the object is not - already present and the object if of a type supported by the enumerable. + ## Creating a Set - set.addObject(contact); + You can create a set like you would most objects using + `new Ember.Set()`. Most new sets you create will be empty, but you can + also initialize the set with some content by passing an array or other + enumerable of objects to the constructor. - ## Removing Objects + Finally, you can pass in an existing set and the set will be copied. You + can also create a copy of a set by calling `Ember.Set#copy()`. - To remove an object form an enumerable, use the removeObject() method. This - will only remove the object if it is already in the enumerable, otherwise - this method has no effect. + ```javascript + // creates a new empty set + var foundNames = new Ember.Set(); - set.removeObject(contact); + // creates a set with four names in it. + var names = new Ember.Set(["Charles", "Tom", "Juan", "Alex"]); // :P - ## Implementing In Your Own Code + // creates a copy of the names set. + var namesCopy = new Ember.Set(names); - If you are implementing an object and want to support this API, just include - this mixin in your class and implement the required methods. In your unit - tests, be sure to apply the Ember.MutableEnumerableTests to your object. + // same as above. + var anotherNamesCopy = names.copy(); + ``` - @class MutableEnumerable - @namespace Ember - @extends Ember.Mixin - @uses Ember.Enumerable -*/ -Ember.MutableEnumerable = Ember.Mixin.create(Ember.Enumerable, - /** @scope Ember.MutableEnumerable.prototype */ { + ## Adding/Removing Objects - /** - __Required.__ You must implement this method to apply this mixin. + You generally add or remove objects from a set using `add()` or + `remove()`. You can add any type of object including primitives such as + numbers, strings, and booleans. - Attempts to add the passed object to the receiver if the object is not - already present in the collection. If the object is present, this method - has no effect. + Unlike arrays, objects can only exist one time in a set. If you call `add()` + on a set with the same object multiple times, the object will only be added + once. Likewise, calling `remove()` with the same object multiple times will + remove the object the first time and have no effect on future calls until + you add the object to the set again. - If the passed object is of a type not supported by the receiver - then this method should raise an exception. + NOTE: You cannot add/remove `null` or `undefined` to a set. Any attempt to do + so will be ignored. - @method addObject - @param {Object} object The object to add to the enumerable. - @return {Object} the passed object - */ - addObject: Ember.required(Function), + In addition to add/remove you can also call `push()`/`pop()`. Push behaves + just like `add()` but `pop()`, unlike `remove()` will pick an arbitrary + object, remove it and return it. This is a good way to use a set as a job + queue when you don't care which order the jobs are executed in. + + ## Testing for an Object + + To test for an object's presence in a set you simply call + `Ember.Set#contains()`. + + ## Observing changes + + When using `Ember.Set`, you can observe the `"[]"` property to be + alerted whenever the content changes. You can also add an enumerable + observer to the set to be notified of specific objects that are added and + removed from the set. See `Ember.Enumerable` for more information on + enumerables. + + This is often unhelpful. If you are filtering sets of objects, for instance, + it is very inefficient to re-filter all of the items each time the set + changes. It would be better if you could just adjust the filtered set based + on what was changed on the original set. The same issue applies to merging + sets, as well. + + ## Other Methods + + `Ember.Set` primary implements other mixin APIs. For a complete reference + on the methods you will use with `Ember.Set`, please consult these mixins. + The most useful ones will be `Ember.Enumerable` and + `Ember.MutableEnumerable` which implement most of the common iterator + methods you are used to on Array. + + Note that you can also use the `Ember.Copyable` and `Ember.Freezable` + APIs on `Ember.Set` as well. Once a set is frozen it can no longer be + modified. The benefit of this is that when you call `frozenCopy()` on it, + Ember will avoid making copies of the set. This allows you to write + code that can know with certainty when the underlying set data will or + will not be modified. + + @class Set + @namespace Ember + @extends Ember.CoreObject + @uses Ember.MutableEnumerable + @uses Ember.Copyable + @uses Ember.Freezable + @since Ember 0.9 +*/ +Ember.Set = Ember.CoreObject.extend(Ember.MutableEnumerable, Ember.Copyable, Ember.Freezable, + /** @scope Ember.Set.prototype */ { + + // .......................................................... + // IMPLEMENT ENUMERABLE APIS + // /** - Adds each object in the passed enumerable to the receiver. + This property will change as the number of objects in the set changes. - @method addObjects - @param {Ember.Enumerable} objects the objects to add. - @return {Object} receiver + @property length + @type number + @default 0 */ - addObjects: function(objects) { - Ember.beginPropertyChanges(this); - forEach(objects, function(obj) { this.addObject(obj); }, this); - Ember.endPropertyChanges(this); - return this; - }, + length: 0, /** - __Required.__ You must implement this method to apply this mixin. - - Attempts to remove the passed object from the receiver collection if the - object is in present in the collection. If the object is not present, - this method has no effect. + Clears the set. This is useful if you want to reuse an existing set + without having to recreate it. - If the passed object is of a type not supported by the receiver - then this method should raise an exception. + ```javascript + var colors = new Ember.Set(["red", "green", "blue"]); + colors.length; // 3 + colors.clear(); + colors.length; // 0 + ``` - @method removeObject - @param {Object} object The object to remove from the enumerable. - @return {Object} the passed object + @method clear + @return {Ember.Set} An empty Set */ - removeObject: Ember.required(Function), + clear: function() { + if (this.isFrozen) { throw new Error(Ember.FROZEN_ERROR); } + var len = get(this, 'length'); + if (len === 0) { return this; } - /** - Removes each objects in the passed enumerable from the receiver. + var guid; - @method removeObjects - @param {Ember.Enumerable} objects the objects to remove - @return {Object} receiver - */ - removeObjects: function(objects) { - Ember.beginPropertyChanges(this); - forEach(objects, function(obj) { this.removeObject(obj); }, this); - Ember.endPropertyChanges(this); - return this; - } + this.enumerableContentWillChange(len, 0); + Ember.propertyWillChange(this, 'firstObject'); + Ember.propertyWillChange(this, 'lastObject'); -}); + for (var i=0; i < len; i++){ + guid = guidFor(this[i]); + delete this[guid]; + delete this[i]; + } -})(); + set(this, 'length', 0); + Ember.propertyDidChange(this, 'firstObject'); + Ember.propertyDidChange(this, 'lastObject'); + this.enumerableContentDidChange(len, 0); + return this; + }, -(function() { -/** -@module ember -@submodule ember-runtime -*/ -// .......................................................... -// CONSTANTS -// + /** + Returns true if the passed object is also an enumerable that contains the + same objects as the receiver. -var OUT_OF_RANGE_EXCEPTION = "Index out of range" ; -var EMPTY = []; + ```javascript + var colors = ["red", "green", "blue"], + same_colors = new Ember.Set(colors); -// .......................................................... -// HELPERS -// + same_colors.isEqual(colors); // true + same_colors.isEqual(["purple", "brown"]); // false + ``` -var get = Ember.get, set = Ember.set, forEach = Ember.EnumerableUtils.forEach; + @method isEqual + @param {Ember.Set} obj the other object. + @return {Boolean} + */ + isEqual: function(obj) { + // fail fast + if (!Ember.Enumerable.detect(obj)) return false; -/** - This mixin defines the API for modifying array-like objects. These methods - can be applied only to a collection that keeps its items in an ordered set. + var loc = get(this, 'length'); + if (get(obj, 'length') !== loc) return false; - Note that an Array can change even if it does not implement this mixin. - For example, one might implement a SparseArray that cannot be directly - modified, but if its underlying enumerable changes, it will change also. + while(--loc >= 0) { + if (!obj.contains(this[loc])) return false; + } - @class MutableArray - @namespace Ember - @extends Ember.Mixin - @uses Ember.Array - @uses Ember.MutableEnumerable -*/ -Ember.MutableArray = Ember.Mixin.create(Ember.Array, Ember.MutableEnumerable, - /** @scope Ember.MutableArray.prototype */ { + return true; + }, /** - __Required.__ You must implement this method to apply this mixin. + Adds an object to the set. Only non-`null` objects can be added to a set + and those can only be added once. If the object is already in the set or + the passed value is null this method will have no effect. + + This is an alias for `Ember.MutableEnumerable.addObject()`. - This is one of the primitives you must implement to support Ember.Array. You - should replace amt objects started at idx with the objects in the passed - array. You should also call this.enumerableContentDidChange() ; + ```javascript + var colors = new Ember.Set(); + colors.add("blue"); // ["blue"] + colors.add("blue"); // ["blue"] + colors.add("red"); // ["blue", "red"] + colors.add(null); // ["blue", "red"] + colors.add(undefined); // ["blue", "red"] + ``` - @method replace - @param {Number} idx Starting index in the array to replace. If idx >= length, - then append to the end of the array. - @param {Number} amt Number of elements that should be removed from the array, - starting at *idx*. - @param {Array} objects An array of zero or more objects that should be inserted - into the array at *idx* + @method add + @param {Object} obj The object to add. + @return {Ember.Set} The set itself. */ - replace: Ember.required(), + add: Ember.aliasMethod('addObject'), /** - Remove all elements from self. This is useful if you - want to reuse an existing array without having to recreate it. + Removes the object from the set if it is found. If you pass a `null` value + or an object that is already not in the set, this method will have no + effect. This is an alias for `Ember.MutableEnumerable.removeObject()`. - var colors = ["red", "green", "blue"]; - color.length(); => 3 - colors.clear(); => [] - colors.length(); => 0 + ```javascript + var colors = new Ember.Set(["red", "green", "blue"]); + colors.remove("red"); // ["blue", "green"] + colors.remove("purple"); // ["blue", "green"] + colors.remove(null); // ["blue", "green"] + ``` - @method clear - @return {Ember.Array} An empty Array. + @method remove + @param {Object} obj The object to remove + @return {Ember.Set} The set itself. */ - clear: function () { - var len = get(this, 'length'); - if (len === 0) return this; - this.replace(0, len, EMPTY); - return this; - }, + remove: Ember.aliasMethod('removeObject'), /** - This will use the primitive replace() method to insert an object at the - specified index. + Removes the last element from the set and returns it, or `null` if it's empty. - var colors = ["red", "green", "blue"]; - colors.insertAt(2, "yellow"); => ["red", "green", "yellow", "blue"] - colors.insertAt(5, "orange"); => Error: Index out of range + ```javascript + var colors = new Ember.Set(["green", "blue"]); + colors.pop(); // "blue" + colors.pop(); // "green" + colors.pop(); // null + ``` - @method insertAt - @param {Number} idx index of insert the object at. - @param {Object} object object to insert + @method pop + @return {Object} The removed object from the set or null. */ - insertAt: function(idx, object) { - if (idx > get(this, 'length')) throw new Error(OUT_OF_RANGE_EXCEPTION) ; - this.replace(idx, 0, [object]) ; - return this ; + pop: function() { + if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); + var obj = this.length > 0 ? this[this.length-1] : null; + this.remove(obj); + return obj; }, /** - Remove an object at the specified index using the replace() primitive - method. You can pass either a single index, or a start and a length. + Inserts the given object on to the end of the set. It returns + the set itself. - If you pass a start and length that is beyond the - length this method will throw an Ember.OUT_OF_RANGE_EXCEPTION + This is an alias for `Ember.MutableEnumerable.addObject()`. - var colors = ["red", "green", "blue", "yellow", "orange"]; - colors.removeAt(0); => ["green", "blue", "yellow", "orange"] - colors.removeAt(2, 2); => ["green", "blue"] - colors.removeAt(4, 2); => Error: Index out of range + ```javascript + var colors = new Ember.Set(); + colors.push("red"); // ["red"] + colors.push("green"); // ["red", "green"] + colors.push("blue"); // ["red", "green", "blue"] + ``` - @method removeAt - @param {Number} start index, start of range - @param {Number} len length of passing range - @return {Object} receiver + @method push + @return {Ember.Set} The set itself. */ - removeAt: function(start, len) { - if ('number' === typeof start) { + push: Ember.aliasMethod('addObject'), - if ((start < 0) || (start >= get(this, 'length'))) { - throw new Error(OUT_OF_RANGE_EXCEPTION); - } + /** + Removes the last element from the set and returns it, or `null` if it's empty. - // fast case - if (len === undefined) len = 1; - this.replace(start, len, EMPTY); - } + This is an alias for `Ember.Set.pop()`. - return this ; - }, + ```javascript + var colors = new Ember.Set(["green", "blue"]); + colors.shift(); // "blue" + colors.shift(); // "green" + colors.shift(); // null + ``` + + @method shift + @return {Object} The removed object from the set or null. + */ + shift: Ember.aliasMethod('pop'), /** - Push the object onto the end of the array. Works just like push() but it - is KVO-compliant. + Inserts the given object on to the end of the set. It returns + the set itself. - var colors = ["red", "green", "blue"]; - colors.pushObject("black"); => ["red", "green", "blue", "black"] - colors.pushObject(["yellow", "orange"]); => ["red", "green", "blue", "black", ["yellow", "orange"]] + This is an alias of `Ember.Set.push()` - @method pushObject - @param {anything} obj object to push + ```javascript + var colors = new Ember.Set(); + colors.unshift("red"); // ["red"] + colors.unshift("green"); // ["red", "green"] + colors.unshift("blue"); // ["red", "green", "blue"] + ``` + + @method unshift + @return {Ember.Set} The set itself. */ - pushObject: function(obj) { - this.insertAt(get(this, 'length'), obj) ; - return obj ; - }, + unshift: Ember.aliasMethod('push'), /** - Add the objects in the passed numerable to the end of the array. Defers - notifying observers of the change until all objects are added. + Adds each object in the passed enumerable to the set. - var colors = ["red", "green", "blue"]; - colors.pushObjects("black"); => ["red", "green", "blue", "black"] - colors.pushObjects(["yellow", "orange"]); => ["red", "green", "blue", "black", "yellow", "orange"] + This is an alias of `Ember.MutableEnumerable.addObjects()` - @method pushObjects - @param {Ember.Enumerable} objects the objects to add - @return {Ember.Array} receiver + ```javascript + var colors = new Ember.Set(); + colors.addEach(["red", "green", "blue"]); // ["red", "green", "blue"] + ``` + + @method addEach + @param {Ember.Enumerable} objects the objects to add. + @return {Ember.Set} The set itself. */ - pushObjects: function(objects) { - this.replace(get(this, 'length'), 0, objects); - return this; - }, + addEach: Ember.aliasMethod('addObjects'), /** - Pop object from array or nil if none are left. Works just like pop() but - it is KVO-compliant. + Removes each object in the passed enumerable to the set. - var colors = ["red", "green", "blue"]; - colors.popObject(); => "blue" - console.log(colors); => ["red", "green"] + This is an alias of `Ember.MutableEnumerable.removeObjects()` - @method popObject - @return object + ```javascript + var colors = new Ember.Set(["red", "green", "blue"]); + colors.removeEach(["red", "blue"]); // ["green"] + ``` + + @method removeEach + @param {Ember.Enumerable} objects the objects to remove. + @return {Ember.Set} The set itself. */ - popObject: function() { - var len = get(this, 'length') ; - if (len === 0) return null ; + removeEach: Ember.aliasMethod('removeObjects'), - var ret = this.objectAt(len-1) ; - this.removeAt(len-1, 1) ; - return ret ; + // .......................................................... + // PRIVATE ENUMERABLE SUPPORT + // + + init: function(items) { + this._super(); + if (items) this.addObjects(items); }, - /** - Shift an object from start of array or nil if none are left. Works just - like shift() but it is KVO-compliant. + // implement Ember.Enumerable + nextObject: function(idx) { + return this[idx]; + }, + + // more optimized version + firstObject: Ember.computed(function() { + return this.length > 0 ? this[0] : undefined; + }), - var colors = ["red", "green", "blue"]; - colors.shiftObject(); => "red" - console.log(colors); => ["green", "blue"] + // more optimized version + lastObject: Ember.computed(function() { + return this.length > 0 ? this[this.length-1] : undefined; + }), - @method shiftObject - @return object - */ - shiftObject: function() { - if (get(this, 'length') === 0) return null ; - var ret = this.objectAt(0) ; - this.removeAt(0) ; - return ret ; - }, + // implements Ember.MutableEnumerable + addObject: function(obj) { + if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); + if (none(obj)) return this; // nothing to do - /** - Unshift an object to start of array. Works just like unshift() but it is - KVO-compliant. + var guid = guidFor(obj), + idx = this[guid], + len = get(this, 'length'), + added ; - var colors = ["red", "green", "blue"]; - colors.unshiftObject("yellow"); => ["yellow", "red", "green", "blue"] - colors.unshiftObject(["black", "white"]); => [["black", "white"], "yellow", "red", "green", "blue"] + if (idx>=0 && idx ["black", "white", "red", "green", "blue"] - colors.unshiftObjects("yellow"); => Type Error: 'undefined' is not a function + len = get(this, 'length'); + this[guid] = len; + this[len] = obj; + set(this, 'length', len+1); + + Ember.propertyDidChange(this, 'lastObject'); + this.enumerableContentDidChange(null, added); - @method unshiftObjects - @param {Ember.Enumerable} objects the objects to add - @return {Ember.Array} receiver - */ - unshiftObjects: function(objects) { - this.replace(0, 0, objects); return this; }, - /** - Reverse objects in the array. Works just like reverse() but it is - KVO-compliant. + // implements Ember.MutableEnumerable + removeObject: function(obj) { + if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); + if (none(obj)) return this; // nothing to do - @method reverseObjects - @return {Ember.Array} receiver - */ - reverseObjects: function() { - var len = get(this, 'length'); - if (len === 0) return this; - var objects = this.toArray().reverse(); - this.replace(0, len, objects); - return this; - }, + var guid = guidFor(obj), + idx = this[guid], + len = get(this, 'length'), + isFirst = idx === 0, + isLast = idx === len-1, + last, removed; - /** - Replace all the the receiver's content with content of the argument. - If argument is an empty array receiver will be cleared. - var colors = ["red", "green", "blue"]; - colors.setObjects(["black", "white"]); => ["black", "white"] - colors.setObjects([]); => [] + if (idx>=0 && idx=0; + }, - removeObject: function(obj) { - var loc = get(this, 'length') || 0; - while(--loc >= 0) { - var curObject = this.objectAt(loc) ; - if (curObject === obj) this.removeAt(loc) ; + copy: function() { + var C = this.constructor, ret = new C(), loc = get(this, 'length'); + set(ret, 'length', loc); + while(--loc>=0) { + ret[loc] = this[loc]; + ret[guidFor(this[loc])] = loc; } - return this ; + return ret; }, - addObject: function(obj) { - if (!this.contains(obj)) this.pushObject(obj); - return this ; + toString: function() { + var len = this.length, idx, array = []; + for(idx = 0; idx < len; idx++) { + array[idx] = this[idx]; + } + return "Ember.Set<%@>".fmt(array.join(',')); } }); - })(); @@ -7968,512 +10800,487 @@ Ember.MutableArray = Ember.Mixin.create(Ember.Array, Ember.MutableEnumerable, @submodule ember-runtime */ -var get = Ember.get, set = Ember.set, defineProperty = Ember.defineProperty; - /** - ## Overview - - This mixin provides properties and property observing functionality, core - features of the Ember object model. - - Properties and observers allow one object to observe changes to a - property on another object. This is one of the fundamental ways that - models, controllers and views communicate with each other in an Ember - application. - - Any object that has this mixin applied can be used in observer - operations. That includes Ember.Object and most objects you will - interact with as you write your Ember application. - - Note that you will not generally apply this mixin to classes yourself, - but you will use the features provided by this module frequently, so it - is important to understand how to use it. - - ## Using get() and set() - - Because of Ember's support for bindings and observers, you will always - access properties using the get method, and set properties using the - set method. This allows the observing objects to be notified and - computed properties to be handled properly. + `Ember.Object` is the main base class for all Ember objects. It is a subclass + of `Ember.CoreObject` with the `Ember.Observable` mixin applied. For details, + see the documentation for each of these. - More documentation about `get` and `set` are below. + @class Object + @namespace Ember + @extends Ember.CoreObject + @uses Ember.Observable +*/ +Ember.Object = Ember.CoreObject.extend(Ember.Observable); - ## Observing Property Changes +})(); - You typically observe property changes simply by adding the `observes` - call to the end of your method declarations in classes that you write. - For example: - Ember.Object.create({ - valueObserver: function() { - // Executes whenever the "value" property changes - }.observes('value') - }); - Although this is the most common way to add an observer, this capability - is actually built into the Ember.Object class on top of two methods - defined in this mixin: `addObserver` and `removeObserver`. You can use - these two methods to add and remove observers yourself if you need to - do so at runtime. +(function() { +/** +@module ember +@submodule ember-runtime +*/ - To add an observer for a property, call: +var get = Ember.get, indexOf = Ember.ArrayPolyfills.indexOf; - object.addObserver('propertyKey', targetObject, targetAction) +/** + A Namespace is an object usually used to contain other objects or methods + such as an application or framework. Create a namespace anytime you want + to define one of these new containers. - This will call the `targetAction` method on the `targetObject` to be called - whenever the value of the `propertyKey` changes. + # Example Usage - Note that if `propertyKey` is a computed property, the observer will be - called when any of the property dependencies are changed, even if the - resulting value of the computed property is unchanged. This is necessary - because computed properties are not computed until `get` is called. + ```javascript + MyFramework = Ember.Namespace.create({ + VERSION: '1.0.0' + }); + ``` - @class Observable + @class Namespace @namespace Ember - @extends Ember.Mixin + @extends Ember.Object */ -Ember.Observable = Ember.Mixin.create(/** @scope Ember.Observable.prototype */ { - - // compatibility - isObserverable: true, - - /** - Retrieves the value of a property from the object. - - This method is usually similar to using object[keyName] or object.keyName, - however it supports both computed properties and the unknownProperty - handler. +var Namespace = Ember.Namespace = Ember.Object.extend({ + isNamespace: true, - Because `get` unifies the syntax for accessing all these kinds - of properties, it can make many refactorings easier, such as replacing a - simple property with a computed property, or vice versa. + init: function() { + Ember.Namespace.NAMESPACES.push(this); + Ember.Namespace.PROCESSED = false; + }, - ### Computed Properties + toString: function() { + var name = get(this, 'name'); + if (name) { return name; } - Computed properties are methods defined with the `property` modifier - declared at the end, such as: + findNamespaces(); + return this[Ember.GUID_KEY+'_name']; + }, - fullName: function() { - return this.getEach('firstName', 'lastName').compact().join(' '); - }.property('firstName', 'lastName') + nameClasses: function() { + processNamespace([this.toString()], this, {}); + }, - When you call `get` on a computed property, the function will be - called and the return value will be returned instead of the function - itself. + destroy: function() { + var namespaces = Ember.Namespace.NAMESPACES; + Ember.lookup[this.toString()] = undefined; + namespaces.splice(indexOf.call(namespaces, this), 1); + this._super(); + } +}); - ### Unknown Properties +Namespace.reopenClass({ + NAMESPACES: [Ember], + PROCESSED: false, + processAll: processAllNamespaces +}); - Likewise, if you try to call `get` on a property whose value is - undefined, the unknownProperty() method will be called on the object. - If this method returns any value other than undefined, it will be returned - instead. This allows you to implement "virtual" properties that are - not defined upfront. +var hasOwnProp = ({}).hasOwnProperty, + guidFor = Ember.guidFor; - @method get - @param {String} key The property to retrieve - @return {Object} The property value or undefined. - */ - get: function(keyName) { - return get(this, keyName); - }, +function processNamespace(paths, root, seen) { + var idx = paths.length; - /** - To get multiple properties at once, call getProperties - with a list of strings or an array: + // Loop over all of the keys in the namespace, looking for classes + for(var key in root) { + if (!hasOwnProp.call(root, key)) { continue; } + var obj = root[key]; - record.getProperties('firstName', 'lastName', 'zipCode'); // => { firstName: 'John', lastName: 'Doe', zipCode: '10011' } + // If we are processing the `Ember` namespace, for example, the + // `paths` will start with `["Ember"]`. Every iteration through + // the loop will update the **second** element of this list with + // the key, so processing `Ember.View` will make the Array + // `['Ember', 'View']`. + paths[idx] = key; - is equivalent to: + // If we have found an unprocessed class + if (obj && obj.toString === classToString) { + // Replace the class' `toString` with the dot-separated path + // and set its `NAME_KEY` + obj.toString = makeToString(paths.join('.')); + obj[NAME_KEY] = paths.join('.'); - record.getProperties(['firstName', 'lastName', 'zipCode']); // => { firstName: 'John', lastName: 'Doe', zipCode: '10011' } + // Support nested namespaces + } else if (obj && obj.isNamespace) { + // Skip aliased namespaces + if (seen[guidFor(obj)]) { continue; } + seen[guidFor(obj)] = true; - @method getProperties - @param {String...|Array} list of keys to get - @return {Hash} - */ - getProperties: function() { - var ret = {}; - var propertyNames = arguments; - if (arguments.length === 1 && Ember.typeOf(arguments[0]) === 'array') { - propertyNames = arguments[0]; + // Process the child namespace + processNamespace(paths, obj, seen); } - for(var i = 0; i < propertyNames.length; i++) { - ret[propertyNames[i]] = get(this, propertyNames[i]); - } - return ret; - }, - - /** - Sets the provided key or path to the value. + } - This method is generally very similar to calling object[key] = value or - object.key = value, except that it provides support for computed - properties, the unknownProperty() method and property observers. + paths.length = idx; // cut out last item +} - ### Computed Properties +function findNamespaces() { + var Namespace = Ember.Namespace, lookup = Ember.lookup, obj, isNamespace; - If you try to set a value on a key that has a computed property handler - defined (see the get() method for an example), then set() will call - that method, passing both the value and key instead of simply changing - the value itself. This is useful for those times when you need to - implement a property that is composed of one or more member - properties. + if (Namespace.PROCESSED) { return; } - ### Unknown Properties + for (var prop in lookup) { + // These don't raise exceptions but can cause warnings + if (prop === "parent" || prop === "top" || prop === "frameElement") { continue; } - If you try to set a value on a key that is undefined in the target - object, then the unknownProperty() handler will be called instead. This - gives you an opportunity to implement complex "virtual" properties that - are not predefined on the object. If unknownProperty() returns - undefined, then set() will simply set the value on the object. + // get(window.globalStorage, 'isNamespace') would try to read the storage for domain isNamespace and cause exception in Firefox. + // globalStorage is a storage obsoleted by the WhatWG storage specification. See https://developer.mozilla.org/en/DOM/Storage#globalStorage + if (prop === "globalStorage" && lookup.StorageList && lookup.globalStorage instanceof lookup.StorageList) { continue; } + // Unfortunately, some versions of IE don't support window.hasOwnProperty + if (lookup.hasOwnProperty && !lookup.hasOwnProperty(prop)) { continue; } - ### Property Observers + // At times we are not allowed to access certain properties for security reasons. + // There are also times where even if we can access them, we are not allowed to access their properties. + try { + obj = Ember.lookup[prop]; + isNamespace = obj && obj.isNamespace; + } catch (e) { + continue; + } - In addition to changing the property, set() will also register a - property change with the object. Unless you have placed this call - inside of a beginPropertyChanges() and endPropertyChanges(), any "local" - observers (i.e. observer methods declared on the same object), will be - called immediately. Any "remote" observers (i.e. observer methods - declared on another object) will be placed in a queue and called at a - later time in a coalesced manner. + if (isNamespace) { + Ember.deprecate("Namespaces should not begin with lowercase.", /^[A-Z]/.test(prop)); + obj[NAME_KEY] = prop; + } + } +} - ### Chaining +var NAME_KEY = Ember.NAME_KEY = Ember.GUID_KEY + '_name'; - In addition to property changes, set() returns the value of the object - itself so you can do chaining like this: +function superClassString(mixin) { + var superclass = mixin.superclass; + if (superclass) { + if (superclass[NAME_KEY]) { return superclass[NAME_KEY]; } + else { return superClassString(superclass); } + } else { + return; + } +} - record.set('firstName', 'Charles').set('lastName', 'Jolley'); +function classToString() { + if (!Ember.BOOTED && !this[NAME_KEY]) { + processAllNamespaces(); + } - @method set - @param {String} key The property to set - @param {Object} value The value to set or null. - @return {Ember.Observable} - */ - set: function(keyName, value) { - set(this, keyName, value); - return this; - }, + var ret; - /** - To set multiple properties at once, call setProperties - with a Hash: + if (this[NAME_KEY]) { + ret = this[NAME_KEY]; + } else { + var str = superClassString(this); + if (str) { + ret = "(subclass of " + str + ")"; + } else { + ret = "(unknown mixin)"; + } + this.toString = makeToString(ret); + } - record.setProperties({ firstName: 'Charles', lastName: 'Jolley' }); + return ret; +} - @method setProperties - @param {Hash} hash the hash of keys and values to set - @return {Ember.Observable} - */ - setProperties: function(hash) { - return Ember.setProperties(this, hash); - }, +function processAllNamespaces() { + if (!Namespace.PROCESSED) { + findNamespaces(); + Namespace.PROCESSED = true; + } - /** - Begins a grouping of property changes. + if (Ember.anyUnprocessedMixins) { + var namespaces = Namespace.NAMESPACES, namespace; + for (var i=0, l=namespaces.length; i=idx) { + var item = content.objectAt(loc); + if (item) { + Ember.addBeforeObserver(item, keyName, proxy, 'contentKeyWillChange'); + Ember.addObserver(item, keyName, proxy, 'contentKeyDidChange'); + // keep track of the indicies each item was found at so we can map + // it back when the obj changes. + guid = guidFor(item); + if (!objects[guid]) objects[guid] = []; + objects[guid].push(loc); + } + } } -var CoreObject = makeCtor(); +function removeObserverForContentKey(content, keyName, proxy, idx, loc) { + var objects = proxy._objects; + if (!objects) objects = proxy._objects = {}; + var indicies, guid; -CoreObject.PrototypeMixin = Mixin.create({ + while(--loc>=idx) { + var item = content.objectAt(loc); + if (item) { + Ember.removeBeforeObserver(item, keyName, proxy, 'contentKeyWillChange'); + Ember.removeObserver(item, keyName, proxy, 'contentKeyDidChange'); - reopen: function() { - applyMixin(this, arguments, true); - return this; - }, + guid = guidFor(item); + indicies = objects[guid]; + indicies[indicies.indexOf(loc)] = null; + } + } +} - isInstance: true, +/** + This is the object instance returned when you get the `@each` property on an + array. It uses the unknownProperty handler to automatically create + EachArray instances for property names. - init: function() {}, + @private + @class EachProxy + @namespace Ember + @extends Ember.Object +*/ +Ember.EachProxy = Ember.Object.extend({ - /** - @property isDestroyed - @default false - */ - isDestroyed: false, + init: function(content) { + this._super(); + this._content = content; + content.addArrayObserver(this); + + // in case someone is already observing some keys make sure they are + // added + forEach(Ember.watchedEvents(this), function(eventName) { + this.didAddListener(eventName); + }, this); + }, /** - @property isDestroying - @default false + You can directly access mapped properties by simply requesting them. + The `unknownProperty` handler will generate an EachArray of each item. + + @method unknownProperty + @param keyName {String} + @param value {anything} */ - isDestroying: false, + unknownProperty: function(keyName, value) { + var ret; + ret = new EachArray(this._content, keyName, this); + Ember.defineProperty(this, keyName, null, ret); + this.beginObservingContentKey(keyName); + return ret; + }, - /** - Destroys an object by setting the isDestroyed flag and removing its - metadata, which effectively destroys observers and bindings. + // .......................................................... + // ARRAY CHANGES + // Invokes whenever the content array itself changes. - If you try to set a property on a destroyed object, an exception will be - raised. + arrayWillChange: function(content, idx, removedCnt, addedCnt) { + var keys = this._keys, key, array, lim; - Note that destruction is scheduled for the end of the run loop and does not - happen immediately. + lim = removedCnt>0 ? idx+removedCnt : -1; + Ember.beginPropertyChanges(this); - @method destroy - @return {Ember.Object} receiver - */ - destroy: function() { - if (this.isDestroying) { return; } + for(key in keys) { + if (!keys.hasOwnProperty(key)) { continue; } - this.isDestroying = true; + if (lim>0) removeObserverForContentKey(content, key, this, idx, lim); - if (this.willDestroy) { this.willDestroy(); } + Ember.propertyWillChange(this, key); + } - set(this, 'isDestroyed', true); - schedule('destroy', this, this._scheduledDestroy); - return this; + Ember.propertyWillChange(this._content, '@each'); + Ember.endPropertyChanges(this); }, - /** - @private + arrayDidChange: function(content, idx, removedCnt, addedCnt) { + var keys = this._keys, key, array, lim; - Invoked by the run loop to actually destroy the object. This is - scheduled for execution by the `destroy` method. + lim = addedCnt>0 ? idx+addedCnt : -1; + Ember.beginPropertyChanges(this); - @method _scheduledDestroy - */ - _scheduledDestroy: function() { - destroy(this); - if (this.didDestroy) { this.didDestroy(); } + for(key in keys) { + if (!keys.hasOwnProperty(key)) { continue; } + + if (lim>0) addObserverForContentKey(content, key, this, idx, lim); + + Ember.propertyDidChange(this, key); + } + + Ember.propertyDidChange(this._content, '@each'); + Ember.endPropertyChanges(this); }, - bind: function(to, from) { - if (!(from instanceof Ember.Binding)) { from = Ember.Binding.from(from); } - from.to(to).connect(this); - return from; + // .......................................................... + // LISTEN FOR NEW OBSERVERS AND OTHER EVENT LISTENERS + // Start monitoring keys based on who is listening... + + didAddListener: function(eventName) { + if (IS_OBSERVER.test(eventName)) { + this.beginObservingContentKey(eventName.slice(0, -7)); + } }, - toString: function() { - return '<'+this.constructor.toString()+':'+guidFor(this)+'>'; - } -}); + didRemoveListener: function(eventName) { + if (IS_OBSERVER.test(eventName)) { + this.stopObservingContentKey(eventName.slice(0, -7)); + } + }, -if (Ember.config.overridePrototypeMixin) { - Ember.config.overridePrototypeMixin(CoreObject.PrototypeMixin); -} + // .......................................................... + // CONTENT KEY OBSERVING + // Actual watch keys on the source content. -CoreObject.__super__ = null; + beginObservingContentKey: function(keyName) { + var keys = this._keys; + if (!keys) keys = this._keys = {}; + if (!keys[keyName]) { + keys[keyName] = 1; + var content = this._content, + len = get(content, 'length'); + addObserverForContentKey(content, keyName, this, 0, len); + } else { + keys[keyName]++; + } + }, -var ClassMixin = Mixin.create({ + stopObservingContentKey: function(keyName) { + var keys = this._keys; + if (keys && (keys[keyName]>0) && (--keys[keyName]<=0)) { + var content = this._content, + len = get(content, 'length'); + removeObserverForContentKey(content, keyName, this, 0, len); + } + }, - ClassMixin: Ember.required(), + contentKeyWillChange: function(obj, keyName) { + Ember.propertyWillChange(this, keyName); + }, - PrototypeMixin: Ember.required(), + contentKeyDidChange: function(obj, keyName) { + Ember.propertyDidChange(this, keyName); + } - isClass: true, +}); - isMethod: false, - extend: function() { - var Class = makeCtor(), proto; - Class.ClassMixin = Mixin.create(this.ClassMixin); - Class.PrototypeMixin = Mixin.create(this.PrototypeMixin); - Class.ClassMixin.ownerConstructor = Class; - Class.PrototypeMixin.ownerConstructor = Class; +})(); - reopen.apply(Class.PrototypeMixin, arguments); - Class.superclass = this; - Class.__super__ = this.prototype; - proto = Class.prototype = o_create(this.prototype); - proto.constructor = Class; - generateGuid(proto, 'ember'); - meta(proto).proto = proto; // this will disable observers on prototype +(function() { +/** +@module ember +@submodule ember-runtime +*/ - Class.ClassMixin.apply(Class); - return Class; - }, - create: function() { - var C = this; - if (arguments.length>0) { this._initMixins(arguments); } - return new C(); - }, +var get = Ember.get, set = Ember.set; - reopen: function() { - this.willReopen(); - reopen.apply(this.PrototypeMixin, arguments); - return this; - }, +// Add Ember.Array to Array.prototype. Remove methods with native +// implementations and supply some more optimized versions of generic methods +// because they are so common. +var NativeArray = Ember.Mixin.create(Ember.MutableArray, Ember.Observable, Ember.Copyable, { - reopenClass: function() { - reopen.apply(this.ClassMixin, arguments); - applyMixin(this, arguments, false); - return this; + // because length is a built-in property we need to know to just get the + // original property. + get: function(key) { + if (key==='length') return this.length; + else if ('number' === typeof key) return this[key]; + else return this._super(key); }, - detect: function(obj) { - if ('function' !== typeof obj) { return false; } - while(obj) { - if (obj===this) { return true; } - obj = obj.superclass; - } - return false; + objectAt: function(idx) { + return this[idx]; }, - detectInstance: function(obj) { - return obj instanceof this; - }, + // primitive for array support. + replace: function(idx, amt, objects) { - /** - In some cases, you may want to annotate computed properties with additional - metadata about how they function or what values they operate on. For example, - computed property functions may close over variables that are then no longer - available for introspection. + if (this.isFrozen) throw Ember.FROZEN_ERROR ; - You can pass a hash of these values to a computed property like this: + // if we replaced exactly the same number of items, then pass only the + // replaced range. Otherwise, pass the full remaining array length + // since everything has shifted + var len = objects ? get(objects, 'length') : 0; + this.arrayContentWillChange(idx, amt, len); - person: function() { - var personId = this.get('personId'); - return App.Person.create({ id: personId }); - }.property().meta({ type: App.Person }) + if (!objects || objects.length === 0) { + this.splice(idx, amt) ; + } else { + var args = [idx, amt].concat(objects) ; + this.splice.apply(this,args) ; + } - Once you've done this, you can retrieve the values saved to the computed - property from your class like this: + this.arrayContentDidChange(idx, amt, len); + return this ; + }, - MyClass.metaForProperty('person'); + // If you ask for an unknown property, then try to collect the value + // from member items. + unknownProperty: function(key, value) { + var ret;// = this.reducedProperty(key, value) ; + if ((value !== undefined) && ret === undefined) { + ret = this[key] = value; + } + return ret ; + }, - This will return the original hash that was passed to `meta()`. + // If browser did not implement indexOf natively, then override with + // specialized version + indexOf: function(object, startAt) { + var idx, len = this.length; - @method metaForProperty - @param key {String} property name - */ - metaForProperty: function(key) { - var desc = meta(this.proto(), false).descs[key]; + if (startAt === undefined) startAt = 0; + else startAt = (startAt < 0) ? Math.ceil(startAt) : Math.floor(startAt); + if (startAt < 0) startAt += len; - Ember.assert("metaForProperty() could not find a computed property with key '"+key+"'.", !!desc && desc instanceof Ember.ComputedProperty); - return desc._meta || {}; + for(idx=startAt;idx=0;idx--) { + if (this[idx] === object) return idx ; + } + return -1; + }, - if (property instanceof Ember.ComputedProperty) { - callback.call(binding || this, name, property._meta || empty); - } + copy: function(deep) { + if (deep) { + return this.map(function(item){ return Ember.copy(item, true); }); } + + return this.slice(); } +}); +// Remove any methods implemented natively so we don't override them +var ignore = ['length']; +Ember.EnumerableUtils.forEach(NativeArray.keys(), function(methodName) { + if (Array.prototype[methodName]) ignore.push(methodName); }); -if (Ember.config.overrideClassMixin) { - Ember.config.overrideClassMixin(ClassMixin); +if (ignore.length>0) { + NativeArray = NativeArray.without.apply(NativeArray, ignore); } -CoreObject.ClassMixin = ClassMixin; -ClassMixin.apply(CoreObject); - /** - @class CoreObject + The NativeArray mixin contains the properties needed to to make the native + Array support Ember.MutableArray and all of its dependent APIs. Unless you + have `Ember.EXTEND_PROTOTYPES or `Ember.EXTEND_PROTOTYPES.Array` set to + false, this will be applied automatically. Otherwise you can apply the mixin + at anytime by calling `Ember.NativeArray.activate`. + + @class NativeArray @namespace Ember + @extends Ember.Mixin + @uses Ember.MutableArray + @uses Ember.MutableEnumerable + @uses Ember.Copyable + @uses Ember.Freezable */ -Ember.CoreObject = CoreObject; +Ember.NativeArray = NativeArray; + +/** + Creates an `Ember.NativeArray` from an Array like object. + Does not modify the original object. + + @method A + @for Ember + @return {Ember.NativeArray} +*/ +Ember.A = function(arr){ + if (arr === undefined) { arr = []; } + return Ember.Array.detect(arr) ? arr : Ember.NativeArray.apply(arr); +}; + +/** + Activates the mixin on the Array.prototype if not already applied. Calling + this method more than once is safe. + + @method activate + @for Ember.NativeArray + @static + @return {void} +*/ +Ember.NativeArray.activate = function() { + NativeArray.apply(Array.prototype); + + Ember.A = function(arr) { return arr || []; }; +}; + +if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Array) { + Ember.NativeArray.activate(); +} + + +})(); +(function() { +var DeferredMixin = Ember.DeferredMixin, // mixins/deferred + EmberObject = Ember.Object, // system/object + get = Ember.get; + +var Deferred = Ember.Object.extend(DeferredMixin); + +Deferred.reopenClass({ + promise: function(callback, binding) { + var deferred = Deferred.create(); + callback.call(binding, deferred); + return get(deferred, 'promise'); + } +}); + +Ember.Deferred = Deferred; })(); @@ -8922,504 +11822,566 @@ Ember.CoreObject = CoreObject; @submodule ember-runtime */ -var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor, none = Ember.none; +var loadHooks = {}; +var loaded = {}; /** - An unordered collection of objects. - - A Set works a bit like an array except that its items are not ordered. - You can create a set to efficiently test for membership for an object. You - can also iterate through a set just like an array, even accessing objects - by index, however there is no guarantee as to their order. - - All Sets are observable via the Enumerable Observer API - which works - on any enumerable object including both Sets and Arrays. - - ## Creating a Set +@method onLoad +@for Ember +@param name {String} name of hook +@param callback {Function} callback to be called +*/ +Ember.onLoad = function(name, callback) { + var object; - You can create a set like you would most objects using - `new Ember.Set()`. Most new sets you create will be empty, but you can - also initialize the set with some content by passing an array or other - enumerable of objects to the constructor. + loadHooks[name] = loadHooks[name] || Ember.A(); + loadHooks[name].pushObject(callback); - Finally, you can pass in an existing set and the set will be copied. You - can also create a copy of a set by calling `Ember.Set#copy()`. + if (object = loaded[name]) { + callback(object); + } +}; - #js - // creates a new empty set - var foundNames = new Ember.Set(); +/** +@method runLoadHooks +@for Ember +@param name {String} name of hook +@param object {Object} object to pass to callbacks +*/ +Ember.runLoadHooks = function(name, object) { + var hooks; - // creates a set with four names in it. - var names = new Ember.Set(["Charles", "Tom", "Juan", "Alex"]); // :P + loaded[name] = object; - // creates a copy of the names set. - var namesCopy = new Ember.Set(names); + if (hooks = loadHooks[name]) { + loadHooks[name].forEach(function(callback) { + callback(object); + }); + } +}; - // same as above. - var anotherNamesCopy = names.copy(); +})(); - ## Adding/Removing Objects - You generally add or remove objects from a set using `add()` or - `remove()`. You can add any type of object including primitives such as - numbers, strings, and booleans. - Unlike arrays, objects can only exist one time in a set. If you call `add()` - on a set with the same object multiple times, the object will only be added - once. Likewise, calling `remove()` with the same object multiple times will - remove the object the first time and have no effect on future calls until - you add the object to the set again. +(function() { - NOTE: You cannot add/remove null or undefined to a set. Any attempt to do so - will be ignored. +})(); - In addition to add/remove you can also call `push()`/`pop()`. Push behaves - just like `add()` but `pop()`, unlike `remove()` will pick an arbitrary - object, remove it and return it. This is a good way to use a set as a job - queue when you don't care which order the jobs are executed in. - ## Testing for an Object - To test for an object's presence in a set you simply call - `Ember.Set#contains()`. +(function() { +var get = Ember.get; - ## Observing changes +/** +@module ember +@submodule ember-runtime +*/ - When using `Ember.Set`, you can observe the `"[]"` property to be - alerted whenever the content changes. You can also add an enumerable - observer to the set to be notified of specific objects that are added and - removed from the set. See `Ember.Enumerable` for more information on - enumerables. +/** + `Ember.ControllerMixin` provides a standard interface for all classes that + compose Ember's controller layer: `Ember.Controller`, + `Ember.ArrayController`, and `Ember.ObjectController`. - This is often unhelpful. If you are filtering sets of objects, for instance, - it is very inefficient to re-filter all of the items each time the set - changes. It would be better if you could just adjust the filtered set based - on what was changed on the original set. The same issue applies to merging - sets, as well. + Within an `Ember.Router`-managed application single shared instaces of every + Controller object in your application's namespace will be added to the + application's `Ember.Router` instance. See `Ember.Application#initialize` + for additional information. - ## Other Methods + ## Views - `Ember.Set` primary implements other mixin APIs. For a complete reference - on the methods you will use with `Ember.Set`, please consult these mixins. - The most useful ones will be `Ember.Enumerable` and - `Ember.MutableEnumerable` which implement most of the common iterator - methods you are used to on Array. + By default a controller instance will be the rendering context + for its associated `Ember.View.` This connection is made during calls to + `Ember.ControllerMixin#connectOutlet`. - Note that you can also use the `Ember.Copyable` and `Ember.Freezable` - APIs on `Ember.Set` as well. Once a set is frozen it can no longer be - modified. The benefit of this is that when you call frozenCopy() on it, - Ember will avoid making copies of the set. This allows you to write - code that can know with certainty when the underlying set data will or - will not be modified. + Within the view's template, the `Ember.View` instance can be accessed + through the controller with `{{view}}`. - @class Set + ## Target Forwarding + + By default a controller will target your application's `Ember.Router` + instance. Calls to `{{action}}` within the template of a controller's view + are forwarded to the router. See `Ember.Handlebars.helpers.action` for + additional information. + + @class ControllerMixin @namespace Ember - @extends Ember.CoreObject - @uses Ember.MutableEnumerable - @uses Ember.Copyable - @uses Ember.Freezable - @since Ember 0.9 + @extends Ember.Mixin */ -Ember.Set = Ember.CoreObject.extend(Ember.MutableEnumerable, Ember.Copyable, Ember.Freezable, - /** @scope Ember.Set.prototype */ { +Ember.ControllerMixin = Ember.Mixin.create({ + /** + The object to which events from the view should be sent. - // .......................................................... - // IMPLEMENT ENUMERABLE APIS - // + For example, when a Handlebars template uses the `{{action}}` helper, + it will attempt to send the event to the view's controller's `target`. - /** - This property will change as the number of objects in the set changes. + By default, a controller's `target` is set to the router after it is + instantiated by `Ember.Application#initialize`. - @property length - @type number - @default 0 + @property target + @default null */ - length: 0, + target: null, - /** - Clears the set. This is useful if you want to reuse an existing set - without having to recreate it. + container: null, - var colors = new Ember.Set(["red", "green", "blue"]); - colors.length; => 3 - colors.clear(); - colors.length; => 0 + store: null, - @method clear - @return {Ember.Set} An empty Set - */ - clear: function() { - if (this.isFrozen) { throw new Error(Ember.FROZEN_ERROR); } + send: function(actionName) { + var args = [].slice.call(arguments, 1), target; - var len = get(this, 'length'); - if (len === 0) { return this; } + if (this[actionName]) { + Ember.assert("The controller " + this + " does not have the action " + actionName, typeof this[actionName] === 'function'); + this[actionName].apply(this, args); + } else if(target = get(this, 'target')) { + Ember.assert("The target for controller " + this + " (" + target + ") did not define a `send` method", typeof target.send === 'function'); + target.send.apply(target, arguments); + } + } +}); - var guid; +/** + @class Controller + @namespace Ember + @extends Ember.Object + @uses Ember.ControllerMixin +*/ +Ember.Controller = Ember.Object.extend(Ember.ControllerMixin); - this.enumerableContentWillChange(len, 0); - Ember.propertyWillChange(this, 'firstObject'); - Ember.propertyWillChange(this, 'lastObject'); +})(); - for (var i=0; i < len; i++){ - guid = guidFor(this[i]); - delete this[guid]; - delete this[i]; - } - set(this, 'length', 0); - Ember.propertyDidChange(this, 'firstObject'); - Ember.propertyDidChange(this, 'lastObject'); - this.enumerableContentDidChange(len, 0); +(function() { +/** +@module ember +@submodule ember-runtime +*/ - return this; - }, +var get = Ember.get, set = Ember.set, forEach = Ember.EnumerableUtils.forEach; - /** - Returns true if the passed object is also an enumerable that contains the - same objects as the receiver. +/** + `Ember.SortableMixin` provides a standard interface for array proxies + to specify a sort order and maintain this sorting when objects are added, + removed, or updated without changing the implicit order of their underlying + content array: - var colors = ["red", "green", "blue"], - same_colors = new Ember.Set(colors); - same_colors.isEqual(colors); => true - same_colors.isEqual(["purple", "brown"]); => false + ```javascript + songs = [ + {trackNumber: 4, title: 'Ob-La-Di, Ob-La-Da'}, + {trackNumber: 2, title: 'Back in the U.S.S.R.'}, + {trackNumber: 3, title: 'Glass Onion'}, + ]; - @method isEqual - @param {Ember.Set} obj the other object. - @return {Boolean} - */ - isEqual: function(obj) { - // fail fast - if (!Ember.Enumerable.detect(obj)) return false; + songsController = Ember.ArrayController.create({ + content: songs, + sortProperties: ['trackNumber'] + }); - var loc = get(this, 'length'); - if (get(obj, 'length') !== loc) return false; + songsController.get('firstObject'); // {trackNumber: 2, title: 'Back in the U.S.S.R.'} - while(--loc >= 0) { - if (!obj.contains(this[loc])) return false; - } + songsController.addObject({trackNumber: 1, title: 'Dear Prudence'}); + songsController.get('firstObject'); // {trackNumber: 1, title: 'Dear Prudence'} + ``` - return true; + @class SortableMixin + @namespace Ember + @extends Ember.Mixin + @uses Ember.MutableEnumerable +*/ +Ember.SortableMixin = Ember.Mixin.create(Ember.MutableEnumerable, { + sortProperties: null, + sortAscending: true, + + orderBy: function(item1, item2) { + var result = 0, + sortProperties = get(this, 'sortProperties'), + sortAscending = get(this, 'sortAscending'); + + Ember.assert("you need to define `sortProperties`", !!sortProperties); + + forEach(sortProperties, function(propertyName) { + if (result === 0) { + result = Ember.compare(get(item1, propertyName), get(item2, propertyName)); + if ((result !== 0) && !sortAscending) { + result = (-1) * result; + } + } + }); + + return result; }, - /** - Adds an object to the set. Only non-null objects can be added to a set - and those can only be added once. If the object is already in the set or - the passed value is null this method will have no effect. + destroy: function() { + var content = get(this, 'content'), + sortProperties = get(this, 'sortProperties'); - This is an alias for `Ember.MutableEnumerable.addObject()`. + if (content && sortProperties) { + forEach(content, function(item) { + forEach(sortProperties, function(sortProperty) { + Ember.removeObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); + }, this); + }, this); + } - var colors = new Ember.Set(); - colors.add("blue"); => ["blue"] - colors.add("blue"); => ["blue"] - colors.add("red"); => ["blue", "red"] - colors.add(null); => ["blue", "red"] - colors.add(undefined); => ["blue", "red"] + return this._super(); + }, - @method add - @param {Object} obj The object to add. - @return {Ember.Set} The set itself. - */ - add: Ember.alias('addObject'), + isSorted: Ember.computed('sortProperties', function() { + return !!get(this, 'sortProperties'); + }), - /** - Removes the object from the set if it is found. If you pass a null value - or an object that is already not in the set, this method will have no - effect. This is an alias for `Ember.MutableEnumerable.removeObject()`. + arrangedContent: Ember.computed('content', 'sortProperties.@each', function(key, value) { + var content = get(this, 'content'), + isSorted = get(this, 'isSorted'), + sortProperties = get(this, 'sortProperties'), + self = this; - var colors = new Ember.Set(["red", "green", "blue"]); - colors.remove("red"); => ["blue", "green"] - colors.remove("purple"); => ["blue", "green"] - colors.remove(null); => ["blue", "green"] + if (content && isSorted) { + content = content.slice(); + content.sort(function(item1, item2) { + return self.orderBy(item1, item2); + }); + forEach(content, function(item) { + forEach(sortProperties, function(sortProperty) { + Ember.addObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); + }, this); + }, this); + return Ember.A(content); + } - @method remove - @param {Object} obj The object to remove - @return {Ember.Set} The set itself. - */ - remove: Ember.alias('removeObject'), + return content; + }), - /** - Removes the last element from the set and returns it, or null if it's empty. + _contentWillChange: Ember.beforeObserver(function() { + var content = get(this, 'content'), + sortProperties = get(this, 'sortProperties'); - var colors = new Ember.Set(["green", "blue"]); - colors.pop(); => "blue" - colors.pop(); => "green" - colors.pop(); => null + if (content && sortProperties) { + forEach(content, function(item) { + forEach(sortProperties, function(sortProperty) { + Ember.removeObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); + }, this); + }, this); + } - @method pop - @return {Object} The removed object from the set or null. - */ - pop: function() { - if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); - var obj = this.length > 0 ? this[this.length-1] : null; - this.remove(obj); - return obj; - }, + this._super(); + }, 'content'), - /** - Inserts the given object on to the end of the set. It returns - the set itself. + sortAscendingWillChange: Ember.beforeObserver(function() { + this._lastSortAscending = get(this, 'sortAscending'); + }, 'sortAscending'), - This is an alias for `Ember.MutableEnumerable.addObject()`. + sortAscendingDidChange: Ember.observer(function() { + if (get(this, 'sortAscending') !== this._lastSortAscending) { + var arrangedContent = get(this, 'arrangedContent'); + arrangedContent.reverseObjects(); + } + }, 'sortAscending'), - var colors = new Ember.Set(); - colors.push("red"); => ["red"] - colors.push("green"); => ["red", "green"] - colors.push("blue"); => ["red", "green", "blue"] + contentArrayWillChange: function(array, idx, removedCount, addedCount) { + var isSorted = get(this, 'isSorted'); - @method push - @return {Ember.Set} The set itself. - */ - push: Ember.alias('addObject'), + if (isSorted) { + var arrangedContent = get(this, 'arrangedContent'); + var removedObjects = array.slice(idx, idx+removedCount); + var sortProperties = get(this, 'sortProperties'); - /** - Removes the last element from the set and returns it, or null if it's empty. + forEach(removedObjects, function(item) { + arrangedContent.removeObject(item); - This is an alias for `Ember.Set.pop()`. + forEach(sortProperties, function(sortProperty) { + Ember.removeObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); + }, this); + }, this); + } - var colors = new Ember.Set(["green", "blue"]); - colors.shift(); => "blue" - colors.shift(); => "green" - colors.shift(); => null + return this._super(array, idx, removedCount, addedCount); + }, - @method shift - @return {Object} The removed object from the set or null. - */ - shift: Ember.alias('pop'), + contentArrayDidChange: function(array, idx, removedCount, addedCount) { + var isSorted = get(this, 'isSorted'), + sortProperties = get(this, 'sortProperties'); - /** - Inserts the given object on to the end of the set. It returns - the set itself. + if (isSorted) { + var addedObjects = array.slice(idx, idx+addedCount); + var arrangedContent = get(this, 'arrangedContent'); - This is an alias of `Ember.Set.push()` + forEach(addedObjects, function(item) { + this.insertItemSorted(item); - var colors = new Ember.Set(); - colors.unshift("red"); => ["red"] - colors.unshift("green"); => ["red", "green"] - colors.unshift("blue"); => ["red", "green", "blue"] + forEach(sortProperties, function(sortProperty) { + Ember.addObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); + }, this); + }, this); + } - @method unshift - @return {Ember.Set} The set itself. - */ - unshift: Ember.alias('push'), + return this._super(array, idx, removedCount, addedCount); + }, - /** - Adds each object in the passed enumerable to the set. + insertItemSorted: function(item) { + var arrangedContent = get(this, 'arrangedContent'); + var length = get(arrangedContent, 'length'); - This is an alias of `Ember.MutableEnumerable.addObjects()` + var idx = this._binarySearch(item, 0, length); + arrangedContent.insertAt(idx, item); + }, - var colors = new Ember.Set(); - colors.addEach(["red", "green", "blue"]); => ["red", "green", "blue"] + contentItemSortPropertyDidChange: function(item) { + var arrangedContent = get(this, 'arrangedContent'), + oldIndex = arrangedContent.indexOf(item), + leftItem = arrangedContent.objectAt(oldIndex - 1), + rightItem = arrangedContent.objectAt(oldIndex + 1), + leftResult = leftItem && this.orderBy(item, leftItem), + rightResult = rightItem && this.orderBy(item, rightItem); - @method addEach - @param {Ember.Enumerable} objects the objects to add. - @return {Ember.Set} The set itself. - */ - addEach: Ember.alias('addObjects'), + if (leftResult < 0 || rightResult > 0) { + arrangedContent.removeObject(item); + this.insertItemSorted(item); + } + }, - /** - Removes each object in the passed enumerable to the set. + _binarySearch: function(item, low, high) { + var mid, midItem, res, arrangedContent; - This is an alias of `Ember.MutableEnumerable.removeObjects()` + if (low === high) { + return low; + } - var colors = new Ember.Set(["red", "green", "blue"]); - colors.removeEach(["red", "blue"]); => ["green"] + arrangedContent = get(this, 'arrangedContent'); - @method removeEach - @param {Ember.Enumerable} objects the objects to remove. - @return {Ember.Set} The set itself. - */ - removeEach: Ember.alias('removeObjects'), + mid = low + Math.floor((high - low) / 2); + midItem = arrangedContent.objectAt(mid); - // .......................................................... - // PRIVATE ENUMERABLE SUPPORT - // + res = this.orderBy(midItem, item); - init: function(items) { - this._super(); - if (items) this.addObjects(items); - }, + if (res < 0) { + return this._binarySearch(item, mid+1, high); + } else if (res > 0) { + return this._binarySearch(item, low, mid); + } - // implement Ember.Enumerable - nextObject: function(idx) { - return this[idx]; - }, + return mid; + } +}); - // more optimized version - firstObject: Ember.computed(function() { - return this.length > 0 ? this[0] : undefined; - }).property().cacheable(), +})(); - // more optimized version - lastObject: Ember.computed(function() { - return this.length > 0 ? this[this.length-1] : undefined; - }).property().cacheable(), - // implements Ember.MutableEnumerable - addObject: function(obj) { - if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); - if (none(obj)) return this; // nothing to do - var guid = guidFor(obj), - idx = this[guid], - len = get(this, 'length'), - added ; +(function() { +/** +@module ember +@submodule ember-runtime +*/ - if (idx>=0 && idx=0 && idx{{title}} ({{titleLength}} characters) + {{/each}} + ``` - delete this[guid]; - delete this[len-1]; - set(this, 'length', len-1); + ```javascript + App.PostsController = Ember.ArrayController.extend({ + itemController: 'post' + }); - if (isFirst) { Ember.propertyDidChange(this, 'firstObject'); } - if (isLast) { Ember.propertyDidChange(this, 'lastObject'); } - this.enumerableContentDidChange(removed, null); - } + App.PostController = Ember.ObjectController.extend({ + // the `title` property will be proxied to the underlying post. - return this; - }, + titleLength: function() { + return this.get('title').length; + }.property('title') + }); + ``` - // optimized version - contains: function(obj) { - return this[guidFor(obj)]>=0; - }, + In some cases it is helpful to return a different `itemController` depending + on the particular item. Subclasses can do this by overriding + `lookupItemController`. - copy: function() { - var C = this.constructor, ret = new C(), loc = get(this, 'length'); - set(ret, 'length', loc); - while(--loc>=0) { - ret[loc] = this[loc]; - ret[guidFor(this[loc])] = loc; - } - return ret; - }, + For example: - toString: function() { - var len = this.length, idx, array = []; - for(idx = 0; idx < len; idx++) { - array[idx] = this[idx]; + ```javascript + App.MyArrayController = Ember.ArrayController.extend({ + lookupItemController: function( object ) { + if (object.get('isSpecial')) { + return "special"; // use App.SpecialController + } else { + return "regular"; // use App.RegularController + } } - return "Ember.Set<%@>".fmt(array.join(',')); - } - -}); + }); + ``` -})(); + @class ArrayController + @namespace Ember + @extends Ember.ArrayProxy + @uses Ember.SortableMixin + @uses Ember.ControllerMixin +*/ +Ember.ArrayController = Ember.ArrayProxy.extend(Ember.ControllerMixin, + Ember.SortableMixin, { + /** + The controller used to wrap items, if any. -(function() { -/** -@module ember -@submodule ember-runtime -*/ + @property itemController + @type String + @default null + */ + itemController: null, -/** - `Ember.Object` is the main base class for all Ember objects. It is a subclass - of `Ember.CoreObject` with the `Ember.Observable` mixin applied. For details, - see the documentation for each of these. + /** + Return the name of the controller to wrap items, or `null` if items should + be returned directly. The default implementation simply returns the + `itemController` property, but subclasses can override this method to return + different controllers for different objects. - @class Object - @namespace Ember - @extends Ember.CoreObject - @uses Ember.Observable -*/ -Ember.Object = Ember.CoreObject.extend(Ember.Observable); + For example: -})(); + ```javascript + App.MyArrayController = Ember.ArrayController.extend({ + lookupItemController: function( object ) { + if (object.get('isSpecial')) { + return "special"; // use App.SpecialController + } else { + return "regular"; // use App.RegularController + } + } + }); + ``` + @method + @type String + @default null + */ + lookupItemController: function(object) { + return get(this, 'itemController'); + }, + objectAtContent: function(idx) { + var length = get(this, 'length'), + object = get(this,'arrangedContent').objectAt(idx), + controllerClass = this.lookupItemController(object); -(function() { -/** -@module ember -@submodule ember-runtime -*/ + if (controllerClass && idx < length) { + return this.controllerAt(idx, object, controllerClass); + } else { + // When controllerClass is falsy we have not opted in to using item + // controllers, so return the object directly. However, when + // controllerClass is defined but the index is out of range, we want to + // return the "out of range" value, whatever that might be. Rather than + // make assumptions (e.g. guessing `null` or `undefined`) we defer this to + // `arrangedContent`. + return object; + } + }, -var indexOf = Ember.ArrayPolyfills.indexOf; + arrangedContentDidChange: function() { + this._super(); + this._resetSubContainers(); + }, -/** - A Namespace is an object usually used to contain other objects or methods - such as an application or framework. Create a namespace anytime you want - to define one of these new containers. + arrayContentDidChange: function(idx, removedCnt, addedCnt) { + var subContainers = get(this, 'subContainers'), + subContainersToRemove = subContainers.slice(idx, idx+removedCnt); - # Example Usage + forEach(subContainersToRemove, function(subContainer) { + if (subContainer) { subContainer.destroy(); } + }); - MyFramework = Ember.Namespace.create({ - VERSION: '1.0.0' - }); + replace(subContainers, idx, removedCnt, new Array(addedCnt)); - @class Namespace - @namespace Ember - @extends Ember.Object -*/ -Ember.Namespace = Ember.Object.extend({ - isNamespace: true, + // The shadow array of subcontainers must be updated before we trigger + // observers, otherwise observers will get the wrong subcontainer when + // calling `objectAt` + this._super(idx, removedCnt, addedCnt); + }, init: function() { - Ember.Namespace.NAMESPACES.push(this); - Ember.Namespace.PROCESSED = false; + this._super(); + this._resetSubContainers(); }, - toString: function() { - Ember.identifyNamespaces(); - return this[Ember.GUID_KEY+'_name']; + controllerAt: function(idx, object, controllerClass) { + var container = get(this, 'container'), + subContainers = get(this, 'subContainers'), + subContainer = subContainers[idx], + controller; + + if (!subContainer) { + subContainer = subContainers[idx] = container.child(); + } + + controller = subContainer.lookup("controller:" + controllerClass); + if (!controller) { + throw new Error('Could not resolve itemController: "' + controllerClass + '"'); + } + + controller.set('target', this); + controller.set('content', object); + + return controller; }, - destroy: function() { - var namespaces = Ember.Namespace.NAMESPACES; - window[this.toString()] = undefined; - namespaces.splice(indexOf.call(namespaces, this), 1); - this._super(); + subContainers: null, + + _resetSubContainers: function() { + var subContainers = get(this, 'subContainers'); + + if (subContainers) { + forEach(subContainers, function(subContainer) { + if (subContainer) { subContainer.destroy(); } + }); + } + + this.set('subContainers', Ember.A()); } }); -Ember.Namespace.NAMESPACES = [Ember]; -Ember.Namespace.PROCESSED = false; - })(); @@ -9431,31 +12393,26 @@ Ember.Namespace.PROCESSED = false; */ /** - Defines a namespace that will contain an executable application. This is - very similar to a normal namespace except that it is expected to include at - least a 'ready' function which can be run to initialize the application. + `Ember.ObjectController` is part of Ember's Controller layer. A single shared + instance of each `Ember.ObjectController` subclass in your application's + namespace will be created at application initialization and be stored on your + application's `Ember.Router` instance. - Currently Ember.Application is very similar to Ember.Namespace. However, this - class may be augmented by additional frameworks so it is important to use - this instance when building new applications. + `Ember.ObjectController` derives its functionality from its superclass + `Ember.ObjectProxy` and the `Ember.ControllerMixin` mixin. - # Example Usage + @class ObjectController + @namespace Ember + @extends Ember.ObjectProxy + @uses Ember.ControllerMixin +**/ +Ember.ObjectController = Ember.ObjectProxy.extend(Ember.ControllerMixin); - MyApp = Ember.Application.create({ - VERSION: '1.0.0', - store: Ember.Store.create().from(Ember.fixtures) - }); +})(); - MyApp.ready = function() { - //..init code goes here... - } - @class Application - @namespace Ember - @extends Ember.Namespace -*/ -Ember.Application = Ember.Namespace.extend(); +(function() { })(); @@ -9463,236 +12420,189 @@ Ember.Application = Ember.Namespace.extend(); (function() { /** +Ember Runtime + @module ember @submodule ember-runtime +@requires ember-metal */ +})(); -var get = Ember.get, set = Ember.set; - +(function() { /** - An ArrayProxy wraps any other object that implements Ember.Array and/or - Ember.MutableArray, forwarding all requests. This makes it very useful for - a number of binding use cases or other cases where being able to swap - out the underlying array is useful. - - A simple example of usage: - - var pets = ['dog', 'cat', 'fish']; - var ap = Ember.ArrayProxy.create({ content: Ember.A(pets) }); - ap.get('firstObject'); // => 'dog' - ap.set('content', ['amoeba', 'paramecium']); - ap.get('firstObject'); // => 'amoeba' - - This class can also be useful as a layer to transform the contents of - an array, as they are accessed. This can be done by overriding - `objectAtContent`: +@module ember +@submodule ember-views +*/ - var pets = ['dog', 'cat', 'fish']; - var ap = Ember.ArrayProxy.create({ - content: Ember.A(pets), - objectAtContent: function(idx) { - return this.get('content').objectAt(idx).toUpperCase(); - } - }); - ap.get('firstObject'); // => 'DOG' +var jQuery = Ember.imports.jQuery; +Ember.assert("Ember Views require jQuery 1.7 (>= 1.7.2), 1.8 or 1.9", jQuery && (jQuery().jquery.match(/^1\.(7(?!$)(?!\.[01])|8|9)(\.\d+)?(pre|rc\d?)?/) || Ember.ENV.FORCE_JQUERY)); +/** + Alias for jQuery - @class ArrayProxy - @namespace Ember - @extends Ember.Object - @uses Ember.MutableArray + @method $ + @for Ember */ -Ember.ArrayProxy = Ember.Object.extend(Ember.MutableArray, -/** @scope Ember.ArrayProxy.prototype */ { - - /** - The content array. Must be an object that implements Ember.Array and/or - Ember.MutableArray. +Ember.$ = jQuery; - @property content - @type Ember.Array - */ - content: null, - - /** - The array that the proxy pretends to be. In the default `ArrayProxy` - implementation, this and `content` are the same. Subclasses of `ArrayProxy` - can override this property to provide things like sorting and filtering. - - @property arrangedContent - */ - arrangedContent: Ember.computed('content', function() { - return get(this, 'content'); - }).cacheable(), +})(); - /** - Should actually retrieve the object at the specified index from the - content. You can override this method in subclasses to transform the - content item to something new. - This method will only be called if content is non-null. - @method objectAtContent - @param {Number} idx The index to retrieve. - @return {Object} the value or undefined if none found - */ - objectAtContent: function(idx) { - return get(this, 'arrangedContent').objectAt(idx); - }, +(function() { +/** +@module ember +@submodule ember-views +*/ - /** - Should actually replace the specified objects on the content array. - You can override this method in subclasses to transform the content item - into something new. +// http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#dndevents +var dragEvents = Ember.String.w('dragstart drag dragenter dragleave dragover drop dragend'); - This method will only be called if content is non-null. +// Copies the `dataTransfer` property from a browser event object onto the +// jQuery event object for the specified events +Ember.EnumerableUtils.forEach(dragEvents, function(eventName) { + Ember.$.event.fixHooks[eventName] = { props: ['dataTransfer'] }; +}); - @method replaceContent - @param {Number} idx The starting index - @param {Number} amt The number of items to remove from the content. - @param {Array} objects Optional array of objects to insert or null if no objects. - @return {void} - */ - replaceContent: function(idx, amt, objects) { - get(this, 'arrangedContent').replace(idx, amt, objects); - }, +})(); - /** - @private - Invoked when the content property is about to change. Notifies observers that the - entire array content will change. - @method _contentWillChange - */ - _contentWillChange: Ember.beforeObserver(function() { - this._teardownContent(); - }, 'content'), +(function() { +/** +@module ember +@submodule ember-views +*/ - _teardownContent: function() { - var content = get(this, 'content'); +/*** BEGIN METAMORPH HELPERS ***/ - if (content) { - content.removeArrayObserver(this, { - willChange: 'contentArrayWillChange', - didChange: 'contentArrayDidChange' - }); - } - }, +// 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 +// the first node an invisible text node. We, like Modernizr, use ­ +var needsShy = (function(){ + var testEl = document.createElement('div'); + testEl.innerHTML = "
"; + testEl.firstChild.innerHTML = ""; + return testEl.firstChild.innerHTML === ''; +})(); - contentArrayWillChange: Ember.K, - contentArrayDidChange: Ember.K, +// IE 8 (and likely earlier) likes to move whitespace preceeding +// a script tag to appear after it. This means that we can +// accidentally remove whitespace when updating a morph. +var movesWhitespace = (function() { + var testEl = document.createElement('div'); + testEl.innerHTML = "Test: Value"; + return testEl.childNodes[0].nodeValue === 'Test:' && + testEl.childNodes[2].nodeValue === ' Value'; +})(); - /** - @private +// Use this to find children by ID instead of using jQuery +var findChildById = function(element, id) { + if (element.getAttribute('id') === id) { return element; } - Invoked when the content property changes. Notifies observers that the - entire array content has changed. + var len = element.childNodes.length, idx, node, found; + for (idx=0; idx 0) { + var len = matches.length, idx; + for (idx=0; idxTest'); + canSet = el.options.length === 1; + } - this._setupArrangedContent(); + innerHTMLTags[tagName] = canSet; - this.arrangedContentDidChange(this); - this.arrangedContentArrayDidChange(this, 0, undefined, len); - }, 'arrangedContent'), + return canSet; +}; - _setupArrangedContent: function() { - var arrangedContent = get(this, 'arrangedContent'); +var setInnerHTML = function(element, html) { + var tagName = element.tagName; - if (arrangedContent) { - arrangedContent.addArrayObserver(this, { - willChange: 'arrangedContentArrayWillChange', - didChange: 'arrangedContentArrayDidChange' - }); - } - }, + if (canSetInnerHTML(tagName)) { + setInnerHTMLWithoutFix(element, html); + } else { + Ember.assert("Can't set innerHTML on "+element.tagName+" in this browser", element.outerHTML); - _teardownArrangedContent: function() { - var arrangedContent = get(this, 'arrangedContent'); + var startTag = element.outerHTML.match(new RegExp("<"+tagName+"([^>]*)>", 'i'))[0], + endTag = ''; - if (arrangedContent) { - arrangedContent.removeArrayObserver(this, { - willChange: 'arrangedContentArrayWillChange', - didChange: 'arrangedContentArrayDidChange' - }); + var wrapper = document.createElement('div'); + setInnerHTMLWithoutFix(wrapper, startTag + html + endTag); + element = wrapper.firstChild; + while (element.tagName !== tagName) { + element = element.nextSibling; } - }, - - arrangedContentWillChange: Ember.K, - arrangedContentDidChange: Ember.K, - - objectAt: function(idx) { - return get(this, 'content') && this.objectAtContent(idx); - }, - - length: Ember.computed(function() { - var arrangedContent = get(this, 'arrangedContent'); - return arrangedContent ? get(arrangedContent, 'length') : 0; - // No dependencies since Enumerable notifies length of change - }).property().cacheable(), - - replace: function(idx, amt, objects) { - if (get(this, 'content')) this.replaceContent(idx, amt, objects); - return this; - }, - - arrangedContentArrayWillChange: function(item, idx, removedCnt, addedCnt) { - this.arrayContentWillChange(idx, removedCnt, addedCnt); - }, - - arrangedContentArrayDidChange: function(item, idx, removedCnt, addedCnt) { - this.arrayContentDidChange(idx, removedCnt, addedCnt); - }, - - init: function() { - this._super(); - this._setupContent(); - this._setupArrangedContent(); - }, - - willDestroy: function() { - this._teardownArrangedContent(); - this._teardownContent(); } -}); + return element; +}; + +function isSimpleClick(event) { + var modifier = event.shiftKey || event.metaKey || event.altKey || event.ctrlKey, + secondaryClick = event.which > 1; // IE9 may return undefined + + return !modifier && !secondaryClick; +} + +Ember.ViewUtils = { + setInnerHTML: setInnerHTML, + isSimpleClick: isSimpleClick +}; })(); @@ -9701,488 +12611,417 @@ Ember.ArrayProxy = Ember.Object.extend(Ember.MutableArray, (function() { /** @module ember -@submodule ember-runtime +@submodule ember-views */ -var get = Ember.get, - set = Ember.set, - fmt = Ember.String.fmt, - addBeforeObserver = Ember.addBeforeObserver, - addObserver = Ember.addObserver, - removeBeforeObserver = Ember.removeBeforeObserver, - removeObserver = Ember.removeObserver, - propertyWillChange = Ember.propertyWillChange, - propertyDidChange = Ember.propertyDidChange; - -function contentPropertyWillChange(content, contentKey) { - var key = contentKey.slice(8); // remove "content." - if (key in this) { return; } // if shadowed in proxy - propertyWillChange(this, key); -} - -function contentPropertyDidChange(content, contentKey) { - var key = contentKey.slice(8); // remove "content." - if (key in this) { return; } // if shadowed in proxy - propertyDidChange(this, key); -} +var get = Ember.get, set = Ember.set; +var indexOf = Ember.ArrayPolyfills.indexOf; -/** - `Ember.ObjectProxy` forwards all properties not defined by the proxy itself - to a proxied `content` object. - object = Ember.Object.create({ - name: 'Foo' - }); - proxy = Ember.ObjectProxy.create({ - content: object - }); - // Access and change existing properties - proxy.get('name') // => 'Foo' - proxy.set('name', 'Bar'); - object.get('name') // => 'Bar' - // Create new 'description' property on `object` - proxy.set('description', 'Foo is a whizboo baz'); - object.get('description') // => 'Foo is a whizboo baz' - While `content` is unset, setting a property to be delegated will throw an Error. +var ClassSet = function() { + this.seen = {}; + this.list = []; +}; - proxy = Ember.ObjectProxy.create({ - content: null, - flag: null - }); - proxy.set('flag', true); - proxy.get('flag'); // => true - proxy.get('foo'); // => undefined - proxy.set('foo', 'data'); // throws Error +ClassSet.prototype = { + add: function(string) { + if (string in this.seen) { return; } + this.seen[string] = true; - Delegated properties can be bound to and will change when content is updated. + this.list.push(string); + }, - Computed properties on the proxy itself can depend on delegated properties. + toDOM: function() { + return this.list.join(" "); + } +}; - ProxyWithComputedProperty = Ember.ObjectProxy.extend({ - fullName: function () { - var firstName = this.get('firstName'), - lastName = this.get('lastName'); - if (firstName && lastName) { - return firstName + ' ' + lastName; - } - return firstName || lastName; - }.property('firstName', 'lastName') - }); - proxy = ProxyWithComputedProperty.create(); - proxy.get('fullName'); => undefined - proxy.set('content', { - firstName: 'Tom', lastName: 'Dale' - }); // triggers property change for fullName on proxy - proxy.get('fullName'); => 'Tom Dale' +/** + `Ember.RenderBuffer` gathers information regarding the a view and generates the + final representation. `Ember.RenderBuffer` will generate HTML which can be pushed + to the DOM. - @class ObjectProxy + @class RenderBuffer @namespace Ember - @extends Ember.Object + @constructor */ -Ember.ObjectProxy = Ember.Object.extend( -/** @scope Ember.ObjectProxy.prototype */ { - /** - The object whose properties will be forwarded. - - @property content - @type Ember.Object - @default null - */ - content: null, - _contentDidChange: Ember.observer(function() { - Ember.assert("Can't set ObjectProxy's content to itself", this.get('content') !== this); - }, 'content'), - - willWatchProperty: function (key) { - var contentKey = 'content.' + key; - addBeforeObserver(this, contentKey, null, contentPropertyWillChange); - addObserver(this, contentKey, null, contentPropertyDidChange); - }, - - didUnwatchProperty: function (key) { - var contentKey = 'content.' + key; - removeBeforeObserver(this, contentKey, null, contentPropertyWillChange); - removeObserver(this, contentKey, null, contentPropertyDidChange); - }, +Ember.RenderBuffer = function(tagName) { + return new Ember._RenderBuffer(tagName); +}; - unknownProperty: function (key) { - var content = get(this, 'content'); - if (content) { - return get(content, key); - } - }, +Ember._RenderBuffer = function(tagName) { + this.tagNames = [tagName || null]; + this.buffer = []; +}; - setUnknownProperty: function (key, value) { - var content = get(this, 'content'); - Ember.assert(fmt("Cannot delegate set('%@', %@) to the 'content' property of object proxy %@: its 'content' is undefined.", [key, value, this]), content); - return set(content, key, value); - } -}); +Ember._RenderBuffer.prototype = +/** @scope Ember.RenderBuffer.prototype */ { -})(); + // The root view's element + _element: null, + /** + @private + An internal set used to de-dupe class names when `addClass()` is + used. After each call to `addClass()`, the `classes` property + will be updated. -(function() { -/** -@module ember -@submodule ember-runtime -*/ + @property elementClasses + @type Array + @default [] + */ + elementClasses: null, + /** + Array of class names which will be applied in the class attribute. -var set = Ember.set, get = Ember.get, guidFor = Ember.guidFor; -var forEach = Ember.EnumerableUtils.forEach; + You can use `setClasses()` to set this property directly. If you + use `addClass()`, it will be maintained for you. -var EachArray = Ember.Object.extend(Ember.Array, { + @property classes + @type Array + @default [] + */ + classes: null, - init: function(content, keyName, owner) { - this._super(); - this._keyName = keyName; - this._owner = owner; - this._content = content; - }, + /** + The id in of the element, to be applied in the id attribute. - objectAt: function(idx) { - var item = this._content.objectAt(idx); - return item && get(item, this._keyName); - }, + You should not set this property yourself, rather, you should use + the `id()` method of `Ember.RenderBuffer`. - length: Ember.computed(function() { - var content = this._content; - return content ? get(content, 'length') : 0; - }).property().cacheable() + @property elementId + @type String + @default null + */ + elementId: null, -}); + /** + A hash keyed on the name of the attribute and whose value will be + applied to that attribute. For example, if you wanted to apply a + `data-view="Foo.bar"` property to an element, you would set the + elementAttributes hash to `{'data-view':'Foo.bar'}`. -var IS_OBSERVER = /^.+:(before|change)$/; + You should not maintain this hash yourself, rather, you should use + the `attr()` method of `Ember.RenderBuffer`. -function addObserverForContentKey(content, keyName, proxy, idx, loc) { - var objects = proxy._objects, guid; - if (!objects) objects = proxy._objects = {}; + @property elementAttributes + @type Hash + @default {} + */ + elementAttributes: null, - while(--loc>=idx) { - var item = content.objectAt(loc); - if (item) { - Ember.addBeforeObserver(item, keyName, proxy, 'contentKeyWillChange'); - Ember.addObserver(item, keyName, proxy, 'contentKeyDidChange'); + /** + The tagname of the element an instance of `Ember.RenderBuffer` represents. - // keep track of the indicies each item was found at so we can map - // it back when the obj changes. - guid = guidFor(item); - if (!objects[guid]) objects[guid] = []; - objects[guid].push(loc); - } - } -} + Usually, this gets set as the first parameter to `Ember.RenderBuffer`. For + example, if you wanted to create a `p` tag, then you would call -function removeObserverForContentKey(content, keyName, proxy, idx, loc) { - var objects = proxy._objects; - if (!objects) objects = proxy._objects = {}; - var indicies, guid; + ```javascript + Ember.RenderBuffer('p') + ``` - while(--loc>=idx) { - var item = content.objectAt(loc); - if (item) { - Ember.removeBeforeObserver(item, keyName, proxy, 'contentKeyWillChange'); - Ember.removeObserver(item, keyName, proxy, 'contentKeyDidChange'); + @property elementTag + @type String + @default null + */ + elementTag: null, - guid = guidFor(item); - indicies = objects[guid]; - indicies[indicies.indexOf(loc)] = null; - } - } -} + /** + A hash keyed on the name of the style attribute and whose value will + be applied to that attribute. For example, if you wanted to apply a + `background-color:black;` style to an element, you would set the + elementStyle hash to `{'background-color':'black'}`. -/** - This is the object instance returned when you get the @each property on an - array. It uses the unknownProperty handler to automatically create - EachArray instances for property names. + You should not maintain this hash yourself, rather, you should use + the `style()` method of `Ember.RenderBuffer`. - @private - @class EachProxy - @namespace Ember - @extends Ember.Object -*/ -Ember.EachProxy = Ember.Object.extend({ + @property elementStyle + @type Hash + @default {} + */ + elementStyle: null, - init: function(content) { - this._super(); - this._content = content; - content.addArrayObserver(this); + /** + Nested `RenderBuffers` will set this to their parent `RenderBuffer` + instance. - // in case someone is already observing some keys make sure they are - // added - forEach(Ember.watchedEvents(this), function(eventName) { - this.didAddListener(eventName); - }, this); - }, + @property parentBuffer + @type Ember._RenderBuffer + */ + parentBuffer: null, /** - You can directly access mapped properties by simply requesting them. - The unknownProperty handler will generate an EachArray of each item. + Adds a string of HTML to the `RenderBuffer`. - @method unknownProperty - @param keyName {String} - @param value {anything} + @method push + @param {String} string HTML to push into the buffer + @chainable */ - unknownProperty: function(keyName, value) { - var ret; - ret = new EachArray(this._content, keyName, this); - Ember.defineProperty(this, keyName, null, ret); - this.beginObservingContentKey(keyName); - return ret; + push: function(string) { + this.buffer.push(string); + return this; }, - // .......................................................... - // ARRAY CHANGES - // Invokes whenever the content array itself changes. - - arrayWillChange: function(content, idx, removedCnt, addedCnt) { - var keys = this._keys, key, array, lim; - - lim = removedCnt>0 ? idx+removedCnt : -1; - Ember.beginPropertyChanges(this); - - for(key in keys) { - if (!keys.hasOwnProperty(key)) { continue; } + /** + Adds a class to the buffer, which will be rendered to the class attribute. - if (lim>0) removeObserverForContentKey(content, key, this, idx, lim); + @method addClass + @param {String} className Class name to add to the buffer + @chainable + */ + addClass: function(className) { + // lazily create elementClasses + var elementClasses = this.elementClasses = (this.elementClasses || new ClassSet()); + this.elementClasses.add(className); + this.classes = this.elementClasses.list; - Ember.propertyWillChange(this, key); - } + return this; + }, - Ember.propertyWillChange(this._content, '@each'); - Ember.endPropertyChanges(this); + setClasses: function(classNames) { + this.classes = classNames; }, - arrayDidChange: function(content, idx, removedCnt, addedCnt) { - var keys = this._keys, key, array, lim; + /** + Sets the elementID to be used for the element. - lim = addedCnt>0 ? idx+addedCnt : -1; - Ember.beginPropertyChanges(this); + @method id + @param {String} id + @chainable + */ + id: function(id) { + this.elementId = id; + return this; + }, - for(key in keys) { - if (!keys.hasOwnProperty(key)) { continue; } + // duck type attribute functionality like jQuery so a render buffer + // can be used like a jQuery object in attribute binding scenarios. - if (lim>0) addObserverForContentKey(content, key, this, idx, lim); + /** + Adds an attribute which will be rendered to the element. - Ember.propertyDidChange(this, key); + @method attr + @param {String} name The name of the attribute + @param {String} value The value to add to the attribute + @chainable + @return {Ember.RenderBuffer|String} this or the current attribute value + */ + attr: function(name, value) { + var attributes = this.elementAttributes = (this.elementAttributes || {}); + + if (arguments.length === 1) { + return attributes[name]; + } else { + attributes[name] = value; } - Ember.propertyDidChange(this._content, '@each'); - Ember.endPropertyChanges(this); + return this; }, - // .......................................................... - // LISTEN FOR NEW OBSERVERS AND OTHER EVENT LISTENERS - // Start monitoring keys based on who is listening... + /** + Remove an attribute from the list of attributes to render. - didAddListener: function(eventName) { - if (IS_OBSERVER.test(eventName)) { - this.beginObservingContentKey(eventName.slice(0, -7)); - } - }, + @method removeAttr + @param {String} name The name of the attribute + @chainable + */ + removeAttr: function(name) { + var attributes = this.elementAttributes; + if (attributes) { delete attributes[name]; } - didRemoveListener: function(eventName) { - if (IS_OBSERVER.test(eventName)) { - this.stopObservingContentKey(eventName.slice(0, -7)); - } + return this; }, - // .......................................................... - // CONTENT KEY OBSERVING - // Actual watch keys on the source content. + /** + Adds a style to the style attribute which will be rendered to the element. - beginObservingContentKey: function(keyName) { - var keys = this._keys; - if (!keys) keys = this._keys = {}; - if (!keys[keyName]) { - keys[keyName] = 1; - var content = this._content, - len = get(content, 'length'); - addObserverForContentKey(content, keyName, this, 0, len); - } else { - keys[keyName]++; - } - }, + @method style + @param {String} name Name of the style + @param {String} value + @chainable + */ + style: function(name, value) { + var style = this.elementStyle = (this.elementStyle || {}); - stopObservingContentKey: function(keyName) { - var keys = this._keys; - if (keys && (keys[keyName]>0) && (--keys[keyName]<=0)) { - var content = this._content, - len = get(content, 'length'); - removeObserverForContentKey(content, keyName, this, 0, len); - } + this.elementStyle[name] = value; + return this; }, - contentKeyWillChange: function(obj, keyName) { - Ember.propertyWillChange(this, keyName); + begin: function(tagName) { + this.tagNames.push(tagName || null); + return this; }, - contentKeyDidChange: function(obj, keyName) { - Ember.propertyDidChange(this, keyName); - } + pushOpeningTag: function() { + var tagName = this.currentTagName(); + if (!tagName) { return; } -}); + if (!this._element && this.buffer.length === 0) { + this._element = this.generateElement(); + return; + } + var buffer = this.buffer, + id = this.elementId, + classes = this.classes, + attrs = this.elementAttributes, + style = this.elementStyle, + prop; + buffer.push('<' + tagName); -})(); + if (id) { + buffer.push(' id="' + this._escapeAttribute(id) + '"'); + this.elementId = null; + } + if (classes) { + buffer.push(' class="' + this._escapeAttribute(classes.join(' ')) + '"'); + this.classes = null; + } + if (style) { + buffer.push(' style="'); + for (prop in style) { + if (style.hasOwnProperty(prop)) { + buffer.push(prop + ':' + this._escapeAttribute(style[prop]) + ';'); + } + } -(function() { -/** -@module ember -@submodule ember-runtime -*/ + buffer.push('"'); + this.elementStyle = null; + } -var get = Ember.get, set = Ember.set; + if (attrs) { + for (prop in attrs) { + if (attrs.hasOwnProperty(prop)) { + buffer.push(' ' + prop + '="' + this._escapeAttribute(attrs[prop]) + '"'); + } + } -// Add Ember.Array to Array.prototype. Remove methods with native -// implementations and supply some more optimized versions of generic methods -// because they are so common. -var NativeArray = Ember.Mixin.create(Ember.MutableArray, Ember.Observable, Ember.Copyable, { + this.elementAttributes = null; + } - // because length is a built-in property we need to know to just get the - // original property. - get: function(key) { - if (key==='length') return this.length; - else if ('number' === typeof key) return this[key]; - else return this._super(key); + buffer.push('>'); }, - objectAt: function(idx) { - return this[idx]; + pushClosingTag: function() { + var tagName = this.tagNames.pop(); + if (tagName) { this.buffer.push(''); } }, - // primitive for array support. - replace: function(idx, amt, objects) { - - if (this.isFrozen) throw Ember.FROZEN_ERROR ; + currentTagName: function() { + return this.tagNames[this.tagNames.length-1]; + }, - // if we replaced exactly the same number of items, then pass only the - // replaced range. Otherwise, pass the full remaining array length - // since everything has shifted - var len = objects ? get(objects, 'length') : 0; - this.arrayContentWillChange(idx, amt, len); + generateElement: function() { + var tagName = this.tagNames.pop(), // pop since we don't need to close + element = document.createElement(tagName), + $element = Ember.$(element), + id = this.elementId, + classes = this.classes, + attrs = this.elementAttributes, + style = this.elementStyle, + styleBuffer = '', prop; - if (!objects || objects.length === 0) { - this.splice(idx, amt) ; - } else { - var args = [idx, amt].concat(objects) ; - this.splice.apply(this,args) ; + if (id) { + $element.attr('id', id); + this.elementId = null; } - - this.arrayContentDidChange(idx, amt, len); - return this ; - }, - - // If you ask for an unknown property, then try to collect the value - // from member items. - unknownProperty: function(key, value) { - var ret;// = this.reducedProperty(key, value) ; - if ((value !== undefined) && ret === undefined) { - ret = this[key] = value; + if (classes) { + $element.attr('class', classes.join(' ')); + this.classes = null; } - return ret ; - }, - // If browser did not implement indexOf natively, then override with - // specialized version - indexOf: function(object, startAt) { - var idx, len = this.length; + if (style) { + for (prop in style) { + if (style.hasOwnProperty(prop)) { + styleBuffer += (prop + ':' + style[prop] + ';'); + } + } - if (startAt === undefined) startAt = 0; - else startAt = (startAt < 0) ? Math.ceil(startAt) : Math.floor(startAt); - if (startAt < 0) startAt += len; + $element.attr('style', styleBuffer); - for(idx=startAt;idx=0;idx--) { - if (this[idx] === object) return idx ; + this.elementAttributes = null; } - return -1; + + return element; }, - copy: function() { - return this.slice(); - } -}); + /** + @method element + @return {DOMElement} The element corresponding to the generated HTML + of this buffer + */ + element: function() { + var html = this.innerString(); -// Remove any methods implemented natively so we don't override them -var ignore = ['length']; -Ember.EnumerableUtils.forEach(NativeArray.keys(), function(methodName) { - if (Array.prototype[methodName]) ignore.push(methodName); -}); + if (html) { + this._element = Ember.ViewUtils.setInnerHTML(this._element, html); + } -if (ignore.length>0) { - NativeArray = NativeArray.without.apply(NativeArray, ignore); -} + return this._element; + }, -/** - The NativeArray mixin contains the properties needed to to make the native - Array support Ember.MutableArray and all of its dependent APIs. Unless you - have Ember.EXTEND_PROTOTYPES set to false, this will be applied automatically. - Otherwise you can apply the mixin at anytime by calling - `Ember.NativeArray.activate`. + /** + Generates the HTML content for this buffer. - @class NativeArray - @namespace Ember - @extends Ember.Mixin - @uses Ember.MutableArray - @uses Ember.MutableEnumerable - @uses Ember.Copyable - @uses Ember.Freezable -*/ -Ember.NativeArray = NativeArray; + @method string + @return {String} The generated HTML + */ + string: function() { + if (this._element) { + return this.element().outerHTML; + } else { + return this.innerString(); + } + }, -/** - Creates an Ember.NativeArray from an Array like object. - Does not modify the original object. + innerString: function() { + return this.buffer.join(''); + }, - @method A - @for Ember - @return {Ember.NativeArray} -*/ -Ember.A = function(arr){ - if (arr === undefined) { arr = []; } - return Ember.NativeArray.apply(arr); -}; + _escapeAttribute: function(value) { + // Stolen shamelessly from Handlebars -/** - Activates the mixin on the Array.prototype if not already applied. Calling - this method more than once is safe. + var escape = { + "<": "<", + ">": ">", + '"': """, + "'": "'", + "`": "`" + }; - @method activate - @for Ember.NativeArray - @static - @return {void} -*/ -Ember.NativeArray.activate = function() { - NativeArray.apply(Array.prototype); + var badChars = /&(?!\w+;)|[<>"'`]/g; + var possible = /[&<>"'`]/; - Ember.A = function(arr) { return arr || []; }; -}; + var escapeChar = function(chr) { + return escape[chr] || "&"; + }; -if (Ember.EXTEND_PROTOTYPES) Ember.NativeArray.activate(); + var string = value.toString(); + if(!possible.test(string)) { return string; } + return string.replace(badChars, escapeChar); + } +}; })(); @@ -10191,111 +13030,203 @@ if (Ember.EXTEND_PROTOTYPES) Ember.NativeArray.activate(); (function() { /** @module ember -@submodule ember-runtime +@submodule ember-views */ -var get = Ember.get, set = Ember.set; +var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt; + +/** + `Ember.EventDispatcher` handles delegating browser events to their + corresponding `Ember.Views.` For example, when you click on a view, + `Ember.EventDispatcher` ensures that that view's `mouseDown` method gets + called. + + @class EventDispatcher + @namespace Ember + @private + @extends Ember.Object +*/ +Ember.EventDispatcher = Ember.Object.extend( +/** @scope Ember.EventDispatcher.prototype */{ -Ember._PromiseChain = Ember.Object.extend({ - promises: null, - failureCallback: Ember.K, - successCallback: Ember.K, - abortCallback: Ember.K, - promiseSuccessCallback: Ember.K, + /** + @private - runNextPromise: function() { - if (get(this, 'isDestroyed')) { return; } + The root DOM element to which event listeners should be attached. Event + listeners will be attached to the document unless this is overridden. - var item = get(this, 'promises').shiftObject(); - if (item) { - var promise = get(item, 'promise') || item; - Ember.assert("Cannot find promise to invoke", Ember.canInvoke(promise, 'then')); + Can be specified as a DOMElement or a selector string. - var self = this; + The default body is a string since this may be evaluated before document.body + exists in the DOM. - var successCallback = function() { - self.promiseSuccessCallback.call(this, item, arguments); - self.runNextPromise(); - }; + @property rootElement + @type DOMElement + @default 'body' + */ + rootElement: 'body', + + /** + @private + + Sets up event listeners for standard browser events. + + This will be called after the browser sends a `DOMContentReady` event. By + default, it will set up all of the listeners on the document body. If you + would like to register the listeners on a different element, set the event + dispatcher's `root` property. + + @method setup + @param addedEvents {Hash} + */ + setup: function(addedEvents) { + 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' + }; + + Ember.$.extend(events, addedEvents || {}); + + var rootElement = Ember.$(get(this, 'rootElement')); + + Ember.assert(fmt('You cannot use the same root element (%@) multiple times in an Ember.Application', [rootElement.selector || rootElement[0].tagName]), !rootElement.is('.ember-application')); + Ember.assert('You cannot make a new Ember.Application using a root element that is a descendent of an existing Ember.Application', !rootElement.closest('.ember-application').length); + Ember.assert('You cannot make a new Ember.Application using a root element that is an ancestor of an existing Ember.Application', !rootElement.find('.ember-application').length); + + rootElement.addClass('ember-application'); - var failureCallback = get(self, 'failureCallback'); + Ember.assert('Unable to add "ember-application" class to rootElement. Make sure you set rootElement to the body or an element in the body.', rootElement.is('.ember-application')); - promise.then(successCallback, failureCallback); - } else { - this.successCallback(); + for (event in events) { + if (events.hasOwnProperty(event)) { + this.setupHandler(rootElement, event, events[event]); + } } }, - start: function() { - this.runNextPromise(); - return this; - }, + /** + @private - abort: function() { - this.abortCallback(); - this.destroy(); - }, + Registers an event listener on the document. If the given event is + triggered, the provided event handler will be triggered on the target view. - init: function() { - set(this, 'promises', Ember.A(get(this, 'promises'))); - this._super(); - } -}); + If the target view does not implement the event handler, or if the handler + returns `false`, the parent view will be called. The event will continue to + bubble to each successive parent view until it reaches the top. + For example, to have the `mouseDown` method called on the target view when + a `mousedown` event is received from the browser, do the following: -})(); + ```javascript + setupHandler('mousedown', 'mouseDown'); + ``` + + @method setupHandler + @param {Element} rootElement + @param {String} event the browser-originated event to listen to + @param {String} eventName the name of the method to call on the view + */ + setupHandler: function(rootElement, event, eventName) { + var self = this; + rootElement.delegate('.ember-view', event + '.ember', function(evt, triggeringManager) { + return Ember.handleErrors(function() { + var view = Ember.View.views[this.id], + result = true, manager = null; + manager = self._findNearestEventManager(view,eventName); -(function() { -/** -@module ember -@submodule ember-runtime -*/ + if (manager && manager !== triggeringManager) { + result = self._dispatchEvent(manager, evt, eventName, view); + } else if (view) { + result = self._bubbleEvent(view,evt,eventName); + } else { + evt.stopPropagation(); + } -var loadHooks = {}; -var loaded = {}; + return result; + }, this); + }); -/** -@method onLoad -@for Ember -@param name {String} name of hook -@param callback {Function} callback to be called -*/ -Ember.onLoad = function(name, callback) { - var object; + rootElement.delegate('[data-ember-action]', event + '.ember', function(evt) { + return Ember.handleErrors(function() { + var actionId = Ember.$(evt.currentTarget).attr('data-ember-action'), + action = Ember.Handlebars.ActionHelper.registeredActions[actionId], + handler = action.handler; - loadHooks[name] = loadHooks[name] || Ember.A(); - loadHooks[name].pushObject(callback); + if (action.eventName === eventName) { + return handler(evt); + } + }, this); + }); + }, - if (object = loaded[name]) { - callback(object); - } -}; + _findNearestEventManager: function(view, eventName) { + var manager = null; -/** -@method runLoadHooks -@for Ember -@param name {String} name of hook -@param object {Object} object to pass to callbacks -*/ -Ember.runLoadHooks = function(name, object) { - var hooks; + while (view) { + manager = get(view, 'eventManager'); + if (manager && manager[eventName]) { break; } - loaded[name] = object; + view = get(view, 'parentView'); + } - if (hooks = loadHooks[name]) { - loadHooks[name].forEach(function(callback) { - callback(object); - }); - } -}; + return manager; + }, -})(); + _dispatchEvent: function(object, evt, eventName, view) { + var result = true; + + var handler = object[eventName]; + if (Ember.typeOf(handler) === 'function') { + result = handler.call(object, evt, view); + // Do not preventDefault in eventManagers. + evt.stopPropagation(); + } + else { + result = this._bubbleEvent(view, evt, eventName); + } + return result; + }, + _bubbleEvent: function(view, evt, eventName) { + return Ember.run(function() { + return view.handleEvent(eventName, evt); + }); + }, -(function() { + destroy: function() { + var rootElement = get(this, 'rootElement'); + Ember.$(rootElement).undelegate('.ember').removeClass('ember-application'); + return this._super(); + } +}); })(); @@ -10304,4341 +13235,4904 @@ Ember.runLoadHooks = function(name, object) { (function() { /** @module ember -@submodule ember-runtime +@submodule ember-views */ -/** - Ember.ControllerMixin provides a standard interface for all classes - that compose Ember's controller layer: Ember.Controller, Ember.ArrayController, - and Ember.ObjectController. - - Within an Ember.Router-managed application single shared instaces of every - Controller object in your application's namespace will be added to the - application's Ember.Router instance. See `Ember.Application#initialize` - for additional information. +// Add a new named queue for rendering views that happens +// after bindings have synced, and a queue for scheduling actions +// that that should occur after view rendering. +var queues = Ember.run.queues; +queues.splice(Ember.$.inArray('actions', queues)+1, 0, 'render', 'afterRender'); - ## Views - By default a controller instance will be the rendering context - for its associated Ember.View. This connection is made during calls to - `Ember.ControllerMixin#connectOutlet`. +})(); - Within the view's template, the Ember.View instance can be accessed - through the controller with `{{view}}`. - ## Target Forwarding - By default a controller will target your application's Ember.Router instance. - Calls to `{{action}}` within the template of a controller's view are forwarded - to the router. See `Ember.Handlebars.helpers.action` for additional information. - @class ControllerMixin - @namespace Ember - @extends Ember.Mixin +(function() { +/** +@module ember +@submodule ember-views */ -Ember.ControllerMixin = Ember.Mixin.create({ - /** - The object to which events from the view should be sent. - For example, when a Handlebars template uses the `{{action}}` helper, - it will attempt to send the event to the view's controller's `target`. +var get = Ember.get, set = Ember.set; + +// Original class declaration and documentation in runtime/lib/controllers/controller.js +// NOTE: It may be possible with YUIDoc to combine docs in two locations - By default, a controller's `target` is set to the router after it is - instantiated by `Ember.Application#initialize`. +/** +Additional methods for the ControllerMixin - @property target - @default null - */ +@class ControllerMixin +@namespace Ember +*/ +Ember.ControllerMixin.reopen({ target: null, - - store: null + namespace: null, + view: null, + container: null }); -/** - @class Controller - @namespace Ember - @extends Ember.Object - @uses Ember.ControllerMixin -*/ -Ember.Controller = Ember.Object.extend(Ember.ControllerMixin); +})(); + + + +(function() { })(); (function() { +var states = {}; + /** @module ember -@submodule ember-runtime +@submodule ember-views */ -var get = Ember.get, set = Ember.set, forEach = Ember.EnumerableUtils.forEach; +var get = Ember.get, set = Ember.set, addObserver = Ember.addObserver, removeObserver = Ember.removeObserver; +var meta = Ember.meta, guidFor = Ember.guidFor, fmt = Ember.String.fmt; +var a_slice = [].slice; +var a_forEach = Ember.EnumerableUtils.forEach; +var a_addObject = Ember.EnumerableUtils.addObject; -/** - Ember.SortableMixin provides a standard interface for array proxies - to specify a sort order and maintain this sorting when objects are added, - removed, or updated without changing the implicit order of their underlying - content array: +var childViewsProperty = Ember.computed(function() { + var childViews = this._childViews; - songs = [ - {trackNumber: 4, title: 'Ob-La-Di, Ob-La-Da'}, - {trackNumber: 2, title: 'Back in the U.S.S.R.'}, - {trackNumber: 3, title: 'Glass Onion'}, - ]; + var ret = Ember.A(); - songsController = Ember.ArrayController.create({ - content: songs, - sortProperties: ['trackNumber'] - }); + a_forEach(childViews, function(view) { + if (view.isVirtual) { + ret.pushObjects(get(view, 'childViews')); + } else { + ret.push(view); + } + }); - songsController.get('firstObject'); // {trackNumber: 2, title: 'Back in the U.S.S.R.'} + return ret; +}); - songsController.addObject({trackNumber: 1, title: 'Dear Prudence'}); - songsController.get('firstObject'); // {trackNumber: 1, title: 'Dear Prudence'} +Ember.warn("The VIEW_PRESERVES_CONTEXT flag has been removed and the functionality can no longer be disabled.", Ember.ENV.VIEW_PRESERVES_CONTEXT !== false); +/** + Global hash of shared templates. This will automatically be populated + by the build tools so that you can store your Handlebars templates in + separate files that get loaded into JavaScript at buildtime. - @class SortableMixin - @namespace Ember - @extends Ember.Mixin - @uses Ember.MutableEnumerable + @property TEMPLATES + @for Ember + @type Hash */ -Ember.SortableMixin = Ember.Mixin.create(Ember.MutableEnumerable, { - sortProperties: null, - sortAscending: true, +Ember.TEMPLATES = {}; - addObject: function(obj) { - var content = get(this, 'content'); - content.pushObject(obj); - }, +Ember.CoreView = Ember.Object.extend(Ember.Evented, { + isView: true, - removeObject: function(obj) { - var content = get(this, 'content'); - content.removeObject(obj); - }, + states: states, - orderBy: function(item1, item2) { - var result = 0, - sortProperties = get(this, 'sortProperties'), - sortAscending = get(this, 'sortAscending'); + init: function() { + this._super(); - Ember.assert("you need to define `sortProperties`", !!sortProperties); + // Register the view for event handling. This hash is used by + // Ember.EventDispatcher to dispatch incoming events. + if (!this.isVirtual) Ember.View.views[this.elementId] = this; - forEach(sortProperties, function(propertyName) { - if (result === 0) { - result = Ember.compare(get(item1, propertyName), get(item2, propertyName)); - if ((result !== 0) && !sortAscending) { - result = (-1) * result; - } - } + this.addBeforeObserver('elementId', function() { + throw new Error("Changing a view's elementId after creation is not allowed"); }); - return result; + this.transitionTo('preRender'); }, - destroy: function() { - var content = get(this, 'content'), - sortProperties = get(this, 'sortProperties'); + /** + If the view is currently inserted into the DOM of a parent view, this + property will point to the parent of the view. - if (content && sortProperties) { - forEach(content, function(item) { - forEach(sortProperties, function(sortProperty) { - Ember.removeObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); - }, this); - }, this); + @property parentView + @type Ember.View + @default null + */ + parentView: Ember.computed(function() { + var parent = this._parentView; + + if (parent && parent.isVirtual) { + return get(parent, 'parentView'); + } else { + return parent; } + }).property('_parentView'), - return this._super(); + state: null, + + _parentView: null, + + // return the current view, not including virtual views + concreteView: Ember.computed(function() { + if (!this.isVirtual) { return this; } + else { return get(this, 'parentView'); } + }).property('parentView').volatile(), + + instrumentName: 'core_view', + + instrumentDetails: function(hash) { + hash.object = this.toString(); }, - isSorted: Ember.computed('sortProperties', function() { - return !!get(this, 'sortProperties'); - }), + /** + @private - arrangedContent: Ember.computed('content', 'sortProperties.@each', function(key, value) { - var content = get(this, 'content'), - isSorted = get(this, 'isSorted'), - sortProperties = get(this, 'sortProperties'), - self = this; + Invoked by the view system when this view needs to produce an HTML + representation. This method will create a new render buffer, if needed, + then apply any default attributes, such as class names and visibility. + Finally, the `render()` method is invoked, which is responsible for + doing the bulk of the rendering. - if (content && isSorted) { - content = content.slice(); - content.sort(function(item1, item2) { - return self.orderBy(item1, item2); - }); - forEach(content, function(item) { - forEach(sortProperties, function(sortProperty) { - Ember.addObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); - }, this); - }, this); - return Ember.A(content); - } + You should not need to override this method; instead, implement the + `template` property, or if you need more control, override the `render` + method. - return content; - }).cacheable(), + @method renderToBuffer + @param {Ember.RenderBuffer} buffer the render buffer. If no buffer is + passed, a default buffer, using the current view's `tagName`, will + be used. + */ + renderToBuffer: function(parentBuffer, bufferOperation) { + var name = 'render.' + this.instrumentName, + details = {}; - _contentWillChange: Ember.beforeObserver(function() { - var content = get(this, 'content'), - sortProperties = get(this, 'sortProperties'); + this.instrumentDetails(details); - if (content && sortProperties) { - forEach(content, function(item) { - forEach(sortProperties, function(sortProperty) { - Ember.removeObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); - }, this); - }, this); - } + return Ember.instrument(name, details, function() { + return this._renderToBuffer(parentBuffer, bufferOperation); + }, this); + }, - this._super(); - }, 'content'), + _renderToBuffer: function(parentBuffer, bufferOperation) { + Ember.run.sync(); - sortAscendingWillChange: Ember.beforeObserver(function() { - this._lastSortAscending = get(this, 'sortAscending'); - }, 'sortAscending'), + // If this is the top-most view, start a new buffer. Otherwise, + // create a new buffer relative to the original using the + // provided buffer operation (for example, `insertAfter` will + // insert a new buffer after the "parent buffer"). + var tagName = this.tagName; - sortAscendingDidChange: Ember.observer(function() { - if (get(this, 'sortAscending') !== this._lastSortAscending) { - var arrangedContent = get(this, 'arrangedContent'); - arrangedContent.reverseObjects(); + if (tagName === null || tagName === undefined) { + tagName = 'div'; } - }, 'sortAscending'), - contentArrayWillChange: function(array, idx, removedCount, addedCount) { - var isSorted = get(this, 'isSorted'); + var buffer = this.buffer = parentBuffer && parentBuffer.begin(tagName) || Ember.RenderBuffer(tagName); + this.transitionTo('inBuffer', false); - if (isSorted) { - var arrangedContent = get(this, 'arrangedContent'); - var removedObjects = array.slice(idx, idx+removedCount); - var sortProperties = get(this, 'sortProperties'); + this.beforeRender(buffer); + this.render(buffer); + this.afterRender(buffer); - forEach(removedObjects, function(item) { - arrangedContent.removeObject(item); + return buffer; + }, - forEach(sortProperties, function(sortProperty) { - Ember.removeObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); - }, this); - }); + /** + @private + + Override the default event firing from `Ember.Evented` to + also call methods with the given name. + + @method trigger + @param name {String} + */ + trigger: function(name) { + this._super.apply(this, arguments); + var method = this[name]; + if (method) { + var args = [], i, l; + for (i = 1, l = arguments.length; i < l; i++) { + args.push(arguments[i]); + } + return method.apply(this, args); } + }, - return this._super(array, idx, removedCount, addedCount); + has: function(name) { + return Ember.typeOf(this[name]) === 'function' || this._super(name); }, - contentArrayDidChange: function(array, idx, removedCount, addedCount) { - var isSorted = get(this, 'isSorted'), - sortProperties = get(this, 'sortProperties'); + willDestroy: function() { + var parent = this._parentView; - if (isSorted) { - var addedObjects = array.slice(idx, idx+addedCount); - var arrangedContent = get(this, 'arrangedContent'); + // destroy the element -- this will avoid each child view destroying + // the element over and over again... + if (!this.removedFromDOM) { this.destroyElement(); } - forEach(addedObjects, function(item) { - this.insertItemSorted(item); + // remove from parent if found. Don't call removeFromParent, + // as removeFromParent will try to remove the element from + // the DOM again. + if (parent) { parent.removeChild(this); } - forEach(sortProperties, function(sortProperty) { - Ember.addObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); - }, this); - }, this); - } + this.transitionTo('destroyed'); - return this._super(array, idx, removedCount, addedCount); + // next remove view from global hash + if (!this.isVirtual) delete Ember.View.views[this.elementId]; }, - insertItemSorted: function(item) { - var arrangedContent = get(this, 'arrangedContent'); - var length = get(arrangedContent, 'length'); + clearRenderedChildren: Ember.K, + triggerRecursively: Ember.K, + invokeRecursively: Ember.K, + transitionTo: Ember.K, + destroyElement: Ember.K +}); + +/** + `Ember.View` is the class in Ember responsible for encapsulating templates of + HTML content, combining templates with data to render as sections of a page's + DOM, and registering and responding to user-initiated events. - var idx = this._binarySearch(item, 0, length); - arrangedContent.insertAt(idx, item); - }, + ## HTML Tag - contentItemSortPropertyDidChange: function(item) { - var arrangedContent = get(this, 'arrangedContent'), - oldIndex = arrangedContent.indexOf(item), - newIndex = this._binarySearch(item, 0, get(arrangedContent, 'length')); + The default HTML tag name used for a view's DOM representation is `div`. This + can be customized by setting the `tagName` property. The following view +class: - if (newIndex !== oldIndex) { - arrangedContent.removeObject(item); - this.insertItemSorted(item); - } - }, + ```javascript + ParagraphView = Ember.View.extend({ + tagName: 'em' + }); + ``` - _binarySearch: function(item, low, high) { - var mid, midItem, res, arrangedContent; + Would result in instances with the following HTML: - if (low === high) { - return low; - } + ```html + + ``` - arrangedContent = get(this, 'arrangedContent'); + ## HTML `class` Attribute - mid = low + Math.floor((high - low) / 2); - midItem = arrangedContent.objectAt(mid); + The HTML `class` attribute of a view's tag can be set by providing a + `classNames` property that is set to an array of strings: - res = this.orderBy(midItem, item); + ```javascript + MyView = Ember.View.extend({ + classNames: ['my-class', 'my-other-class'] + }); + ``` - if (res < 0) { - return this._binarySearch(item, mid+1, high); - } else if (res > 0) { - return this._binarySearch(item, low, mid); - } + Will result in view instances with an HTML representation of: - return mid; - } -}); + ```html +
+ ``` -})(); + `class` attribute values can also be set by providing a `classNameBindings` + property set to an array of properties names for the view. The return value + of these properties will be added as part of the value for the view's `class` + attribute. These properties can be computed properties: + ```javascript + MyView = Ember.View.extend({ + classNameBindings: ['propertyA', 'propertyB'], + propertyA: 'from-a', + propertyB: function(){ + if(someLogic){ return 'from-b'; } + }.property() + }); + ``` + Will result in view instances with an HTML representation of: -(function() { -/** -@module ember -@submodule ember-runtime -*/ + ```html +
+ ``` -var get = Ember.get, set = Ember.set; + If the value of a class name binding returns a boolean the property name + itself will be used as the class name if the property is true. The class name + will not be added if the value is `false` or `undefined`. -/** - Ember.ArrayController provides a way for you to publish a collection of objects - so that you can easily bind to the collection from a Handlebars #each helper, - an Ember.CollectionView, or other controllers. + ```javascript + MyView = Ember.View.extend({ + classNameBindings: ['hovered'], + hovered: true + }); + ``` - The advantage of using an ArrayController is that you only have to set up - your view bindings once; to change what's displayed, simply swap out the - `content` property on the controller. + Will result in view instances with an HTML representation of: - For example, imagine you wanted to display a list of items fetched via an XHR - request. Create an Ember.ArrayController and set its `content` property: + ```html +
+ ``` - ``` javascript - MyApp.listController = Ember.ArrayController.create(); + When using boolean class name bindings you can supply a string value other + than the property name for use as the `class` HTML attribute by appending the + preferred value after a ":" character when defining the binding: - $.get('people.json', function(data) { - MyApp.listController.set('content', data); + ```javascript + MyView = Ember.View.extend({ + classNameBindings: ['awesome:so-very-cool'], + awesome: true }); ``` - Then, create a view that binds to your new controller: + Will result in view instances with an HTML representation of: - ``` handlebars - {{#each MyApp.listController}} - {{firstName}} {{lastName}} - {{/each}} + ```html +
``` - Although you are binding to the controller, the behavior of this controller - is to pass through any methods or properties to the underlying array. This - capability comes from `Ember.ArrayProxy`, which this class inherits from. + Boolean value class name bindings whose property names are in a + camelCase-style format will be converted to a dasherized format: - Note: As of this writing, `ArrayController` does not add any functionality - to its superclass, `ArrayProxy`. The Ember team plans to add additional - controller-specific functionality in the future, e.g. single or multiple - selection support. If you are creating something that is conceptually a - controller, use this class. + ```javascript + MyView = Ember.View.extend({ + classNameBindings: ['isUrgent'], + isUrgent: true + }); + ``` - @class ArrayController - @namespace Ember - @extends Ember.ArrayProxy - @uses Ember.SortableMixin - @uses Ember.ControllerMixin -*/ + Will result in view instances with an HTML representation of: -Ember.ArrayController = Ember.ArrayProxy.extend(Ember.ControllerMixin, - Ember.SortableMixin); + ```html +
+ ``` -})(); + Class name bindings can also refer to object values that are found by + traversing a path relative to the view itself: + ```javascript + MyView = Ember.View.extend({ + classNameBindings: ['messages.empty'] + messages: Ember.Object.create({ + empty: true + }) + }); + ``` + Will result in view instances with an HTML representation of: -(function() { -/** -@module ember -@submodule ember-runtime -*/ + ```html +
+ ``` -/** - Ember.ObjectController is part of Ember's Controller layer. A single - shared instance of each Ember.ObjectController subclass in your application's - namespace will be created at application initialization and be stored on your - application's Ember.Router instance. + If you want to add a class name for a property which evaluates to true and + and a different class name if it evaluates to false, you can pass a binding + like this: - Ember.ObjectController derives its functionality from its superclass - Ember.ObjectProxy and the Ember.ControllerMixin mixin. + ```javascript + // Applies 'enabled' class when isEnabled is true and 'disabled' when isEnabled is false + Ember.View.create({ + classNameBindings: ['isEnabled:enabled:disabled'] + isEnabled: true + }); + ``` - @class ObjectController - @namespace Ember - @extends Ember.ObjectProxy - @uses Ember.ControllerMixin -**/ -Ember.ObjectController = Ember.ObjectProxy.extend(Ember.ControllerMixin); + Will result in view instances with an HTML representation of: -})(); + ```html +
+ ``` + When isEnabled is `false`, the resulting HTML reprensentation looks like + this: + ```html +
+ ``` -(function() { + This syntax offers the convenience to add a class if a property is `false`: -})(); + ```javascript + // Applies no class when isEnabled is true and class 'disabled' when isEnabled is false + Ember.View.create({ + classNameBindings: ['isEnabled::disabled'] + isEnabled: true + }); + ``` + Will result in view instances with an HTML representation of: + ```html +
+ ``` -(function() { -/** -Ember Runtime + When the `isEnabled` property on the view is set to `false`, it will result + in view instances with an HTML representation of: -@module ember -@submodule ember-runtime -@requires ember-metal -*/ + ```html +
+ ``` -})(); + Updates to the the value of a class name binding will result in automatic + update of the HTML `class` attribute in the view's rendered HTML + representation. If the value becomes `false` or `undefined` the class name + will be removed. -(function() { -function visit(vertex, fn, visited, path) { - var name = vertex.name, - vertices = vertex.incoming, - names = vertex.incomingNames, - len = names.length, - i; - if (!visited) { - visited = {}; - } - if (!path) { - path = []; - } - if (visited.hasOwnProperty(name)) { - return; - } - path.push(name); - visited[name] = true; - for (i = 0; i < len; i++) { - visit(vertices[names[i]], fn, visited, path); - } - fn(vertex, path); - path.pop(); -} + Both `classNames` and `classNameBindings` are concatenated properties. See + `Ember.Object` documentation for more information about concatenated + properties. -function DAG() { - this.names = []; - this.vertices = {}; -} + ## HTML Attributes -DAG.prototype.add = function(name) { - if (!name) { return; } - if (this.vertices.hasOwnProperty(name)) { - return this.vertices[name]; - } - var vertex = { - name: name, incoming: {}, incomingNames: [], hasOutgoing: false, value: null - }; - this.vertices[name] = vertex; - this.names.push(name); - return vertex; -}; + The HTML attribute section of a view's tag can be set by providing an + `attributeBindings` property set to an array of property names on the view. + The return value of these properties will be used as the value of the view's + HTML associated attribute: -DAG.prototype.map = function(name, value) { - this.add(name).value = value; -}; + ```javascript + AnchorView = Ember.View.extend({ + tagName: 'a', + attributeBindings: ['href'], + href: 'http://google.com' + }); + ``` -DAG.prototype.addEdge = function(fromName, toName) { - if (!fromName || !toName || fromName === toName) { - return; - } - var from = this.add(fromName), to = this.add(toName); - if (to.incoming.hasOwnProperty(fromName)) { - return; - } - function checkCycle(vertex, path) { - if (vertex.name === toName) { - throw new Error("cycle detected: " + toName + " <- " + path.join(" <- ")); - } - } - visit(from, checkCycle); - from.hasOutgoing = true; - to.incoming[fromName] = from; - to.incomingNames.push(fromName); -}; + Will result in view instances with an HTML representation of: + + ```html + + ``` + + If the return value of an `attributeBindings` monitored property is a boolean + the property will follow HTML's pattern of repeating the attribute's name as + its value: -DAG.prototype.topsort = function(fn) { - var visited = {}, - vertices = this.vertices, - names = this.names, - len = names.length, - i, vertex; - for (i = 0; i < len; i++) { - vertex = vertices[names[i]]; - if (!vertex.hasOutgoing) { - visit(vertex, fn, visited); - } - } -}; + ```javascript + MyTextInput = Ember.View.extend({ + tagName: 'input', + attributeBindings: ['disabled'], + disabled: true + }); + ``` -DAG.prototype.addEdges = function(name, value, before, after) { - var i; - this.map(name, value); - if (before) { - if (typeof before === 'string') { - this.addEdge(name, before); - } else { - for (i = 0; i < before.length; i++) { - this.addEdge(name, before[i]); - } - } - } - if (after) { - if (typeof after === 'string') { - this.addEdge(after, name); - } else { - for (i = 0; i < after.length; i++) { - this.addEdge(after[i], name); + Will result in view instances with an HTML representation of: + + ```html + + ``` + + `attributeBindings` can refer to computed properties: + + ```javascript + MyTextInput = Ember.View.extend({ + tagName: 'input', + attributeBindings: ['disabled'], + disabled: function(){ + if (someLogic) { + return true; + } else { + return false; } - } - } -}; + }.property() + }); + ``` -Ember.DAG = DAG; + Updates to the the property of an attribute binding will result in automatic + update of the HTML attribute in the view's rendered HTML representation. -})(); + `attributeBindings` is a concatenated property. See `Ember.Object` + documentation for more information about concatenated properties. + ## Templates + The HTML contents of a view's rendered representation are determined by its + template. Templates can be any function that accepts an optional context + parameter and returns a string of HTML that will be inserted within the + view's tag. Most typically in Ember this function will be a compiled + `Ember.Handlebars` template. -(function() { -/** -@module ember -@submodule ember-application -*/ + ```javascript + AView = Ember.View.extend({ + template: Ember.Handlebars.compile('I am the template') + }); + ``` -var get = Ember.get, set = Ember.set; + Will result in view instances with an HTML representation of: -/** - An instance of `Ember.Application` is the starting point for every Ember.js - application. It helps to instantiate, initialize and coordinate the many - objects that make up your app. + ```html +
I am the template
+ ``` + + Within an Ember application is more common to define a Handlebars templates as + part of a page: + + ```html + + ``` - Each Ember.js app has one and only one `Ember.Application` object. In fact, the very - first thing you should do in your application is create the instance: + And associate it by name using a view's `templateName` property: ```javascript - window.App = Ember.Application.create(); + AView = Ember.View.extend({ + templateName: 'some-template' + }); ``` - Typically, the application object is the only global variable. All other - classes in your app should be properties on the `Ember.Application` instance, - which highlights its first role: a global namespace. + Using a value for `templateName` that does not have a Handlebars template + with a matching `data-template-name` attribute will throw an error. - For example, if you define a view class, it might look like this: + Assigning a value to both `template` and `templateName` properties will throw + an error. + + For views classes that may have a template later defined (e.g. as the block + portion of a `{{view}}` Handlebars helper call in another template or in + a subclass), you can provide a `defaultTemplate` property set to compiled + template function. If a template is not later provided for the view instance + the `defaultTemplate` value will be used: ```javascript - App.MyView = Ember.View.extend(); + AView = Ember.View.extend({ + defaultTemplate: Ember.Handlebars.compile('I was the default'), + template: null, + templateName: null + }); ``` - After all of your classes are defined, call `App.initialize()` to start the - application. + Will result in instances with an HTML representation of: - Because `Ember.Application` inherits from `Ember.Namespace`, any classes - you create will have useful string representations when calling `toString()`; - see the `Ember.Namespace` documentation for more information. + ```html +
I was the default
+ ``` - While you can think of your `Ember.Application` as a container that holds the - other classes in your application, there are several other responsibilities - going on under-the-hood that you may want to understand. + If a `template` or `templateName` is provided it will take precedence over + `defaultTemplate`: - ### Event Delegation + ```javascript + AView = Ember.View.extend({ + defaultTemplate: Ember.Handlebars.compile('I was the default') + }); - Ember.js uses a technique called _event delegation_. This allows the framework - to set up a global, shared event listener instead of requiring each view to do - it manually. For example, instead of each view registering its own `mousedown` - listener on its associated element, Ember.js sets up a `mousedown` listener on - the `body`. + aView = AView.create({ + template: Ember.Handlebars.compile('I was the template, not default') + }); + ``` - If a `mousedown` event occurs, Ember.js will look at the target of the event and - start walking up the DOM node tree, finding corresponding views and invoking their - `mouseDown` method as it goes. + Will result in the following HTML representation when rendered: - `Ember.Application` has a number of default events that it listens for, as well - as a mapping from lowercase events to camel-cased view method names. For - example, the `keypress` event causes the `keyPress` method on the view to be - called, the `dblclick` event causes `doubleClick` to be called, and so on. + ```html +
I was the template, not default
+ ``` + + ## View Context - If there is a browser event that Ember.js does not listen for by default, you - can specify custom events and their corresponding view method names by setting - the application's `customEvents` property: + The default context of the compiled template is the view's controller: ```javascript - App = Ember.Application.create({ - customEvents: { - // add support for the loadedmetadata media - // player event - 'loadedmetadata': "loadedMetadata" - } + AView = Ember.View.extend({ + template: Ember.Handlebars.compile('Hello {{excitedGreeting}}') + }); + + aController = Ember.Object.create({ + firstName: 'Barry', + excitedGreeting: function(){ + return this.get("content.firstName") + "!!!" + }.property() + }); + + aView = AView.create({ + controller: aController, }); ``` - By default, the application sets up these event listeners on the document body. - However, in cases where you are embedding an Ember.js application inside an - existing page, you may want it to set up the listeners on an element inside - the body. + Will result in an HTML representation of: + + ```html +
Hello Barry!!!
+ ``` + + A context can also be explicitly supplied through the view's `context` + property. If the view has neither `context` nor `controller` properties, the + `parentView`'s context will be used. + + ## Layouts + + Views can have a secondary template that wraps their main template. Like + primary templates, layouts can be any function that accepts an optional + context parameter and returns a string of HTML that will be inserted inside + view's tag. Views whose HTML element is self closing (e.g. ``) + cannot have a layout and this property will be ignored. + + Most typically in Ember a layout will be a compiled `Ember.Handlebars` + template. - For example, if only events inside a DOM element with the ID of `ember-app` should - be delegated, set your application's `rootElement` property: + A view's layout can be set directly with the `layout` property or reference + an existing Handlebars template by name with the `layoutName` property. + + A template used as a layout must contain a single use of the Handlebars + `{{yield}}` helper. The HTML contents of a view's rendered `template` will be + inserted at this location: ```javascript - window.App = Ember.Application.create({ - rootElement: '#ember-app' + AViewWithLayout = Ember.View.extend({ + layout: Ember.Handlebars.compile("
{{yield}}
") + template: Ember.Handlebars.compile("I got wrapped"), }); ``` - The `rootElement` can be either a DOM element or a jQuery-compatible selector - string. Note that *views appended to the DOM outside the root element will not - receive events.* If you specify a custom root element, make sure you only append - views inside it! + Will result in view instances with an HTML representation of: + + ```html +
+
+ I got wrapped +
+
+ ``` + + See `Handlebars.helpers.yield` for more information. - To learn more about the advantages of event delegation and the Ember.js view layer, - and a list of the event listeners that are setup by default, visit the - [Ember.js View Layer guide](http://emberjs.com/guides/view_layer#toc_event-delegation). + ## Responding to Browser Events - ### Dependency Injection + Views can respond to user-initiated events in one of three ways: method + implementation, through an event manager, and through `{{action}}` helper use + in their template or layout. - One thing you may have noticed while using Ember.js is that you define *classes*, not - *instances*. When your application loads, all of the instances are created for you. - Creating these instances is the responsibility of `Ember.Application`. + ### Method Implementation - When the `Ember.Application` initializes, it will look for an `Ember.Router` class - defined on the applications's `Router` property, like this: + Views can respond to user-initiated events by implementing a method that + matches the event name. A `jQuery.Event` object will be passed as the + argument to this method. ```javascript - App.Router = Ember.Router.extend({ - // ... + AView = Ember.View.extend({ + click: function(event){ + // will be called when when an instance's + // rendered element is clicked + } }); ``` - If found, the router is instantiated and saved on the application's `router` - property (note the lowercase 'r'). While you should *not* reference this router - instance directly from your application code, having access to `App.router` - from the console can be useful during debugging. + ### Event Managers - After the router is created, the application loops through all of the - registered _injections_ and invokes them once for each property on the - `Ember.Application` object. + Views can define an object as their `eventManager` property. This object can + then implement methods that match the desired event names. Matching events + that occur on the view's rendered HTML or the rendered HTML of any of its DOM + descendants will trigger this method. A `jQuery.Event` object will be passed + as the first argument to the method and an `Ember.View` object as the + second. The `Ember.View` will be the view whose rendered HTML was interacted + with. This may be the view with the `eventManager` property or one of its + descendent views. - An injection is a function that is responsible for instantiating objects from - classes defined on the application. By default, the only injection registered - instantiates controllers and makes them available on the router. + ```javascript + AView = Ember.View.extend({ + eventManager: Ember.Object.create({ + doubleClick: function(event, view){ + // will be called when when an instance's + // rendered element or any rendering + // of this views's descendent + // elements is clicked + } + }) + }); + ``` - For example, if you define a controller class: + An event defined for an event manager takes precedence over events of the + same name handled through methods on the view. ```javascript - App.MyController = Ember.Controller.extend({ - // ... + AView = Ember.View.extend({ + mouseEnter: function(event){ + // will never trigger. + }, + eventManager: Ember.Object.create({ + mouseEnter: function(event, view){ + // takes presedence over AView#mouseEnter + } + }) }); ``` - Your router will receive an instance of `App.MyController` saved on its - `myController` property. - - Libraries on top of Ember.js can register additional injections. For example, - if your application is using Ember Data, it registers an injection that - instantiates `DS.Store`: + Similarly a view's event manager will take precedence for events of any views + rendered as a descendent. A method name that matches an event name will not + be called if the view instance was rendered inside the HTML representation of + a view that has an `eventManager` property defined that handles events of the + name. Events not handled by the event manager will still trigger method calls + on the descendent. ```javascript - Ember.Application.registerInjection({ - name: 'store', - before: 'controllers', + OuterView = Ember.View.extend({ + template: Ember.Handlebars.compile("outer {{#view InnerView}}inner{{/view}} outer"), + eventManager: Ember.Object.create({ + mouseEnter: function(event, view){ + // view might be instance of either + // OutsideView or InnerView depending on + // where on the page the user interaction occured + } + }) + }); + + InnerView = Ember.View.extend({ + click: function(event){ + // will be called if rendered inside + // an OuterView because OuterView's + // eventManager doesn't handle click events + }, + mouseEnter: function(event){ + // will never be called if rendered inside + // an OuterView. + } + }); + ``` + + ### Handlebars `{{action}}` Helper + + See `Handlebars.helpers.action`. + + ### Event Names + + Possible events names for any of the responding approaches described above + are: + + Touch events: + + * `touchStart` + * `touchMove` + * `touchEnd` + * `touchCancel` + + Keyboard events - injection: function(app, router, property) { - if (property === 'Store') { - set(router, 'store', app[property].create()); - } - } - }); - ``` + * `keyDown` + * `keyUp` + * `keyPress` - ### Routing + Mouse events - In addition to creating your application's router, `Ember.Application` is also - responsible for telling the router when to start routing. + * `mouseDown` + * `mouseUp` + * `contextMenu` + * `click` + * `doubleClick` + * `mouseMove` + * `focusIn` + * `focusOut` + * `mouseEnter` + * `mouseLeave` - By default, the router will begin trying to translate the current URL into - application state once the browser emits the `DOMContentReady` event. If you - need to defer routing, you can call the application's `deferReadiness()` method. - Once routing can begin, call the `advanceReadiness()` method. + Form events: - If there is any setup required before routing begins, you can implement a `ready()` - method on your app that will be invoked immediately before routing begins: + * `submit` + * `change` + * `focusIn` + * `focusOut` + * `input` - ```javascript - window.App = Ember.Application.create({ - ready: function() { - this.set('router.enableLogging', true); - } - }); + HTML5 drag and drop events: - To begin routing, you must have at a minimum a top-level controller and view. - You define these as `App.ApplicationController` and `App.ApplicationView`, - respectively. Your application will not work if you do not define these two - mandatory classes. For example: + * `dragStart` + * `drag` + * `dragEnter` + * `dragLeave` + * `drop` + * `dragEnd` - ```javascript - App.ApplicationView = Ember.View.extend({ - templateName: 'application' - }); - App.ApplicationController = Ember.Controller.extend(); - ``` + ## Handlebars `{{view}}` Helper - @class Application + Other `Ember.View` instances can be included as part of a view's template by + using the `{{view}}` Handlebars helper. See `Handlebars.helpers.view` for + additional information. + + @class View @namespace Ember - @extends Ember.Namespace + @extends Ember.Object + @uses Ember.Evented */ -Ember.Application = Ember.Namespace.extend( -/** @scope Ember.Application.prototype */{ +Ember.View = Ember.CoreView.extend( +/** @scope Ember.View.prototype */ { + + concatenatedProperties: ['classNames', 'classNameBindings', 'attributeBindings'], /** - The root DOM element of the Application. This can be specified as an - element or a - [jQuery-compatible selector string](http://api.jquery.com/category/selectors/). + @property isView + @type Boolean + @default true + @final + */ + isView: true, - This is the element that will be passed to the Application's, - `eventDispatcher`, which sets up the listeners for event delegation. Every - view in your application should be a child of the element you specify here. + // .......................................................... + // TEMPLATE SUPPORT + // - @property rootElement - @type DOMElement - @default 'body' + /** + The name of the template to lookup if no template is provided. + + `Ember.View` will look for a template with this name in this view's + `templates` object. By default, this will be a global object + shared in `Ember.TEMPLATES`. + + @property templateName + @type String + @default null */ - rootElement: 'body', + templateName: null, /** - The `Ember.EventDispatcher` responsible for delegating events to this - application's views. - - The event dispatcher is created by the application at initialization time - and sets up event listeners on the DOM element described by the - application's `rootElement` property. + The name of the layout to lookup if no layout is provided. - See the documentation for `Ember.EventDispatcher` for more information. + `Ember.View` will look for a template with this name in this view's + `templates` object. By default, this will be a global object + shared in `Ember.TEMPLATES`. - @property eventDispatcher - @type Ember.EventDispatcher + @property layoutName + @type String @default null */ - eventDispatcher: null, + layoutName: null, /** - The DOM events for which the event dispatcher should listen. + The hash in which to look for `templateName`. - By default, the application's `Ember.EventDispatcher` listens - for a set of standard DOM events, such as `mousedown` and - `keyup`, and delegates them to your application's `Ember.View` - instances. + @property templates + @type Ember.Object + @default Ember.TEMPLATES + */ + templates: Ember.TEMPLATES, - If you would like additional events to be delegated to your - views, set your `Ember.Application`'s `customEvents` property - to a hash containing the DOM event name as the key and the - corresponding view method name as the value. For example: + /** + The template used to render the view. This should be a function that + accepts an optional context parameter and returns a string of HTML that + will be inserted into the DOM relative to its parent view. - App = Ember.Application.create({ - customEvents: { - // add support for the loadedmetadata media - // player event - 'loadedmetadata': "loadedMetadata" - } - }); + In general, you should set the `templateName` property instead of setting + the template yourself. - @property customEvents - @type Object - @default null + @property template + @type Function */ - customEvents: null, + template: Ember.computed(function(key, value) { + if (value !== undefined) { return value; } - autoinit: !Ember.testing, + var templateName = get(this, 'templateName'), + template = this.templateForName(templateName, 'template'); - isInitialized: false, + return template || get(this, 'defaultTemplate'); + }).property('templateName'), - init: function() { - if (!this.$) { this.$ = Ember.$; } + container: Ember.computed(function() { + var parentView = get(this, '_parentView'); - this._super(); + if (parentView) { return get(parentView, 'container'); } - this.createEventDispatcher(); + return Ember.Container && Ember.Container.defaultContainer; + }), - // Start off the number of deferrals at 1. This will be - // decremented by the Application's own `initialize` method. - this._readinessDeferrals = 1; + /** + The controller managing this view. If this property is set, it will be + made available for use by the template. - this.waitForDOMContentLoaded(); + @property controller + @type Object + */ + controller: Ember.computed(function(key) { + var parentView = get(this, '_parentView'); + return parentView ? get(parentView, 'controller') : null; + }).property('_parentView'), - if (this.autoinit) { - var self = this; - this.$().ready(function() { - if (self.isDestroyed || self.isInitialized) return; - self.initialize(); - }); - } - }, + /** + A view may contain a layout. A layout is a regular template but + supersedes the `template` property during rendering. It is the + responsibility of the layout template to retrieve the `template` + property from the view (or alternatively, call `Handlebars.helpers.yield`, + `{{yield}}`) to render it in the correct location. - /** @private */ - createEventDispatcher: function() { - var rootElement = get(this, 'rootElement'), - eventDispatcher = Ember.EventDispatcher.create({ - rootElement: rootElement - }); + This is useful for a view that has a shared wrapper, but which delegates + the rendering of the contents of the wrapper to the `template` property + on a subclass. - set(this, 'eventDispatcher', eventDispatcher); - }, + @property layout + @type Function + */ + layout: Ember.computed(function(key) { + var layoutName = get(this, 'layoutName'), + layout = this.templateForName(layoutName, 'layout'); - waitForDOMContentLoaded: function() { - this.deferReadiness(); + return layout || get(this, 'defaultLayout'); + }).property('layoutName'), - var self = this; - this.$().ready(function() { - self.advanceReadiness(); - }); - }, + templateForName: function(name, type) { + if (!name) { return; } - deferReadiness: function() { - Ember.assert("You cannot defer readiness since the `ready()` hook has already been called.", this._readinessDeferrals > 0); - this._readinessDeferrals++; - }, + Ember.assert("templateNames are not allowed to contain periods: "+name, name.indexOf('.') === -1); - advanceReadiness: function() { - this._readinessDeferrals--; + var container = get(this, 'container'); - if (this._readinessDeferrals === 0) { - Ember.run.once(this, this.didBecomeReady); + if (container) { + return container.lookup('template:' + name); } }, /** - Instantiate all controllers currently available on the namespace - and inject them onto a router. - - Example: + The object from which templates should access properties. - App.PostsController = Ember.ArrayController.extend(); - App.CommentsController = Ember.ArrayController.extend(); + This object will be passed to the template function each time the render + method is called, but it is up to the individual function to decide what + to do with it. - var router = Ember.Router.create({ - ... - }); + By default, this will be the view's controller. - App.initialize(router); + @property context + @type Object + */ + context: Ember.computed(function(key, value) { + if (arguments.length === 2) { + set(this, '_context', value); + return value; + } else { + return get(this, '_context'); + } + }).volatile(), - router.get('postsController') // - router.get('commentsController') // + /** + @private - router.get('postsController.router') // router + Private copy of the view's template context. This can be set directly + by Handlebars without triggering the observer that causes the view + to be re-rendered. - @method initialize - @param router {Ember.Router} - */ - initialize: function(router) { - Ember.assert("Application initialize may only be call once", !this.isInitialized); - Ember.assert("Application not destroyed", !this.isDestroyed); + The context of a view is looked up as follows: - router = this.setupRouter(router); + 1. Supplied context (usually by Handlebars) + 2. Specified controller + 3. `parentView`'s context (for a child of a ContainerView) - this.runInjections(router); + The code in Handlebars that overrides the `_context` property first + checks to see whether the view has a specified controller. This is + something of a hack and should be revisited. - Ember.runLoadHooks('application', this); + @property _context + */ + _context: Ember.computed(function(key) { + var parentView, controller; - this.isInitialized = true; + if (controller = get(this, 'controller')) { + return controller; + } - // At this point, any injections or load hooks that would have wanted - // to defer readiness have fired. - this.advanceReadiness(); + parentView = this._parentView; + if (parentView) { + return get(parentView, '_context'); + } - return this; - }, + return null; + }), - /** @private */ - runInjections: function(router) { - var injections = get(this.constructor, 'injections'), - graph = new Ember.DAG(), - namespace = this, - properties, i, injection; + /** + @private - for (i=0; i