【问题标题】:Closure confusion: accessing objects when jQuery promise is done闭包混淆:当 jQuery 承诺完成时访问对象
【发布时间】:2013-06-12 21:37:07
【问题描述】:

我有一个这样的 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 这样的对象,但不能访问foobar?另外,这不是模拟同步代码的正确方法吗?运行只能在承诺解决后才能运行的代码?本质上,我想:

  1. 实例化foobar
  2. 从服务器获取foo 和/或bar
  3. foobar 执行所有需要等待获取的操作

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

【问题讨论】:

    标签: jquery coffeescript requirejs promise


    【解决方案1】:

    将其粘贴到 Try Coffeescript REPL http://coffeescript.org/...

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

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

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

    【讨论】:

    • 是的,你是对的;这行得通。显然,我以某种方式过度简化了这个例子。我会尝试更新它以反映更多真实代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多