下面是我为我手动构建的集合设置的当前代码结构。我的服务器上有一个 json 文件,我现在正尝试加载它并基本上删除手动文件并根据该数据构建一个集合。想知道我可能需要在下面更改我的代码以帮助解决这个问题。
var Game = Backbone.Model.extend({
defaults: {
name: 'John Doe',
age: 30,
occupation: 'worker'
}
});
var GameCollection = Backbone.Collection.extend({
model: Game,
url: 'path/to/json',
parse: function(response) {
return response;
}
});
var GamesView = Backbone.View.extend({
tagName: 'ul',
render: function() {
//filter through all items in a collection
this.collection.each(function(game){
var gameView = new GameView({model: game});
this.$el.append(gameView.render().el);
}, this)
return this;
}
});
var GameView = Backbone.View.extend({
tagName: 'li',
template: _.template($('#gameTemplate').html()),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var gameCollection = new GameCollection([
{
name: 'John Doe',
age: 30,
occupation: 'worker'
},
{
name: 'John Doe',
age: 30,
occupation: 'worker'
},
{
name: 'John Doe',
age: 30,
occupation: 'worker'
}
]);
var gamesView = new GamesView({collection: gameCollection});
$(document.body).append(gamesView.render().el);
最佳答案
这是 Backbone 令人喜爱的众多优点之一。我不知道你在后端使用什么,但你声明你的服务器上有一个 json 文件,希望是一个包含应该在你的集合中的模型的 json 文件。现在这是神奇的代码(请击鼓..):
var GameCollection = Backbone.Collection.extend({
model: Game,
url: 'path/to/json/on/external/server',
});
var gameCollection = new GameCollection();
gameCollection.fetch();
没什么大不了的,对吧?当然,您可以为 fetch
添加或更改多个选项,因此请查看此处的文档:http://backbonejs.org/#Collection-fetch . Backbone 默认使用 jQuery.ajax()
,因此请查看此处的文档以查看所有选项:http://api.jquery.com/jQuery.ajax/
除非服务器上的模型与主干模型不匹配,否则您的集合中不需要自定义解析。
须知:
fetch
是异步的。与服务器对话需要时间,其余的 javascript 将继续并完成。您可能需要至少向 success
选项添加一个回调函数,该函数将在 fetch
完成时调用,最好向 添加一些内容error
以及,以防出现问题。您可以将数据添加为查询字符串,以便您的后端可以使用 data
选项使用它,数据必须是一个对象。这是一个例子:
gameCollection.fetch({
data: {collection_id: 25},
success: function(){
renderCollection(); // some callback to do stuff with the collection you made
},
error: function(){
alert("Oh noes! Something went wrong!")
}
});
fetch
应该以 JSON 格式接收数据,因此您的 url 应该以独占方式返回 JSON,或者设置为检测 AJAX 请求并使用 JSON 响应它。
关于javascript - backbone 从外部 json 填充集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20591083/