Last active
November 20, 2016 07:10
-
-
Save givanse/964eda5b8ac3f8158c2087865f4bdb7b to your computer and use it in GitHub Desktop.
re-compute only on value change
This file contains hidden or 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
import Ember from 'ember'; | |
let get = Ember.get; | |
let defaultFilter = function(value) { return value; }; | |
function changeGate(dependentKey, filter) { | |
filter = filter || defaultFilter; | |
let computed = Ember.computed(function handler(key) { | |
let lastValueKey = `__changeGate${key}LastValue`; | |
let isFirstRun = !this.hasOwnProperty(lastValueKey); | |
if (isFirstRun) { //setup an observer which is responsible for notifying property changes | |
this[lastValueKey] = filter.call(this, get(this, dependentKey)); | |
this.addObserver(dependentKey, function() { | |
let newValue = filter.call(this, get(this, dependentKey)); | |
let lastValue = this[lastValueKey]; | |
if (newValue !== lastValue) { | |
this[lastValueKey] = newValue; | |
//should be private API? | |
//this.notifyPropertyChange(key); | |
this.set(key, newValue); | |
} | |
}); | |
} | |
return this[lastValueKey]; | |
}); | |
return computed; | |
}; | |
export default Ember.Controller.extend({ | |
text: "some text", | |
normalCount: Ember.computed('text', function() { | |
return this.get('text').split(' ').length; | |
}), | |
gatedCount: changeGate('text', function() { | |
return this.get('text').split(' ').length; | |
}), | |
normalObserverCount: 0, | |
normalObserver: Ember.observer('normalCount', function() { | |
this.incrementProperty('normalObserverCount'); | |
}), | |
gatedObserverCount: 0, | |
gatedObserver: Ember.observer('gatedCount', function() { | |
this.incrementProperty('gatedObserverCount'); | |
}), | |
}); | |
This file contains hidden or 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
{ | |
"version": "0.10.6", | |
"EmberENV": { | |
"FEATURES": {}, | |
"EXTEND_PROTOTYPES": { | |
"Date": false | |
} | |
}, | |
"options": { | |
"use_pods": false, | |
"enable-testing": false | |
}, | |
"dependencies": { | |
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js", | |
"ember": "2.4.5", | |
"ember-template-compiler": "2.4.5", | |
"ember-testing": "2.4.5", | |
"ember-data": "2.9.0" | |
}, | |
"addons": {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment