Skip to content

Instantly share code, notes, and snippets.

@kkenan
Forked from ofersadgat/controllers.application.js
Created November 16, 2016 11:29
Show Gist options
  • Save kkenan/f5ed5e16c5dd39fdf37c82cba5b5f4f4 to your computer and use it in GitHub Desktop.
Save kkenan/f5ed5e16c5dd39fdf37c82cba5b5f4f4 to your computer and use it in GitHub Desktop.
Computed Update Count
import Ember from 'ember';
function CustomComputedGt(dependentProperty, value) {
var isSubscribed = false;
var lastState;
function gt(context) {
return context.get(dependentProperty) > value;
}
return Ember.computed({
get: function (property) {
if (!isSubscribed) {
this.addObserver(dependentProperty, this, function () {
var newState = gt(this);
if (newState !== lastState) {
this.notifyPropertyChange(property);
lastState = newState;
}
});
isSubscribed = true;
}
lastState = gt(this);
return lastState;
}
}).volatile();
}
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
counter: 0,
callCount: 0,
ocallCount: 0,
countGreater: CustomComputedGt('counter', 5),
setCounter: Ember.on('init', function(){
setInterval(function(){
this.set('counter', this.get('counter') + 1);
}.bind(this), 1000);
}),
//countGreater: Ember.computed.gt('counter', 5),
observeCountGreater: Ember.observer('countGreater', Ember.on('init', function(){
var countGreater = this.get('countGreater');
var fixedCountGreater = this.get('fixedCountGreater');
if (fixedCountGreater != countGreater){
this.set('fixedCountGreater', countGreater);
}
})),
prop: Ember.computed('countGreater', function(){
this.set('callCount', this.get('callCount') + 1);
return 'CounterGreater is ' + this.get('countGreater');
}),
oprop: Ember.computed('fixedCountGreater', function(){
this.set('ocallCount', this.get('ocallCount') + 1);
return 'FixedCounterGreater is ' + this.get('fixedCountGreater');
}),
actions: {
onReset: function() {
this.set('counter', 0);
}
}
});
<h1>Welcome to {{appName}}</h1>
<br>
Counter value: {{counter}}
<br>
Prop value: {{prop}}
<br>
OProp value: {{oprop}}
<br>
Prop callcount: {{callCount}}
<br>
Observed value callcount: {{ocallCount}}
<br>
<button {{action 'onReset'}}>Reset</button>
{
"version": "0.10.6",
"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.9.0",
"ember-data": "2.0.1",
"ember-template-compiler": "2.9.0",
"ember-testing": "2.9.0"
},
"addons": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment