当我在alert()
内的render
函数中使用UserListView
时,输出会正确显示。如果我发表评论alert()
,则不会显示该视图。
我坚持这个。那是为什么?
以下是代码:
var User = Backbone.Model.extend({
defaults: {}
});
var UserCollection = Backbone.Collection.extend({
model: User,
url: 'http://localhost/cirest/index.php/api/userapi/users'
});
var UserView = Backbone.View.extend({
tagName: 'thumbnail',
className: 'span12',
template: $('#userdetailtemplate').html(),
render: function () {
var tmpl = _.template(this.template);
this.$el.html(tmpl(this.model.toJSON()));
return this;
}
});
var UserListView = Backbone.View.extend({
el: ('#content1'),
initialize: function () {
this.collection = new UserCollection();
this.collection.fetch();
this.render();
},
render: function () {
var that = this;
alert('asdf');
_.each(this.collection.models, function (item) {
that.renderUser(item);
}, this);
},
renderUser: function (item) {
var userview = new UserView({
model: item
});
this.$el.append(userview.render().el);
}
});
$(function () {
var uview = new UserListView();
});
Html页面:
<div id="content1" class="span12"></div>
<script type="text/template" id="userdetailtemplate">
<%= user_name %> <%= user_email %>
</script>
答案 0 :(得分:0)
我通过将UserListView中的initialize函数更改为
来工作initialize: function() {
this.collection = new UserCollection();
this.collection.fetch();
this.collection.on("reset", this.render, this);
this.render();
},
感谢@nikoshr也引用该链接