backbone.js view inheritance. `this` resolution in parent

后端 未结 3 1081
执笔经年
执笔经年 2021-02-01 10:59

I have a case that uses view inheritance, and my code looks essentially like:

parentView = Backbone.View.extend({
    events: {
        \"some event\": \"busines         


        
3条回答
  •  感动是毒
    2021-02-01 11:29

    You can solve this problem by adding this line to the initialize method of the child:

    _.bind(this.business, this)
    

    Hopefully someone can point you to a better description of the underlying mechanisms than I can provide but I'll give it a shot:

    What happens is that the method will use the context of the scope it was defined in unless told otherwise. initialize is told to use the context of the child when you call parentView.prototype.initialize.apply(this) because you are passing in the childView with the this reference to the apply method.

    You can bind the business method to the context of the child by using the underscore.js bind method as described above.

提交回复
热议问题