我正在尝试为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();
});
答案 0 :(得分:1)
为什么不在解析的JSON数据中引用数组索引,其中screens
是屏幕数组:
var screen = new app.Screen(screens[index]);
另一种方法是使用像JSONPath这样的东西来根据id来访问对象,这有点复杂。