微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 在backbone.js中使用bind传递上下文

我希望我的面板在单击时重新渲染.

但是,当我执行单击时,我得到以下内容

Uncaught TypeError: Cannot call method 'get' of undefined

看来,我正在记录的“这个”实际上就是模型本身:

_callbacks: Object
_changed: true
_escapedAttributes: Object
_prevIoUsAttributes: Object
attributes: Object
cid: "c0"
collection: r.d
id: "f5589ba4-a0aa-dd86-9697-30e532e0f975"
__proto__: n

我无法通过将我的上下文传递给model.bind来弄清楚为什么不能保留适当的“this”.

这是我的代码

// Models
window.Panel = Backbone.Model.extend({

    defaults: function(){
        return {
            flipped: false,};
    },toggle: function(){
        this.save({flipped: !this.get("flipped")});
    },});


// Collections

window.PanelList = Backbone.Collection.extend({

    model:Panel,localStorage: new Store("panels"),flipped: function(){
        return this.filter(function(panel){ return panel.get("flipped"); })
    }   
});


// Global collection of Panels
window.Panels = new PanelList;

// Panel View

window.PanelView = Backbone.View.extend({ 

    tagName: 'div',template: _.template($("#panel-template").html()),events: {
        "click" : "toggle"
    },initialize: function(){
        this.model.bind("change",this.render,this) 
        $(this.el).html(this.template(this.model.toJSON()));
    },render: function(){    
        console.log(this);
        var flipped = this.model.get("flipped")
        if (flipped){
           $(this.el).addClass("flip"); 
        } else{
           $(this.el).removeClass("flip"); 
        }           
        return this   
    },toggle: function(){
        this.model.toggle(); 
    }
});

解决方法

这样做的主干方法是使用下划线提供的_.bindAll(…)函数
initialize: function(){
    _.bindAll(this,"render");
    this.model.bind("change",this.render) 
    $(this.el).html(this.template(this.model.toJSON()));
}

_.bindAll做了什么记录here,但它基本上是为此目的而构建的.如果要在对象的所有函数中正确设置此项,则可以在没有函数列表的情况下调用_.bindAll(this).在我的大多数视图中,我倾向于使用此全局绑定函数.

原文地址:https://www.jb51.cc/js/156128.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐