1

我正在处理一个简单的backbone.js 示例。问题是在页面加载时它没有在页面上显示任何内容。但是,在 Chrome 调试器控制台中,如果我显式调用视图及其 render() 方法,则结果会以正确的 json 数据显示在屏幕上。

任何帮助都会非常非常感谢!

var Clients = Backbone.Collection.extend({

    model: Client,
    url: 'api/Contacts'

});

var clients = new Clients();


var UserItemView = Backbone.View.extend({
    tagName: 'li',
    template: _.template($('#contacts-template').html()),
    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});


var UserListView = Backbone.View.extend({
    el: $('#contacts'),

    render: function() {
        this.$el.empty();
        var self = this;

        _.each(this.collection.models, function(model) {
            self.renderItem(model);
        });
    },

    renderItem: function(item) {
        var itemView = new UserItemView({
            model: item
        });

        this.$el.append(itemView.render().el);
    }
});

下面是 index.html 页面的代码:

<ul id="contacts"></ul>

<script id="contacts-template" type="text/template">

    <%= FirstName %> <%= LastName %>

</script>


<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.3/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<script src="scripts/app/app.js"></script>
<script>

    $(document).ready(function () {

        alert('HI'); // I verified this alert works

        clients.fetch();

        var userListView = new UserListView({ collection: clients });

        userListView.render();

    });

</script>
4

1 回答 1

2

每个异步调用完成后都应该有一个回调,在这里您尝试在clients收集来自服务器的数据之前使用它。我会将代码更改为:

$(document).ready(function () {
    alert('HI'); // I verified this alert works
    clients.fetch(
        success: function() {
            var userListView = new UserListView({ collection: clients });
            userListView.render();
        },

        error: function() {
            alert('An error has occurred');
        },
    );
});

问候,

于 2012-12-27T18:42:19.900 回答