当我手动定义我的收藏内容时,一切正常。但是在我尝试从服务器获取数据后(我得到了有效的响应),我的视图没有显示。正在显示集合视图(ul),但单个视图(li)不是?在将数据提取到集合时,我需要注意什么?
更新
的 main.js 的
require.config({
paths: {
"jquery":"vendor/jquery/jquery",
"underscore":"vendor/underscore-amd/underscore",
"backbone":"vendor/backbone-amd/backbone",
"text":"../vendor/requirejs/text",
"mustache": "../vendor/mustache/mustache"
},
shim: {
underscore: {
exports: "_"
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
}
}
});
require([
'app',
], function(App){
// The "app" dependency is passed in as "App"
App.initialize();
});
的 app.js 的
define([
'jquery',
'underscore',
'backbone',
'collections/ObjaveCollection',
'views/ObjaveView'
], function($, _, Backbone,ObjaveCollection,ObjaveView){
var initialize = function(){
var objave = new ObjaveCollection();
objave.fetch();
var objaveView = new ObjaveView({ collection: objave});
$(document.body).append(objaveView.render().el);
}
return {
initialize : initialize
};
});
的 ObjavaModel.js 的
define([
'jquery',
'underscore',
'backbone'
], function($, _, Backbone){
var ObjavaModel = Backbone.Model.extend({
defaults:{
naslov: 'My service',
cijena: 100,
}
});
return ObjavaModel;
});
的 ObjaveCollection.js 的
define([
'jquery',
'underscore',
'backbone',
'models/ObjavaModel'
], function($, _,Backbone,ObjavaModel){
var ObjaveCollection = Backbone.Collection.extend({
model: ObjavaModel
});
return ObjaveCollection;
});
的 ObjavaView.js 的
define([
'jquery',
'underscore',
'backbone',
'text!templates/objavaTemplate.html',
'mustache',
], function($, _, Backbone,objavaTemplate,Mustache){
var ObjavaView = Backbone.View.extend({
tagName: "li",
initialize: function () {
this.template = objavaTemplate;
},
render: function() {
rendered = Mustache.to_html(this.template, this.model.toJSON());
$(this.el).html(rendered);
return this;
}
});
return ObjavaView;
});
的 ObjaveView.js 的
define([
'jquery',
'underscore',
'backbone',
'views/ObjavaView'
], function($, _, Backbone,ObjavaView){
var ObjaveView = Backbone.View.extend({
tagName: 'ul',
render: function() {
this.collection.each(function(item) {
console.log(item);
var objavaView = new ObjavaView({ model: item });
console.log(this.$el);
this.$el.append(objavaView.render().el);
}, this);
return this;
}
});
return ObjaveView;
});
答案 0 :(得分:2)
您是在取回数据后重新渲染视图吗?例如,在您的视图(ObjaveView.js)中添加:
initialize: function () {
this.listenTo(this.collection, "sync", this.render);
}