2013-10-08 40 views
0

我想在Backbone.js中为单个页面的Web应用程序构建一些基础。我已将JSON构建为“屏幕”,每个屏幕都有一个ID。Backbone.js:获取特定的JSON部分

我希望能够从特定屏幕呈现数据,既可以用于初始页面加载,也可以用于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(); 


}); 

回答

1

为什么不直接引用数组索引您解析的JSON数据,其中screens是屏幕的数组:

var screen = new app.Screen(screens[index]); 

另一种方法是使用类似JSONPath基于id稍微复杂一点来访问对象。