我能够在控制台中看到json数据,但不能在html中显示。我不知道必须做什么更改才能使它在浏览器中呈现。这是我的密码。
Model.js
var agent = Backbone.Model.extend({
});
var agentList = Backbone.Collection.extend({
model: agent,
url: 'data/agents.json',
});View.js
var agentListView = Backbone.View.extend({
el: '.container',
initialize: function() {
this.template = _.template( tpl.get('agentList'));
},
render: function() {
var agents = new agentList();
agents.fetch({
success: function(agents) {
console.log(agents.toJSON());
}
});
this.$el.html(this.template({ AgentsList: agents.toJSON()}))
},
}); <% _.each(AgentsList, function(item) { %>
<tr>
<td>data</td>
<td><%= item.name%></td>
<td><%= item.gender%></td>
<td><%= item.birthYear%></td>
<td><%= item.skills%></td>
</tr>
<% }); %>发布于 2014-01-21 11:57:54
问题是,您没有在回调中呈现视图,因此不会显示任何内容。
此外,如果您想要尊重MVC原则,那么在呈现函数中获取代理列表肯定不是什么好事。你应该有这样的东西:
var agentCol = new AgentList();
var agentView = new AgentListView({collection: agentCol});
agentCol.fetch({
success: function() {
agentView.render();
}
});你的AgentListView应该看起来像
var AgentListView = Backbone.View.extend({
el: '.container',
initialize: function() {
this.template = _.template(tpl.get('agentList'));
},
render: function() {
this.$el.html(this.template({ agents: this.collection.toJSON()}));
},
});(我冒昧地重命名了一些变量,以匹配命名约定)
发布于 2014-01-21 11:47:26
这可能是因为$el更新代码运行agents集合的时候还没有加载(获取)。
您可以使用下面的代码更新render方法,以便只有在从服务器返回集合fetch时才更新$el。
render: function() {
var $this = this;
var agents = new agentList();
agents.fetch({
success: function(agents) {
console.log(agents.toJSON());
$this.$el.html($this.template({ AgentsList: agents.toJSON() }));
}
});
}或者,您可以收听收集事件(可能是reset),当数据从远程数据源- json文件中获取时,该事件就会触发。
在这种情况下,视图代码可能是,
var agentListView = Backbone.View.extend({
el: '.container',
initialize: function() {
this.template = _.template( tpl.get('agentList'));
this.collection = new agentList();
this.listenTo(this.collection, "reset", this.addAgentsToDom);
},
render: function() {
this.collection.fetch({
success: function(agents) {
console.log(agents.toJSON());
}
});
},
addAgentsToDom: function(collection, options) { // please name the method whatever you want :)
this.$el.html(this.template({ AgentsList: this.collection.toJSON() }));
}
});https://stackoverflow.com/questions/21256719
复制相似问题