Monece Solis
Monece Solis

Reputation: 703

backbone.fetch using "return" only returns undefined instead of the specific value

Hi i'm new to backbonejs,

I created a function to validate sessions and have if and else statements through my routes when calling this function

var validateSession = function(){
    var session = new sessionCollection();
    session.fetch( {
        success : function(){
            return true;
        },
        error : function(){
            CarRentalApp.trigger('admin:login');
            return false;
        }
    } );
};

the problem is the "return" statement is not working out for me. Instead of returning true or false, it returns undefined instead. Am I missing something?

Upvotes: 0

Views: 195

Answers (2)

user2503775
user2503775

Reputation: 4367

You can also use $.Deferred()

var validateSession = function(){
    var defer = $.Deferred();
    var session = new sessionCollection();
    session.fetch( {
        success : function(){
            defer.resolve(true);
        },
        error : function(){
            defer.resolve(false);
        }
    });
    return defer.promise();
};

And then:

$.when(validateSession()).done(function(result){
});

Upvotes: 2

Hetfield Joe
Hetfield Joe

Reputation: 1453

I think this is a javascript question rather than backbone. Backbone.Collection.fetch method is an asynchronous method, that means if you do this:

validateSession();

the function will call session.fetch() and then return immediately, it won't wait the fetch() method finish it's job. you don't have return statement in the validateSession function, so it just return you undefined. and when the fetch() method finished, you won't get any notification.

if you want get the result of session.fetch(), I think you'd better trigger events in both cases of success and error:

var validateSession = function(){
    var session = new sessionCollection();
    session.fetch( {
        success : function(){
            CarRentalApp.trigger('valid:true');
        },
        error : function(){
            CarRentalApp.trigger('valid:false');
        }
    } );
};

then listen on these two events and do some process respectively.

hope this can help.

Upvotes: 1

Related Questions