我有一个像这样的AMD模块:
define ['backbone', 'jquery', 'someObj'], (Backbone, $, someObj) ->
class MyModel extends Backbone.Model
# some options
foo = new MyModel
bar = new MyModel
foo.fetch().done ->
# Here I want to do things with foo and bar now that the fetch is complete
# but they are not visible
# Backbone, $, someObj, and MyModel are all visible, however
为什么我可以访问someObj
之类的对象,而不是foo
或bar
?此外,这不是模拟同步代码的正确方法,即。运行只能在解析承诺后才能运行的代码?基本上,我想:
foo
和bar
foo
和/或bar
foo
和bar
做所有需要等待获取的事情似乎已完成可以包含通用的操作(例如console.log "Done"
)或仅访问从promise传递给它的参数。我想我需要使用不同的闭包结构或其他东西,但我只是在如何做我想要的事情上画一个空白。 (我不确定这是否只是我遇到的事情,因为我在AMD模块中,所以我也用RequireJS标记这个。)
答案 0 :(得分:1)
将此内容粘贴到http://coffeescript.org/的尝试Coffeescript REPL中...
define ['backbone', 'jquery', 'someObj'], (Backbone, $, someObj) ->
class MyModel extends Backbone.Model
# some options
foo = new MyModel
bar = new MyModel
foo.fetch().done ->
# Here I want to do things with foo and bar now that the fetch is complete
# but they are not visible
# Backbone, $, someObj, and MyModel are all visible, however
console.log foo, bar
产生这个:
/*snip boilerplate*/
define(['backbone', 'jquery', 'someObj'], function(Backbone, $, someObj) {
var MyModel, bar, foo, _ref;
MyModel = (function(_super) {
__extends(MyModel, _super);
function MyModel() {
_ref = MyModel.__super__.constructor.apply(this, arguments);
return _ref;
}
return MyModel;
})(Backbone.Model);
foo = new MyModel;
bar = new MyModel;
return foo.fetch().done(function() {
return console.log(foo, bar);
});
});
您的关闭似乎可以访问foo
和bar
。所以我不确定你得到的问题是否与done
回调中的变量访问不同。
听起来您必须在浏览器中调试代码才能验证您是否可以看到应该看到的变量。