我正在尝试为 Backbone.js 中的单页 Web 应用程序构建一些基础。我将我的 JSON 结构化为“屏幕”,每个屏幕都有一个 ID。
我希望能够从特定屏幕呈现数据,既用于初始页面加载,也用于 on.click 事件之后。
当我创建一个新的模型实例时,我一直在尝试传入一个 ID,但到目前为止,我得到的结果不稳定:它正在渲染 JSON 的不同部分,而不是我指出的部分,或者只是渲染所有部分。任何有关如何选择特定“屏幕”(通过其 ID)的指针将不胜感激。
这是一个指示性 JSON 示例代码:
[{
"id": 0,
"options": [
{ "text": "Tackle player", "next": [ 0, 1 ] },
{ "text": "Dribble the ball", "next": [ 1 ] }
],
"results": [
{ "text": "Tackle successful", "next": [ 0 ] },
{ "text": "You are close enough to shoot", "next": [ 0, 1 ] }
]
},
{
"id": 1,
"options": [
{ "text": "BLAH", "next": [ 0, 1 ] },
{ "text": "BLAH2", "next": [ 1 ] }
],
"results": [
{ "text": "BLAH3", "next": [ 0 ] },
{ "text": "BLAH4", "next": [ 0, 1 ] }
]
}
]
这是我的主干代码:
var app = app || {};
app.Screen = Backbone.Model.extend({
url: '/api',
parse: function(response){
return response;
}
});
var Screens = Backbone.Collection.extend({
model: app.Screen,
url: '/api'
});
app.AppView = Backbone.View.extend({
initialize: function(parameters){
this.listenTo(this.collection, 'add', this.addOne);
},
render: function(){
this.$el.html("test");
this.addAll();
return this;
},
addAll: function(){
this.collection.each(this.addOne, this);
},
addOne: function(model){
var screen_view = new app.ScreenView({
model: model});
screen_view.render();
this.$el.append(screen_view.el);
}
});
app.ScreenView = Backbone.View.extend({
template: _.template(
'<ul id="options">' +
'<% _.each(options, function(info) { %>' +
'<li id="optionA"><a href="#"><%= info.text %></a></li>' +
'<% }); %>' +
'</ul>'
),
initialize: function(options) {
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'destroy', this.remove);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
$(function() {
var screen = new app.Screen({id:0}); //CURRENTLY BEHAVING VERY STRANGELY - change ID to 1 and you will get id 0 expected responses
app.screenCollection = new Screens([screen]);
app.screenCollection.fetch();
new app.AppView({
collection: app.screenCollection, el: $('.gameWrapper')
}).render();
});