我是骨干js的新手,不知怎的,我设法读取了json文件并将数据传送给控制器。现在我如何将数据传递给我的视图。如果数据显示为ul标签,我没问题。我想要的是显示json文件中的数据。
(function($){
var model = Backbone.Model.extend({});
collection = Backbone.Collection.extend({
url:'services.json',
model:model,
parse:function(response){
console.log(response.values); //Working
return response.values;
}
});
var ListView = Backbone.View.extend({
el: $('body'), // attaches `this.el` to an existing element.
initialize: function(){
_.bindAll(this, 'render'); // fixes loss of context for 'this' within methods
this.render(); // not all views are self-rendering. This one is.
},
render: function(eventName) {
_.each(this.model.models, function(){
$(this.el).append(); //How to display the values here
}, this);
return this;
}
});
source = new collection();
var listView = new ListView({model:source});
source.fetch({
success: function (values) {
var data = values.toJSON();
console.log(data); //Working
listView.render();
}
});
})(jQuery);
JSON
{
"values": [
{
"name": "name A",
"location": "location A"
},
{
"name": "name B",
"location": "location B"
}
]
}
答案 0 :(得分:0)
您的代码中存在多个问题
1)你不应该将集合作为模型传递,改为
var listView = new ListView({collection:source});
2)不要多次调用渲染,它应该在ajax之后调用,所以从视图中删除渲染< s初始化
initialize: function(){
_.bindAll(this, 'render'); // fixes loss of context for 'this' within methods
},
3)追加到dom
render: function(eventName) {
this.collection.each(function(model) {
this.$el.append('li'+model.get('name');+'<li>');
}
}