视图不能正确显示

view not displaying correctly

本文关键字:显示 不能 视图      更新时间:2023-09-26

当我在UserListView内部的render功能中使用alert()时,输出显示正确。如果我注释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>

我通过改变UserListView中的初始化函数来工作

initialize: function() {
        this.collection = new UserCollection();
        this.collection.fetch();
        this.collection.on("reset", this.render, this);
        this.render();
    },

感谢@nikoshr也提到了那个链接