samedi 4 avril 2015

how can I remove observers from a property assigned to an ember computed alias?

if you have a property assigned to an Ember.computed.alias (or Ember.computed.oneWay), how can you remove its observers dynamically?


additional context:


i have a computed property that i'm passing to a component: time=activeSongProgress. activeSongProgress updates about every 100ms or so. I'd like to be able to assign it to a property on my component as a computed alias:



export default Ember.Component.extend({
...
value: Ember.computed.alias('time'),
...
});


and then be able to dynamically unbind value, set it to something else, then assign it back to the computed alias.


e.g. Ember.defineProperty(this, 'value', Ember.computed.alias('time'));)


when i'm dragging the mouse, i don't want value being set by an observer every 100ms, so i need a way to unbind value from time. currently i'm getting the behaviour i want by adding and removing observers:



// app/components/progress-bar.js
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'input',
attributeBindings: ['value', 'type'],
type: "range",
value: 0,

setValueAsTime: function() {
this.set('value', this.get('time'));
},

setTimeObserver: function() {
this.addObserver('time', this, 'setValueAsTime');
}.on('init'),

mouseDown: function() {
this.removeObserver('time', this, 'setValueAsTime');
},

mouseUp: function() {
this.addObserver('time', this, 'setValueAsTime');
}
});


<!-- app/templates/songs.hbs: -->
{{progress-bar time=activeSongProgress}}


which works great, but i think i'd prefer to do this with computed aliases.





Aucun commentaire:

Enregistrer un commentaire