backbonejs查看如何显示
backbone js view how to display
我是 backbone js 的新手,我设法读取了 json 文件并将数据发送到控制器。现在我如何将数据传递到我的视图。如果数据显示为 ul tags.All 我没问题 我想要的是显示来自 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"
}
]
}
您的代码中存在多个问题
1) 你不应该将集合作为模型传递,更改为
var listView = new ListView({collection:source});
2) 不要多次调用渲染,它应该在 ajax 之后调用,所以从视图的初始化中移除渲染
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>');
}
}
我是 backbone js 的新手,我设法读取了 json 文件并将数据发送到控制器。现在我如何将数据传递到我的视图。如果数据显示为 ul tags.All 我没问题 我想要的是显示来自 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"
}
]
}
您的代码中存在多个问题
1) 你不应该将集合作为模型传递,更改为
var listView = new ListView({collection:source});
2) 不要多次调用渲染,它应该在 ajax 之后调用,所以从视图的初始化中移除渲染
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>');
}
}