1

想我一直盯着这个很久,但是,当它完成提取时,我试图将一个对象带到提取成功方法的范围之外。

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

成功获取后如何获取范围newSuggested之外的内容?fetch

4

2 回答 2

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

旁注:complete在 jQuery 1.8 中已弃用,因此您应该done改用。

于 2013-02-28T16:23:34.727 回答
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);};
于 2013-02-28T16:30:37.323 回答