gpt4 book ai didi

javascript - 在 backbone.js 中使用绑定(bind)传递上下文

转载 作者:数据小太阳 更新时间:2023-10-29 04:53:51 26 4
gpt4 key购买 nike

我希望我的面板在被点击时重新呈现。

但是,当我执行点击时,我得到以下信息:

Uncaught TypeError: Cannot call method 'get' of undefined

看起来我正在记录的“this”实际上是模型本身:

_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 ,但它本质上正是为此目的而构建的。如果你想在对象的所有函数中正确设置this,你可以调用没有函数列表的_.bindAll(this) .在我的大多数观点中,我倾向于使用这种全局绑定(bind)功能。

关于javascript - 在 backbone.js 中使用绑定(bind)传递上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7254290/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com