Skip to content

Instantly share code, notes, and snippets.

@givanse
Last active November 20, 2016 07:10
Show Gist options
  • Save givanse/964eda5b8ac3f8158c2087865f4bdb7b to your computer and use it in GitHub Desktop.
Save givanse/964eda5b8ac3f8158c2087865f4bdb7b to your computer and use it in GitHub Desktop.
re-compute only on value change
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');
}),
});
<h1>re-compute only on value change</h1>
<br>
<br>
{{input value=text style="width: 300px;"}}
<br>
normal count: {{normalCount}}, {{normalObserverCount}}
<br>
gated count: {{gatedCount}}, {{gatedObserverCount}}
<br>
{{outlet}}
<br>
<br>
{
"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