Skip to content

Instantly share code, notes, and snippets.

@benlesh
Last active August 29, 2015 14:03
Show Gist options
  • Save benlesh/1dd86a83f65c7e92f898 to your computer and use it in GitHub Desktop.
Save benlesh/1dd86a83f65c7e92f898 to your computer and use it in GitHub Desktop.
Ember Computed Property Helpers

Ember Computed Property Helpers

More info at http://www.benlesh.com

Open license.. use however. EXCEPT THIS README, IF YOU USE THIS I'LL SUE.

var GETKEY_REGEXP = /^([A-Za-z0-9$_\.]*[A-Za-z0-9$_]+)(\.@each|\.\[\])?/;
function parseArguments(args) {
var handler = args[args.length - 1];
var observed = [].slice.call(args, 0, args.length - 1);
var keys = observed.map(function(name) {
var parts = GETKEY_REGEXP.exec(name);
if(!parts) {
return null;
}
return parts[1];
});
return {
handler: handler,
observed: observed,
keys: keys
};
}
function shorthandFor(type) {
return function() {
var args = parseArguments(arguments);
var actualHandler = function() {
var self = this;
return args.handler.apply(self, args.keys.map(function(key) {
return self.get(key);
}));
};
return Function.prototype[type].apply(actualHandler, args.observed);
};
}
export var property = shorthandFor('property');
export var observer = shorthandFor('observes');
import Ember from 'ember';
export default Ember.Object.extend({
_a: 'a',
_b: 'b',
_c: 'c',
a: function(name, value) {
if(arguments.length > 1) {
this._a = value;
}
return this._a;
}.property(),
b: function(name, value) {
if(arguments.length > 1) {
this._b = value;
}
return this._b;
}.property(),
c: function(name, value) {
if(arguments.length > 1) {
this._c = value;
}
return this._c;
}.property(),
composite: function() {
var a = this.get('a');
var b = this.get('b');
var c = this.get('c');
return a + b + c;
}.property('a','b','c'),
_didChangeAorB: function(){
var a = this.get('a');
var b = this.get('b');
console.log('a or b changed!', a, b);
}.observes('a', 'b')
})
import Ember from 'ember';
import { observer, property } from 'computed-property-helpers';
var alias = Ember.computed.alias;
export default Ember.Object.extend({
_a: 'a',
_b: 'b',
_c: 'c',
a: alias('_a'),
b: alias('_b'),
c: alias('_c'),
composite: property('a','b','c', function(a, b, c) {
return a + b + c;
}),
_didChangeAorB: observer('a', 'b', function(a, b) {
console.log('a or b changed!', a, b);
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment