How to use debounce function with CanJS DefineMap view-model method?

66 views Asked by At

I'm trying to use lodash _.debounce function for canjs DefineMap view-model method but it seems that this is tricky even I tried to do it in the init method but without success:

export const ViewModel = DefineMap.extend({
 init() {
  this.myMethod = _.debounce(this.myMethod, 200)
 },
 myMethod() {
  // cool stuff here
 }
})

Any help is appreciated!

1

There are 1 answers

0
Justin Meyer On BEST ANSWER

Because DefineMap's are sealed by default, and you likely want independent throttling with respect to individual instances of ViewModel, you want to do it like this:

var time = new Date();

var ViewModel = can.DefineMap.extend({
 id: "number",
 myMethod: {
   type: "any",
   default(){

     var fn = _.debounce(function(){
       console.log(this.id+" says Hi at "+(new Date() - time))
     },100);
     return fn;
   }
 }
});

This basically sets the myMethod property to a debounced function. You can see it in action here: http://jsbin.com/nekelak/edit?html,js,console