【发布时间】:2012-11-08 06:01:37
【问题描述】:
在我的应用程序的初始化功能期间,我想默认为我的搜索页面并将我的 LeagueCollection 作为模型传递。
我遇到了一个问题,我可以在我的应用程序初始化中向 this.searchResults 添加一个手表,并按预期查看模型:Array[3], 但是当调用视图中的 this.model.toJSON() 时,我得到错误对象没有方法 toJSON。
这段代码在内存集合中运行良好,然后我切换到使用backbone.localstorage.js 在本地存储应用程序数据。
所以我的问题是:为什么视图中没有填充模型?
在我的 main.js 中有
var AppRouter = Backbone.Router.extend({
routes: {
"": "list",
...
},
initialize: function () {
this.searchResults = new LeagueCollection();
this.searchPage = new SearchPage({
model: this.searchResults.fetch()
});
this.searchPage.render();
},
...
});
在我的搜索页面视图中
window.SearchPage = Backbone.View.extend({
initialize:function () {
this.template = _.template(tpl.get('search-page'));
},
render:function (eventName) {
var self = this;
$(this.el).html(this.template(this.model.toJSON()));
this.listView = new LeagueListView({el: $('ul', this.el), model: this.model});
this.listView.render();
return this;
},
...
});
【问题讨论】:
-
你想要一个集合还是
SearchPage里面的模型,如果你想要一个集合你应该叫它collection而不是model。 -
抱歉术语不正确 - 我的意思是模型
-
但是如果是合集,就应该叫
collection,否则只会迷惑大家。视图构造函数特别对待collection属性,就像对待model参数一样:backbonejs.org/#View-constructor -
是的,查看了您的链接 - 所以集合是 this.options 和模型的一部分,我明白为什么这会令人困惑。谢谢!我会稍微改变一下问题。
-
如果它是一个集合,那么在构造函数调用中调用使用
{collection: c},并在视图中将其称为this.collection,这样就不会那么混乱了。