【问题标题】:Backbone.js render collection in View, but can't access dataBackbone.js 在视图中呈现集合,但无法访问数据
【发布时间】:2013-09-23 07:10:50
【问题描述】:

我有一个代表 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
    };
});

收藏

// 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>

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

【问题讨论】:

  • 我想建议的第一个更改是views/schedule,将this.listenTo(this.collection, 'reset', this.render()); 替换为this.listenTo(this.collection, 'reset', this.render);,原因是,到listenTo 我们只需要传递对@ 的引用987654331@作为参数,我们不需要调用方法,所以在调用render的时候,没有数据存在,无法从模板生成正确的html。
  • 更改它时,模板无法加载..我认为渲染未调用
  • 当您从 render 中删除 () 时,是否会在集合重置时调用渲染?
  • 不,所以我必须添加它
  • 你知道根据docs,我们不能调用方法-render,我们只需要将callback传递给listenTo,获取集合后会自动调用来自服务器。

标签: javascript json backbone.js requirejs


【解决方案1】:

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 格式。骨干集合期望传入的数据是模型属性对象的简单数组,但您的 JSON 具有嵌套在 "calls" 内的数组。你可以在你的集合中提供一个parse 方法来解包:

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

您希望在 ScheduleCollection 中使用该方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多