Last active
March 12, 2019 05:33
-
-
Save heycarsten/6510386 to your computer and use it in GitHub Desktop.
Creates a computed property that automatically increments itself at the specified interval in milliseconds. Useful when used as a dependent property to properties that need to changed as time progresses.
This file contains 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
/* | |
Creates a computed property that automatically increments itself at the | |
specified interval in milliseconds. Useful when used as a dependent | |
property to properties that need to changed based on time. | |
App.PostController = Ember.ObjectController.extend({ | |
'@timer': Ember.computed.timer(1000), | |
sinceCreated: function() { | |
return new Date().getTime() - this.get('createdAt').getTime(); | |
}.property('createdAt', '@timer') | |
}); | |
*/ | |
void function() { | |
var DEFAULT_INTERVAL = 5000; // 5 seconds | |
var cancel = Em.run.cancel, | |
later = Em.run.later, | |
get = Em.get, | |
set = Em.set; | |
function Timer(interval) { | |
this.interval = (interval || DEFAULT_INTERVAL); | |
} | |
Timer.prototype = { | |
didTick: Em.K, | |
isActive: false, | |
currentInterval: 0, | |
resume: function() { | |
if (!this.isActive) { | |
this.isActive = true; | |
this._tick(); | |
} | |
}, | |
_tick: function() { | |
var nextTick = later(this, function() { | |
this._tick(); | |
this.currentInterval++; | |
this.didTick(this.currentInterval); | |
}, this.interval); | |
this._nextTick = nextTick; | |
} | |
}; | |
Em.computed.timer = function(interval) { | |
var timer = new Timer(interval); | |
return Em.computed(function(key) { | |
var obj = this; | |
timer.didTick = function() { | |
obj.notifyPropertyChange(key); | |
} | |
timer.resume(); | |
return timer.currentInterval; | |
}); | |
}; | |
}.call(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment