Last active
October 11, 2017 18:46
-
-
Save patricklx/6f58ef7ef9d901ad4126 to your computer and use it in GitHub Desktop.
A computed property that chains all given computed properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
A computed property that chains all given computed properties | |
Example | |
```javascript | |
Ember.computed.chain('content', [ | |
[Ember.computed.mapBy, 'key'], | |
[Ember.computed.filter, callback], //e.g. remove undefined/null | |
[Ember.computed.sum], | |
[customComputed] | |
]); | |
//or | |
//looks up on Ember.computed | |
Ember.computed.chain('content', [ | |
['mapBy', 'key'], | |
['filter', callback], | |
['sum'], | |
['toFixed', 2] | |
]); | |
``` | |
@method computed.chain | |
@for Ember | |
@param {String} dependentKey | |
@return {Ember.ComputedProperty} a chain of computed properties | |
*/ | |
export function chain (dependentKey, computedChains) { | |
var func, cp, dependantCPs = {}; | |
forEach(computedChains, function (item) { | |
cp = item[0]; | |
var args = [dependentKey].concat(item.slice(1)); | |
if (typeof cp == "string") { | |
cp = Ember.computed[cp]; | |
} | |
cp = cp.apply(null, args); | |
dependentKey = guidFor(cp) + '-chain'; | |
dependantCPs[dependentKey] = cp; | |
}, this); | |
func = cp.func; | |
cp.func = function (propertyName) { | |
if (!this.__ember_meta__.cacheMeta[propertyName+'-chain']) { | |
for (var k in dependantCPs) { | |
var cp = dependantCPs[k]; | |
Ember.defineProperty(this, k, cp); | |
} | |
this.__ember_meta__.cacheMeta[propertyName+'-chain'] = true; | |
} | |
return func.apply(this, arguments); | |
}; | |
return cp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment