0

我有一个像这样的 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

为什么我可以访问对象 like someObj,但不能访问fooor bar?另外,这不是模拟同步代码的正确方法吗?运行只能在承诺解决后才能运行的代码?本质上,我想:

  1. 实例化foobar
  2. 从服务器获取foo和/或bar
  3. 做所有需要等待获取foo的事情bar

似乎 done 可以包含通用的操作(例如console.log "Done")或仅访问从承诺传递给它的参数。我想我需要使用不同的闭包结构或其他东西,但我只是对如何做我想做的事一无所知。(我不确定这是否只是我正在经历的事情,因为我在 AMD 模块中,所以我也用 RequireJS 标记它)。

4

1 回答 1

1

将其粘贴到http://coffeescript.org/的Try 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);
  });
});

看来您的闭包应该可以访问fooand bar。因此,我不确定您遇到的问题是否与done回调中的变量访问不同。

听起来您必须在浏览器中调试代码才能验证您是否可以看到您应该看到的变量。

于 2013-06-18T10:44:03.833 回答