Backbone:获取和范围

时间:2013-02-28 16:10:52

标签: javascript jquery backbone.js

认为我一直盯着这个,但是,当我完成提取时,我试图将一个对象置于fetch success方法的范围之外。

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

如果newSuggested范围成功获取后,我怎样才能获得fetch范围?

2 个答案:

答案 0 :(得分:1)

除非你在代码中的某处上面声明了newSuggested,否则它就是窗口上的全局变量(这不是问题,只是指出来了。)

在您记录它的位置未定义的原因是,当运行console.log语句时,提取尚未完成。

无论您要使用newSuggested做什么,都需要在complete回调函数中执行此操作。

// 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

旁注:jQuery 1.8中不推荐使用complete,因此您应该使用done代替。

答案 1 :(得分:0)

你的脚本是正确的,你甚至可以明确地使用window.newSuggested来使变量成为全局变量(尽管这是默认的)。 您必须将“完成”后的console.log作为执行流程中的呼叫顺序

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