主干.js:获取特定的 JSON 部分

Backbone.js: Fetching specific JSON sections

本文关键字:JSON 部分 js 获取 主干      更新时间:2023-09-26

我正在尝试为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(); 

});

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

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

另一种方法是使用类似 JSONPath 的东西来访问基于 id 的对象,这有点复杂。