Observers on Ember.js computed properties are fired if a dependant key changes, regardless of whether the property value changes or not. ember-computed-change-gate
only triggers observers when the result of a computed property changes.
Consider the following example:
Ember.Object.extend({
name: 'Gavin',
trimmedName: Ember.computed('name'), function() {
return this.get('name').trim();
}),
onTrimmedNameChanged: Ember.observer('trimmedName', function() {
console.log('trimmedName changed');
})
});
Every time name
changes onTrimmedNameChanged
will be run, even if the value of trimmedName
doesn't change.
import changeGate from 'ember-computed-change-gate/change-gate';
Ember.Object.extend({
name: 'Gavin',
trimmedName: changeGate('name', function(value) {
return value.trim();
}),
onTrimmedNameChanged: Ember.observer('trimmedName', function() {
console.log('trimmedName changed');
})
});
Using changeGate
will prevent the onTrimmedNameChanged
observer from firing unless the value of trimmedName
changes. Please see the video below for an example of how I've used this when building Intercom:
Since Ember 3.11 extra configuration can be passed to observers to allow them to be configured synchronous or asynchronous. To configure the synchronous state of the observer in changeGate
pass a config object as the last param with the sync
property set appropriately.
For example:
// synchronous observer
trimmedName: changeGate('name', function(value) {
return value.trim();
}, { sync: true }),
//asynchronous observer
trimmedName: changeGate('name', function(value) {
return value.trim();
}, { sync: false }),
See this RFC and blog post for more informationa about async observers.
Questions? Ping me @gavinjoyce
This is an Ember CLI addon, to install:
ember install ember-computed-change-gate
git clone
this repositorynpm install
bower install
npm run lint:js
npm run lint:js -- --fix
ember test
– Runs the test suite on the current Ember versionember test --server
– Runs the test suite in "watch mode"ember try:each
– Runs the test suite against multiple Ember versions
ember serve
- Visit the dummy application at http://localhost:4200.
For more information on using ember-cli, visit https://ember-cli.com/.
This project is licensed under the MIT License.