Javascript Backbone.js呈现视图中的集合,但可以';t访问数据

Javascript Backbone.js呈现视图中的集合,但可以';t访问数据,javascript,json,backbone.js,requirejs,Javascript,Json,Backbone.js,Requirejs,我有一个表示json对象的主干集合,我试图在视图中呈现这些对象,并将它们迭代到模板中。我认为断点是我无法将json数组读入数组 集合返回数组 { "calls": [ { "callId": "173", "company": "Company 1", "status": "open", "DueDate": "2013-06-10 00:00:00",

我有一个表示json对象的主干集合,我试图在视图中呈现这些对象,并将它们迭代到模板中。我认为断点是我无法将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
    };
});
<ul>
  <% _.each(schedule, function(call){ %>
   <li><%= call.get("company") %> - <%= call.get("DueDate") %></li> 
  <% }); %>
</ul>
收藏

// 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;
});
在模板中

// 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
    };
});
<ul>
  <% _.each(schedule, function(call){ %>
   <li><%= call.get("company") %> - <%= call.get("DueDate") %></li> 
  <% }); %>
</ul>
  • -
如果主干网1.0中的行为发生了变化,则问题在于模板中没有传递数据以进行迭代:

fetch
collection.fetch([options])

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

那么就这样:

this.collection.fetch()
将在主干网1.0+中触发
'add'
'remove'
'change'
事件,而不是像旧版本的主干网那样触发单个
'reset'
事件。如果你说:

this.collection.fetch({ reset: true })
然后您将获得您的
“重置”
事件

下一个问题是JSON格式。主干集合期望传入的数据是一个简单的模型属性对象数组,但JSON的数组嵌套在
“calls”
中。您可以在收藏中提供一种方法来展开物品:

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

您希望在
ScheduleCollection

中使用该方法,我建议的第一个更改是,
views/schedule
,替换行
this.listenTo(this.collection,'reset',this.render())
this.listenTo(this.collection,'reset',this.render)
,原因是,对于
列表,我们只需要传递对
this的引用。render
作为参数,我们不需要调用该方法,因此在调用
render
时,没有数据存在,以便从模板生成正确的html。更改它时,无法加载模板。。我认为render未被调用当您从
render
中删除
()
时,是否在集合重置时调用render?不,因此我必须添加它。您知道,我们不能调用方法-render,我们只需将
回调
传递给
listenTo
,从服务器获取集合后,将自动调用。