如何将backbone.js集合传递给视图并迭代集合,然后呈现视图?

时间:2013-03-16 22:58:11

标签: jquery backbone.js underscore.js

过去,我一直在做的是当我想要渲染并显示带有模板的集合时,只需在集合上调用“each”方法。对于每个模型,我为每个模型创建一个新的单个视图,并将其附加到$ el。但在这种情况下,这是行不通的。我有一个输入类型文本在我的模板中,我不想为每个模型显示一个新的输入。我宁愿以某种方式将集合传递给模板并迭代模板中的集合。另外值得注意的是,在创建此视图的新实例时,我的集合通过我的主应用程序视图传递:

// clientsview.js

define(
[
    'backbone',
    'ClientView',
    'Clients'
], function(Backbone, ClientView, Clients) {

ClientsView = Backbone.View.extend({

    tagName: '#page',
    template: _.template( $('#allClientsTemplate').html() ),


    initialize: function() {
        this.render();
    },

    render: function() {

        // var that = this;
        console.log('collection');
        console.log(this.collection);// successfully returns collection
        console.log('template');
        console.log(this.template);// successfully returns template function


        // This causes an error: 
        //Uncaught TypeError: Cannot call method 'toJSON' of undefined 
        var tmpl = this.template({ clients: this.collection.toJSON() });

        return this;

    }

});
return ClientsView;
});

我在index.html中的模板

// index.html
<script id="allClientsTemplate" type="text/template">
// I do not want create an input for every single model
// but I need the input to be part of the view.
<input type="text" class="table-search" id="search" autocomplete="off"   placeholder="Search Clients…">
<table class="table" id="tblData">
    <thead>
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody id="tblDataBody">

        <% _.each(clients, function(client) { %>

            <tr>
                <td><a href=""><%- client.first_name %></a></td>
                <td><a href=""><%- client.last_name %></a></td>
                <td><a href=""><%- client.status %></a></td>
            </tr>

        <% }); %>

    </tbody>
</script>

我正在我的主应用视图中实例化我的客户端视图:

define(
    [
        'jquery',
        'underscore',
        'backbone',
        'AddClientView',
        'ClientsView',

    ], function( $, _, Backbone, AddClientView, ClientsView ) {

    AppView = Backbone.View.extend({

        initialize: function() {

            // var addClientView = new AddClientView({ collection: this.collection });
            var clientsView   = new ClientsView({ collection:this.collection });


        }

    });
    return AppView;
});

我正在从初始化方法实例化我的主应用程序视图:

define('App', [
    'jquery',
    'underscore',
    'backbone',
    'Router',
    'bootstrap',
    'Clients',
    'AppView'
], function($, _, Backbone, Router, bootstrap, Clients, AppView) {

    function initialize() {

        // for custom global events
        window.vent = _.extend( {}, Backbone.Events )

        var app = new Router();
        Backbone.history.start();


        // probably more appropriate to do this in app view
        var clients = new Clients;// Get collection of clients


        clients.fetch().then( function() {// fetch client collection from db
            new AppView({ collection: clients });
        });

    }
    return {
        initialize: initialize
    };
});

我的initialize方法是从main.js调用的:

// main.js
require.config({
    shim: {
        'underscore': {
         exports: '_'
        },
        'backbone': {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        },
        'bootstrap': {
            deps: ['jquery'],
            exports: 'bootstrap'
        }
    },
    paths: {
        'text'          : 'lib/require/text',
        'jquery'        : 'lib/jquery/jquery-1.9.1',
        'underscore'    : 'lib/underscore/underscore',
        'backbone'      : 'lib/backbone/backbone',
        'bootstrap'     : 'lib/bootstrap/bootstrap',
        'App'           : 'app',
        'Router'        : 'router',
        'AppView'       : 'views/app/appview',
        'Client'        : 'models/clients/client',
        'Clients'       : 'collections/clients/clients',
        'ClientView'    : 'views/clients/clientview',
        'ClientsView'   : 'views/clients/clientsview',
        'AddClientView' : 'views/clients/addclientview'
    }
});
require(['App'], function(App) {
    App.initialize();
});

当我尝试这种方法时出现错误(Uncaught TypeError:无法调用未定义的方法'toJSON')。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

您必须实例化您的集合,向其添加项目,然后实例化视图并将集合传递给它:

var clients= new Clients();
clients.add({FirstName: 'Joe', LastName: 'Blow', Status: 'Active' });

var clientsView = new ClientsView({collection: clients});

您还需要更改模板:

<% _.each(collection, function(client) { %>
<tr>
    <td><a href=""><%- client.get('FirstName') %></a></td>
    <td><a href=""><%- client.get('LastName') %></a></td>
    <td><a href=""><%- client.get('Status') %></a></td>
</tr>
<% }); %>

答案 1 :(得分:0)

你的骨干是正确的。您的问题是,在实例化AppView时,您没有通过fetch创建的承诺传递数据:

您的代码:

clients.fetch().then( function() {// fetch client collection from db
     new AppView({ collection: clients });
});

它应该是:

clients.fetch().then( function(resp) {// fetch client collection from db
     new AppView({ collection: resp.data });
});