Backbone.js: Collection 在使用模板时未定义

Backbone.js: Collection is undefined when using template

我目前正在尝试自学 backbone.js。我看过 Thomas Davis 的@https://backbonetutorials.com/ 和 youtube 频道等教程。我正在尝试制作一个模块化的 backbone 应用程序,使用 require.js、underscore.js、text.js 来呈现我的模板,以及 jquery.

我 运行 遇到一个问题,在我的 collections 视图中,我得到了一个 JSON object,但它没有在模板上呈现。我看过很多 SO 解决方案,但到目前为止,还没有。

Backbone 查看 (list.js)

define([
'jquery',
'underscore',
'backbone',
'collections/Users',
'text!templates/user-list-template.html'],
function ($, _, Backbone, Users, UserListTemplate) {
    var UserList = Backbone.View.extend({
        el: '.page',
        render: function () {
            var that = this;
            that.collection = new Users();
            that.collection.fetch({
                success: function () {
                    var template = _.template(UserListTemplate,
                                     {users: that.collection.models});
                    that.$el.html(template);
                }
            });
        }
    });
    return UserList;
});

Collections (Users.js)

define(['backbone', 'models/User'],
function (Backbone, User) {
    var Users = Backbone.Collection.extend({
        model: User,
        url: 'restapiurl'
    });
    return Users;
});

模板 (user-list-template)

<script type="text/template" id="user-list-template"> 
    <table class="table">
        <thead>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Age</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <% _.each(users, function(user) { %>
                <tr>
                    <td><%= user.get('firstname') %></td>
                    <td><%= user.get('lastname') %></td>
                    <td><%= user.get('age') %></td>
                    <td><a href="#/edit/<%= user.get('id') %>" class="btn btn-info">Edit</a></td>
                </tr>
            <% }); %>
        </tbody>
    </table>
</script>

现在,我可以访问我的 REST 服务并从我的数据库中提取数据。 我在我的 collections 上调用了 .fetch(),我做了一个 console.log(that.collection.toJSON());,在我的 JS 控制台上 chrome,我得到了我的 object.

根据 JS 控制台,在我看来它在 that.$el.html(template); 行中断。消息是:

Uncaught ReferenceError: users is not defined

事情是这样的。当我将所有内容都放在一个页面上时,包括模板、javascript 和各种类型,一切正常。但是,当我尝试将其模块化时,它就崩溃了。没有线索。

我将不胜感激所有帮助。 谢谢。

您使用的 _.template 方法不正确。 _.template 将字符串编译成 Javascript 函数接收数据并输出 HTML.

这应该可以解决问题:

var UserList = Backbone.View.extend({
    el: '.page',
    template: _.template(UserListTemplate),
    initialize: function() {
        // collections are normally passed into views, but it's not a big deal
        this.collection = new Users();
        // when the collection gets data (sync), call render
        this.listenTo(this.collection, 'sync', this.render);
        this.collection.fetch();
    },
    render: function () {
        var data = { users: this.collection.models },
            html = this.template(data);

        this.$el.html(html);
    }
});