javascript – Backbone.js – 集合未定义
作者:互联网
我正在尝试学习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"
}
]
我在我的localhost上测试它.
解决方法:
你应该改变
window.WineCollection = Backbone.Model.extend({
model: Wine,
url: "wine.json"
});
至
window.WineCollection = Backbone.Collection.extend({
model: Wine,
url: "wine.json"
});
标签:javascript,backbone-js,javascript-framework 来源: https://codeday.me/bug/20190725/1538099.html