Skip to content

Instantly share code, notes, and snippets.

@givanse
Last active August 16, 2016 17:05
Show Gist options
  • Save givanse/8ae1a91e6a625da3882981843b3d1e5a to your computer and use it in GitHub Desktop.
Save givanse/8ae1a91e6a625da3882981843b3d1e5a to your computer and use it in GitHub Desktop.
Conditional binding for a computed property
import Ember from 'ember';
let _myComputedProperty = Ember.computed('foobar', function() {
let foobar = this.get('foobar');
console.log('myComputedProperty triggered >', foobar);
return '_' + foobar + '_';
});
export default Ember.Controller.extend({
// Using a flag results in the correct UI result, but the
// computed is still trying to recalculate its value
// every single time
/*
turnOff: false,
myComputedProperty: Ember.computed('foobar', 'turnOff', function() {
console.log('myComputedProperty triggered');
if (this.get('turnOff')) {
return this.get('myComputedProperty');
}
let foobar = this.get('foobar');
return '_' + foobar + '_';
}),
*/
foobar: 0,
myComputedProperty: _myComputedProperty,
actions: {
startUpdates: function() {
setInterval(() => {
this.incrementProperty('foobar');
}, 700);
},
turnOffComputed: function() {
//this.set('turnOff', true);
// lock it to the last known value
let myComputedProperty = this.get('myComputedProperty');
this.set('myComputedProperty', myComputedProperty);
},
turnOnComputed: function() {
this.set('myComputedProperty', _myComputedProperty);
}
}
});
<h1>Conditional Binding</h1>
<br>
<br>
<button {{action "startUpdates"}}>start infinite computed updates</button>
<br>
<br>
<button {{action "turnOffComputed"}}>turn off computed</button>
<button {{action "turnOnComputed"}}>turn on computed</button>
<br>
<br>
foobar: {{foobar}}
<br>
myComputedProperty: {{myComputedProperty}}
{{outlet}}
<br>
<br>
{
"version": "0.10.4",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.7.0",
"ember-data": "2.7.0",
"ember-template-compiler": "2.7.0"
},
"addons": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment