主干.js:获取特定的 JSON 部分
Backbone.js: Fetching specific JSON sections
我正在尝试为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 的对象,这有点复杂。
相关文章:
- jQuery匹配JSON对象的部分文本
- 我什么时候应该把JSON分成更小的部分
- 使用Backbone.js访问JSON响应的部分
- 提取API对Javascript中JSON对象响应的特定部分
- 找到 JSON 数组的特定部分,然后在 Angular 中更深入
- 如何获取部分 JSON 字符串
- 将 json 数组的一部分分别排序到同一数组的其他部分
- 如何获取部分 JSON 对象的值
- 解析json只能部分工作
- 如何加载包含对象对象的 JSON 文件的每个部分
- 使用javascript显示部分JSON数据
- 如何从JSON对象部分获取URL
- 当连接在一起时,如何使用两个部分构建 JSON 对象,生成正确的 JSON 数据路径
- 如何获取 JSON 的部分内容
- 如何从 API 响应中提取部分 JSON
- 从部分 JSON 中提取少量案例
- 部分平展的 JSON 的反序列化
- 主干.js:获取特定的 JSON 部分
- Django 使用 Ajax/JSON 更新部分 HTML
- 检索复杂的 JSON 响应并显示我想要的部分