// ========================================================================== // Project: SproutCore Costello - Property Observing Library // Copyright: ©2006-2011 Strobe Inc. and contributors. // Portions ©2008-2010 Apple Inc. All rights reserved. // License: Licensed under MIT license (see license.js) // ========================================================================== sc_require('core') ; sc_require('system/enumerator'); /*globals Prototype */ /** @namespace This mixin defines the common interface implemented by enumerable objects in SproutCore. 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. h3. 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 SC.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 SC.Enumerable mixin to your class and you will be able to enumerate the contents of your object like any other collection. h3. Using SproutCore 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. SproutCore'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. @since SproutCore 1.0 */ SC.Enumerable = { /** Walk like a duck. @property {Boolean} */ isEnumerable: YES, /** 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 paramter 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 impementation of this method simply looks up the index. This works great on any Array-like objects. @param index {Number} the current index of the iteration @param previousObject {Object} the value returned by the last call to nextObject. @param context {Object} a context object you can use to maintain state. @returns {Object} the next object in the iteration or undefined */ nextObject: function(index, previousObject, context) { return this.objectAt ? this.objectAt(index) : this[index] ; }, /** 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. @returns {Object} the object or undefined */ firstObject: function() { if (this.get('length')===0) return undefined ; if (this.objectAt) return this.objectAt(0); // support arrays out of box // handle generic enumerables var context = SC.Enumerator._popContext(), ret; ret = this.nextObject(0, null, context); context = SC.Enumerator._pushContext(context); return ret ; }.property(), /** Helper method returns the last object from a collection. @returns {Object} the object or undefined */ lastObject: function() { var len = this.get('length'); if (len===0) return undefined ; if (this.objectAt) return this.objectAt(len-1); // support arrays out of box }.property(), /** Returns a new enumerator for this object. See SC.Enumerator for documentation on how to use this object. Enumeration is an alternative to using one of the other iterators described here. @returns {SC.Enumerator} an enumerator for the receiver */ enumerator: function() { return SC.Enumerator.create(this); }, /** 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): {{{ 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. @params callback {Function} the callback to execute @params target {Object} the target object to use @returns {Object} this */ forEach: function(callback, target) { if (typeof callback !== "function") throw new TypeError() ; var len = this.get ? this.get('length') : this.length ; if (target === undefined) target = null; var last = null ; var context = SC.Enumerator._popContext(); for(var idx=0;idx 1) { for(idx=1;idx 2) { for(idx=2;idx 0) { // Loop through removed objects and remove any enumerable observers that // belong to them. removedObjects.forEach(function(item) { item._kvo_for('_kvo_enumerable_observers').forEach(function(observer) { // Remove the observer if it is pointing at this enumerable. // If the observer belongs to another enumerable, just ignore it. if (observer.object === this) { item.removeObserver(observer.key, observer, observer.propertyDidChange); } }); }); // added and resume the chain observer. observedKeys.forEach(function(key) { kvoKey = SC.keyFor('_kvo_enumerable_observers', key); var lastObserver; // Get all original ChainObservers associated with the key this._kvo_for(kvoKey).forEach(function(observer) { // if there are no added objects or removed objects, this // object is a proxy (like ArrayController), which does // not currently receive the added or removed objects. // As a result, walk down to the last element of the // chain and trigger its propertyDidChange, which will // invalidate anything listening. if(!addedObjects.get('length') && !removedObjects.get('length')) { lastObserver = observer; while(lastObserver.next) { lastObserver = lastObserver.next; } lastObserver.propertyDidChange(); } else { addedObjects.forEach(function(item) { this._resumeChainObservingForItemWithChainObserver(item, observer); }, this); } }, this); }, this); } }, /** @private Adds an enumerable observer. Enumerable observers are able to propagate chain observers to each member item in the enumerable, so that the observer is fired whenever a single item changes. You should never call this method directly. Instead, you should call addObserver() with the special '[]' property in the path. For example, if you wanted to observe changes to each item's isDone property, you could call: arrayController.addObserver('[].isDone'); */ addEnumerableObserver: function(key, target, action) { // Add the key to a set so we know what we are observing this._kvo_for('_kvo_enumerable_observed_keys', SC.CoreSet).push(key); // Add the passed ChainObserver to an ObserverSet for that key var kvoKey = SC.keyFor('_kvo_enumerable_observers', key); this._kvo_for(kvoKey).push(target); // set up chained observers on the initial content this._setupEnumerableObservers(this); }, /** Call this method from your unknownProperty() handler to implement automatic reduced properties. A reduced property is a property that collects its contents dynamically from your array contents. Reduced properties always begin with "@". Getting this property will call reduce() on your array with the function matching the key name as the processor. The return value of this will be either the return value from the reduced property or undefined, which means this key is not a reduced property. You can call this at the top of your unknownProperty handler like so: {{{ unknownProperty: function(key, value) { var ret = this.handleReduceProperty(key, value) ; if (ret === undefined) { // process like normal } } }}} @param {String} key the reduce property key @param {Object} value a value or undefined. @param {Boolean} generateProperty only set to false if you do not want an optimized computed property handler generated for this. Not common. @returns {Object} the reduced property or undefined */ reducedProperty: function(key, value, generateProperty) { if (!key || typeof key !== SC.T_STRING || key.charAt(0) !== '@') return undefined ; // not a reduced property // get the reducer key and the reducer var matches = key.match(/^@([^(]*)(\(([^)]*)\))?$/) ; if (!matches || matches.length < 2) return undefined ; // no match var reducerKey = matches[1]; // = 'max' if key = '@max(balance)' var reducerProperty = matches[3] ; // = 'balance' if key = '@max(balance)' reducerKey = "reduce" + reducerKey.slice(0,1).toUpperCase() + reducerKey.slice(1); var reducer = this[reducerKey] ; // if there is no reduce function defined for this key, then we can't // build a reducer for it. if (SC.typeOf(reducer) !== SC.T_FUNCTION) return undefined; // if we can't generate the property, just run reduce if (generateProperty === NO) { return SC.Enumerable.reduce.call(this, reducer, null, reducerProperty) ; } // ok, found the reducer. Let's build the computed property and install var func = SC._buildReducerFor(reducerKey, reducerProperty); var p = this.constructor.prototype ; if (p) { p[key] = func ; // add the function to the properties array so that new instances // will have their dependent key registered. var props = p._properties || [] ; props.push(key) ; p._properties = props ; this.registerDependentKey(key, '[]') ; } // and reduce anyway... return SC.Enumerable.reduce.call(this, reducer, null, reducerProperty) ; }, /** Reducer for @max reduced property. */ reduceMax: function(previousValue, item, index, e, reducerProperty) { if (reducerProperty && item) { item = item.get ? item.get(reducerProperty) : item[reducerProperty]; } if (previousValue === null) return item ; return (item > previousValue) ? item : previousValue ; }, /** Reducer for @maxObject reduced property. */ reduceMaxObject: function(previousItem, item, index, e, reducerProperty) { // get the value for both the previous and current item. If no // reducerProperty was supplied, use the items themselves. var previousValue = previousItem, itemValue = item ; if (reducerProperty) { if (item) { itemValue = item.get ? item.get(reducerProperty) : item[reducerProperty] ; } if (previousItem) { previousValue = previousItem.get ? previousItem.get(reducerProperty) : previousItem[reducerProperty] ; } } if (previousValue === null) return item ; return (itemValue > previousValue) ? item : previousItem ; }, /** Reducer for @min reduced property. */ reduceMin: function(previousValue, item, index, e, reducerProperty) { if (reducerProperty && item) { item = item.get ? item.get(reducerProperty) : item[reducerProperty]; } if (previousValue === null) return item ; return (item < previousValue) ? item : previousValue ; }, /** Reducer for @maxObject reduced property. */ reduceMinObject: function(previousItem, item, index, e, reducerProperty) { // get the value for both the previous and current item. If no // reducerProperty was supplied, use the items themselves. var previousValue = previousItem, itemValue = item ; if (reducerProperty) { if (item) { itemValue = item.get ? item.get(reducerProperty) : item[reducerProperty] ; } if (previousItem) { previousValue = previousItem.get ? previousItem.get(reducerProperty) : previousItem[reducerProperty] ; } } if (previousValue === null) return item ; return (itemValue < previousValue) ? item : previousItem ; }, /** Reducer for @average reduced property. */ reduceAverage: function(previousValue, item, index, e, reducerProperty) { if (reducerProperty && item) { item = item.get ? item.get(reducerProperty) : item[reducerProperty]; } var ret = (previousValue || 0) + item ; var len = e.get ? e.get('length') : e.length; if (index >= len-1) ret = ret / len; //avg after last item. return ret ; }, /** Reducer for @sum reduced property. */ reduceSum: function(previousValue, item, index, e, reducerProperty) { if (reducerProperty && item) { item = item.get ? item.get(reducerProperty) : item[reducerProperty]; } return (previousValue === null) ? item : previousValue + item ; } } ; // Apply reducers... SC.mixin(SC.Enumerable, SC.Reducers) ; SC.mixin(Array.prototype, SC.Reducers) ; Array.prototype.isEnumerable = YES ; // ...................................................... // ARRAY SUPPORT // // Implement the same enhancements on Array. We use specialized methods // because working with arrays are so common. (function() { // These methods will be applied even if they already exist b/c we do it // better. var alwaysMixin = { // this is supported so you can get an enumerator. The rest of the // methods do not use this just to squeeze every last ounce of perf as // possible. nextObject: SC.Enumerable.nextObject, enumerator: SC.Enumerable.enumerator, firstObject: SC.Enumerable.firstObject, lastObject: SC.Enumerable.lastObject, sortProperty: SC.Enumerable.sortProperty, // see above... mapProperty: function(key) { var len = this.length ; var ret = []; for(var idx=0;idx 1) { for(idx=1;idx 2) { for(idx=2;idx