i0n
i0n

Reputation: 926

How to achieve the correct closure using Ember.run.debounce

I am trying to use Ember.run.debounce to only trigger the save action on a parent view or controller once when there are many child views triggering save. The problem seems to be closure (anonymous function), but I can't find any examples of the best way to implement debounce within Ember in this context.

Here is a jsbin outlining the issue. Any help or pointers appreciated!

http://jsbin.com/esoNobo/1/edit?html,js,console,output

Upvotes: 3

Views: 3451

Answers (1)

mavilein
mavilein

Reputation: 11668

Your suspicion is right but the solution is quite easy.

Your approach:

App.GroupsView = Ember.View.extend({
  templateName: 'groups_view',
  actions: {
    save: function () {
      Ember.run.debounce(this, function() {
        console.log('groups view save');
        this.get('controller').send('save');
      }, 1000);
    }
  }

});

My solution proposal: This way you don't have an anonymous function and the Ember run loop is able to do its debounce logic.

App.GroupsView = Ember.View.extend({
  templateName: 'groups_view',
  actions: {
    save: function () {
      Ember.run.debounce(this, this.saveFn, 1000);
    }
  },
  saveFn : function(){
    console.log('groups view save');
    this.get('controller').send('save');
  }

});

Upvotes: 16

Related Questions