Backbone.js:使用模板时未定义集合

时间:2015-04-14 23:42:32

标签: jquery backbone.js requirejs underscore.js

我目前正在尝试自己学习backbone.js。我查看了Thomas Davis的@ https://backbonetutorials.com/和youtube频道等教程。我正在尝试使用require.js,underscore.js,text.js来渲染模板和jquery来创建模块化主干应用程序。

我遇到了一个问题,在我的集合视图中,我正在获取一个JSON对象,但它不在模板上呈现。我已经看过很多SO解决方案,到目前为止,没有骰子。

Backbone View(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;
});

收藏集(Users.js)

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

模板(用户列表模板)

<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服务并从数据库中提取数据。 我在我的馆藏中调用了.fetch(),我做了一个console.log(that.collection.toJSON());,在我的JS控制台上使用chrome,我得到了我的对象。

根据JS控制台,它在我视图中的that.$el.html(template);行处断开。消息是:

Uncaught ReferenceError: users is not defined

所以,这就是事情。当我在一个页面上拥有所有内容时,包括模板,javascripts和各种各样的东西,一切都有效。然而,当我试图模块化它时,它就会破裂。没有线索。

我将非常感谢所有的帮助。 感谢。

1 个答案:

答案 0 :(得分:0)

您错误地使用了_.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);
    }
});
相关问题