gpt4 book ai didi

javascript - Backbone.js - 集合未定义

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:26:41 25 4
gpt4 key购买 nike

我正在尝试学习 backbone.js,但我一直坚持获取 json 并添加到集合中。集合未定义,我不知道为什么。代码:

$(document).ready(function() {
(function($) {
//model
window.Wine = Backbone.Model.extend();

window.WineCollection = Backbone.Model.extend({
url: "http://localhost/bootstrap/json.php",
model: Wine
});


//views
window.WineItemView = Backbone.View.extend({
template: _.template($("#wine-item-template").html()),
tagName: 'li',
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});

window.WineListView = Backbone.View.extend({
tagName: 'ul',
initialize: function() {
this.model.bind('reset', this.render, this);

},
render: function() {

_.each(this.model.models, function(wine) {
$(this.el).append(new WineItemView({
model: wine
}).render().el);
}, this);
return this;
}
});


window.WineView = Backbone.View.extend({
template: _.template($('#wine-template').html()),
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
//Router
window.AppRouter = Backbone.Router.extend({
routes: {
'': 'home',
'wines/:id': "wineDetails"
},
home: function() {
this.wineList = new WineCollection();

this.wineListV = new WineListView({
model: this.wineList
});
this.wineList.fetch({success: function(){
console.log(this.wineList.models); // => 2 (collection have been populated)
}});
console.log(this.wineListV);

$("#winelist").html(this.wineListV.render().el);
},
wineDetails: function(id) {
this.wine = this.wineList.get(id);
console.log(id);
this.wineView = new WineView({
model: this.wine
});
$("#container").empty().html(this.wineView.render().el);
}
});


})(jQuery);

var app = new AppRouter();
Backbone.history.start();
});

json.php 返回:

[
{
"name":"Wine 1",
"price":"100",
"status":"available"
},
{
"name":"Wine 1",
"price":"100",
"status":"available"
},
{
"name":"Wine 1",
"price":"100",
"status":"available"
}
]

我正在我的本地主机上测试这个。

最佳答案

你犯了一个愚蠢的错字:

window.WineCollection = Backbone.Model.extend

应该是

window.WineCollection = Backbone.Collection.extend

请注意,按照惯例,您的 WineListView 类应该使用 this.collection 来引用 WineCollection 的实例,并且 Backbone 集合对象提供下划线迭代方法,而不是

.each(this.model.models, function(wine) {

this.collection.each(function (wineModel) {

关于javascript - Backbone.js - 集合未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11559958/

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