3

I'm using Backbone.Marionette's request-response framework to fetch data in collection and then response it to the request object that request it, but obviously it doesn't wait for collection to get populated. And here is my code:

This is where it is requesting the data:

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

and here is where i set my handler:

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

and here is my API's function:

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;
    }
}
4

1 回答 1

8

使用 promise 将结果传回:

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
});
于 2013-08-27T14:46:56.160 回答