Backbone.js在View中呈现集合,但无法访问数据

时间:2013-09-23 07:10:50

标签: javascript json backbone.js requirejs

我有一个代表json对象的Backbone Collection,我试图在View中渲染这些对象,将它们迭代到模板中。我认为断点是我无法将json数组读入数组

集合返回数组

{

    "calls": [
        {
            "callId": "173",
            "company": "Company 1",
            "status": "open",
            "DueDate": "2013-06-10 00:00:00",
            "EmployeeId": "12"
        },
        {
            "callId": "170",
            "company": "company 2",
            "status": "done",
            "DueDate": "2013-05-27 14:27:37",
            "EmployeeId": "11"
        },
        {
            "callId": "169",
            "company": "Company 3",
            "status": "open",
            "DueDate": "2013-05-20 00:00:00",
            "EmployeeId": "11"
        }
]

}

路线

// Filename: router.js
define([
    'jquery',    
    'underscore',
    'backbone',    
    'app/collections/schedule',
    'app/views/schedule',
    'app/views/dashboard'
], function($, _, Backbone, ScheduleCollection, ScheduleView, DashboardView) {
    var AppRouter = Backbone.Router.extend({
        routes: {
            // Define some URL routes
            'dash': 'defaultRoute',
            'schedule': 'scheduleRoute',
            'accounts': 'accountsRoute',
            'reports': 'reportsRoute',
            // Default
            '*actions': 'defaultRoute'
        },
        scheduleRoute: function() {
            // Create a new instance of the collection
            // You need to set the url in the collection as well to hit the server
            var schedulecollection = new ScheduleCollection();
            // Pass in the collection as the view expects it            
            var scheduleview = new ScheduleView({
                collection: schedulecollection                        
            });            
           //scheduleview.initialize();
           // No need of calling render here
           // as the render is hooked up to the reset event on collection          
        },
        defaultRoute: function(actions) {            
            // We have no matching route, lets display the home page
            DashboardView.render();
        }
    });

    var initialize = function() {                
        var app_router = new AppRouter;
        Backbone.history.start();
    };
    return {
        initialize: initialize
    };
});

集合

// Filename: collections/schedule
define([
    'jquery',
    'underscore',
    'backbone',
    'app/models/schedule'
], function ($, _, Backbone, ScheduleModel) {
    var ScheduleCollection = Backbone.Collection.extend({
        model: ScheduleModel,
        url: "http://sam-client:8888/sam-client/i/schedule",
        initialize: function () {
            //console.log('schedule collections loaded successfully');
        }
    });
    return ScheduleCollection;
});

查看

// Filename: views/schedule
define([
    'jquery',
    'underscore',
    'backbone',
    'text!templates/schedule.html'
], function ($, _, Backbone, ScheduleTemplate) {

    var scheduleView = Backbone.View.extend({        
        el: $("#test"),
        initialize: function () {
            // Listen to the reset event which would call render
            this.listenTo(this.collection, 'reset', this.render());
            // Fetch the collection that will populate the collection
            // with the response 
            this.collection.fetch();                            
        },
        render: function () {   
            var data = {
              schedule: this.collection.models,
              _: _
            };
            var compiledTemplate = _.template(ScheduleTemplate, data);
            this.$el.html(compiledTemplate);                
        }
    });  
    return scheduleView;
});
模板中的

<ul>
  <% _.each(schedule, function(call){ %>
   <li><%= call.get("company") %> - <%= call.get("DueDate") %></li> 
  <% }); %>
</ul>

问题是模板中没有传递数据以便迭代

1 个答案:

答案 0 :(得分:0)

Backbone 1.0中Collection#fetch的行为发生了变化:

  

抓取 collection.fetch([options])

     

[...]当模型数据从服务器返回时,它使用 set 来(智能地)合并获取的模型,除非你通过{reset: true},在这种情况下集合将(有效地)重置

所以就这样:

this.collection.fetch()

将触发Backbone 1.0+中的'add''remove''change'事件,而不是像旧版Backbone那样的单个'reset'事件。如果你说:

this.collection.fetch({ reset: true })

然后你就会得到你的'reset'事件。

下一个问题是您的JSON格式。 Backbone集合期望传入的数据是模型属性对象的简单数组,但是您的JSON具有嵌套在"calls"内的数组。您可以在集合中提供parse方法来解开包装:

parse: function(response) {
    return response.calls;
}

您需要在ScheduleCollection

中使用该方法