need explanation of the _.bindAll() function from Underscore.js

前端 未结 3 1025
日久生厌
日久生厌 2021-01-29 21:41

I\'ve been learning some backbone.js and I\'ve seen plenty of instances where _.bindAll() is used. I have read through the entire backbone.js and underscore.js docu

3条回答
  •  一个人的身影
    2021-01-29 21:48

    The simplest explanation as for me is the next:

    initialize:function () { //backbone initialize function
        this.model.on("change",this.render); //doesn't work because of the wrong context - in such a way we are searching for a render method in the window object  
        this.model.on("change",this.render,this); //works fine
        //or 
        _.bindAll(this,'render');
        this.model.on("change",this.render); //now works fine
        //after  _.bindAll we can use short callback names in model event bindings
    }
    

提交回复
热议问题