问题
The following example code works well:
Auth_controller.prototype.isLogged = function(){
//Check if the user is authenticated
var getAuthStatus = this.auth_model.fetch();
return getAuthStatus;
};
Auth_controller.prototype.redirect = function(fragment, args, next){
var getAuthStatus = this.isLogged();
var self = this;
$.when(getAuthStatus).then(function(response){
//Do something with the response
}
});
This doesn't seem to work for a Collection though.
When I console log the collection, I get an empty collection back.
I know that I can use the success callback function from within the method (tested that already), but I don't want to do that, because I want the function to return a promise that I can call from other functions as well.
Edit -> No, sorry it doesn't work in the success callback either so it seems.
Any suggestions for a workaround ?
Edit;
This image shows what is returned from the model and collection fetch methods.
Unless I'm doing something wrong that is obvious, I don't understand why this happens.
When console logging the returned response in the success callback, I see that the empty object as shown in the screenshot, gets populated.
Edit2:
This is what my collection looks like:
define([
/*--- libraries ---*/
'jquery',
'underscore',
'backbone',
/*--- model ---*/
'models/users/role_model'
], function($, _, Backbone,
Role_model){
var Role_collection = Backbone.Collection.extend({
url: '/ingeb/api_v1/users/roles',
model: Role_model
});
return Role_collection;
});
回答1:
Actually, the collection's fetch
does return a promise:
Delegates to Backbone.sync under the covers for custom persistence strategies and returns a jqXHR.
See http://backbonejs.org/#Collection-fetch and http://api.jquery.com/jQuery.ajax/#jqXHR
来源:https://stackoverflow.com/questions/22967191/why-doesnt-backbone-collection-fetch-return-a-promise