14

I have an observer in a controller that saves the object as changes are made. The problem is it is happing too often.

changed: ( ->
  #save code goes here 
).observes("description")

I am thinking something like http://underscorejs.org/#debounce is needed?

Also It seems to save the object twice once when the attribute changes via a key input and then again when the attribute is set from the returned server value.

Any help would be great I am trying to wrap my head around ember.

4
  • I think the reason that you did not have success with my suggestion is that Ember.debounce /returns a function/ that will run only after debouncing. It doesn't actually run the function by itself. Please have a look at the example I listed in my answer. Let me know how it is different than what you are trying to do. If that's not it, could you perhaps post a jsFiddle that we could use as a base to get the debouncing that you want?
    – jacobq
    Commented Sep 24, 2012 at 19:43
  • At least in Ember 1.0.0, Ember.debounce doens't exist anymore. It is Ember.run.debounce which doesn't return a function but adds the function to a lookup hash which gets checked every time the function gets called.
    – Felix Fung
    Commented Oct 9, 2013 at 4:31
  • 3
    @Willem the ember-invalid tag is under discussion on meta; meta.stackexchange.com/questions/221611/… Commented Feb 17, 2014 at 21:32
  • Willem observers are not deprecated. Felix's answer still applies to the current api. Commented Feb 17, 2014 at 21:56

1 Answer 1

22

From Ember 1.0.0, you can get a debounced observer in any View or Object by wrapping the debounce call inside another function that observes. Ember.run.debounce doesn't return a function but instead adds the function handle to a dictionary. Every subsequent time Ember.run.debounce gets called with that function handle it will check the dictionary to see the last time the function was called and debounce it as expected.

var MyView = Ember.View.extend({
    calledRarely: function() {
        console.log("This will log rarely.");
    },

    calledOften: function() {
        console.log("This will log often.");
        Ember.run.debounce(this, this.calledRarely, 1000);
    }.observes("propertyThatChangesOften")
});

Here, this.calledOften isn't debounced at all so Ember.run.debounce will actually be called as often as the property is changed. It won't call this.calledRarely until our debounce timeout has completed.

1
  • Yes this is now the way to do it. Ember has come a long way since I asked that question. The upgrade to backburner.js added the much needed dbounce and throttle functions to the run loop. Commented Oct 9, 2013 at 17:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.