Backbone Marionette.js reqres框架不等待集合填充

时间:2013-08-27 14:18:10

标签: javascript backbone.js fetch marionette backbone-collections

我正在使用Backbone.Marionette的请求 - 响应框架来获取集合中的数据,然后将其响应给请求它的请求对象,但显然它不会等待集合被填充。这是我的代码:

这是它请求数据的地方:

// Module: Timeline, ListController
var employees = App.request('employee:timeline');

这里是我设置我的处理程序的地方:

// Entities Module
App.reqres.setHandler('employee:timeline', function() {
    return API.getEmployeesForTimeline();
});

这是我的API函数:

getEmployeesForTimeline: function() {
    var employees = new Entities.EmployeeCollection();

    employees.fetch({
        success: function(employees) {
            returnEmployees(employees);
        }
    });

    function returnEmployees(employees) {
        // doing some things with employees collection
        return leaves;
    }
}

1 个答案:

答案 0 :(得分:8)

使用承诺将结果传回:

getEmployeesForTimeline: function() {
    var employees = new Entities.EmployeeCollection();
    var deferred = $.Deferred();
    employees.fetch({
        success: deferred.resolve
    });

    return deferred.promise();
}

// Entities Module: UNCHANGED
App.reqres.setHandler('employee:timeline', function() {
    return API.getEmployeesForTimeline();
});

//request data
var promise = App.request('employee:timeline');
promise.done(function(employees){
    //use employees
});