gpt4 book ai didi

javascript - 为模型问题传递变量

转载 作者:行者123 更新时间:2023-12-03 12:02:39 24 4
gpt4 key购买 nike

我有一个backbonejs应用程序,它的父 View 如下:

var LibraryView = Backbone.View.extend({
initialize: function(options) {
if (options) {
_.extend(this, options);
}
this.render();

alert(this.model); //Alerts Object Object like it's supposed to

_.each(this.model.get("library").books, function(book){
var bookView = new BookView({
el: $('#books'),
book: book,
model: this.model
});
bookView.render();
});
}
});

我的 bookView 看起来像:

var BookView = Backbone.View.extend({
initialize: function(options) {
if (options) {
_.extend(this, options);
}
alert(this.model); // Alerts undefined
}
});

基本上,我试图将 this.model 从 LibraryView 传递到 BookView,但是当我这样做时,BookView 的 alert(this.model) 警报未定义?

我应该提到,当我在 BookView 上 alert(this.book) 时,它不是未定义的。

最佳答案

这是因为 this 已更改 _.each 中的上下文。有上百万篇关于它的帖子,所以我不会解释。像这样结束你们每个人(用这个)以保持上下文:

   _.each(this.model.get("library").books, function(book){
var bookView = new BookView({
el: $('#books'),
book: book,
model: this.model
}, this);

还要查看 Underscore 的 _.bindAll http://underscorejs.org/#bindAll

关于javascript - 为模型问题传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25343938/

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