user240993
user240993

Reputation:

Backbone: fetch and scope

Think I been staring at this to long but, I'm trying to bring an object outside the scope of the fetch success method when it completes the fetch.

cars.fetch().complete(function(){
    newSuggested = cars.models.filter(function (model) { 
       return _.contains(model.attributes.suggestedTo, storedVin)  
    });
})
console.log(newSuggested) //undefined

How can I get the newSuggested outside the fetch scope after it successfully fetched?

Upvotes: 1

Views: 517

Answers (2)

Paul Hoenecke
Paul Hoenecke

Reputation: 5060

Unless you have declared newSuggested somewhere above in the code, it is a global variable on the window (this is not the problem, just pointing it out).

The reason it is undefined where you are logging it, is because when that console.log statement is run, the fetch has not completed.

Whatever you are going to do with newSuggested, you need to do it from within the complete callback function.

// declare the variable using var, so it is not global
var newSuggested;
cars.fetch().complete(function(){
    newSuggested = cars.models.filter(function (model) { 
       return _.contains(model.attributes.suggestedTo, storedVin)  
    });
    console.log(newSuggested); // works!
    // do something with newSuggested here, hard to tell what you are trying to do.
    probablyUpdateViewInSomeWay(newSuggested);
});
// fetch not complete here!
// this is not a scope problem, but an async problem.
// complete callback has not been called yet.
console.log(newSuggested) //undefined, this is expected

Side note: complete is deprecated in jQuery 1.8, so you should use done instead.

Upvotes: 1

BG Adrian
BG Adrian

Reputation: 485

Your script is correct, you can even explicitly use window.newSuggested to make the variable global (though is default like this). You have to move the console.log after "complete" as call order in the execution flow

cars.fetch().complete(function(){
    window.newSuggested = cars.models.filter(function (model) { 
       return _.contains(model.attributes.suggestedTo, storedVin)  
    });
    global_log();
})

function global_log(){console.log(newSuggested);};

Upvotes: 0

Related Questions