Debounced actions in EmberJs

I was developing EmberJS component based on input field. It’s main purpose was auto-save when user stops typing. That is a typing use-case for debounce and should be easy and straightforward. Right?

Well, since I am new to Ember, it was not so easy for me. It was more like a riddle and it took me a considerable time to solve. I finally found a solution using debounce from the underscore library. It worked, yes, but obviously it was not ideal, since Ember has its own implementation in Ember.run.debounce. But it is not very much documented and I could not find example for my use case.

Luckilly, at Topmonks, we do code reviews, so a colleague of mine spotted my struggle and instructed me on how to propertly use the Ember.run.debounce.

The final solution is below. The Ember way how to do debounce. I hope this will save someone’s time 🙂 If so, please let me know in the comments or tweet about it.

export default Ember.Component.extend({
  actions: {    
        save: function(){
          // the target method has to be defined in the component object, 
          // not in the actions object
          Ember.run.debounce(this, this.doSave, 1000);
        }
    },
    
    doSave: function() {
      // perform the save logic here
    }
});

The handlebars template is straight forward

{{input value=myObject.myProperty key-up="save"}}