【问题标题】:Coffeescript, RequireJS, Backbone - @ is out of scopeCoffeescript、RequireJS、Backbone - @ 超出范围
【发布时间】:2012-08-02 11:04:05
【问题描述】:

我有以下代码

define [
  "jquery", 
  "backbone", 
  "underscore",
  "models/days"
], ($, Backbone, _, days) =>

  class Calendar extends Backbone.View

    el          : "#calendar_box"
    collection  : days

    display: =>
      @collection.fetch_data
        month :8
        year  :2012
      , @render

    render: =>
      # console.log @collection - gives "undefined"
      console.log @ # this returns "Window" instead of "Calendar" - current obj.

  # return the calendar object
  new Calendar()

这是 Coffeescript 中的 BackboneView,它请求服务器获取给定月份和年份的日期作为日历。

数据返回正常,因为我可以在 Chrome 控制台中检查它 - GET 请求及其响应。

但是,在“render”函数中,“@”看起来是在全局级别,而不是在“Calendar”级别。

这里发生了什么?

【问题讨论】:

    标签: jquery model-view-controller backbone.js coffeescript requirejs


    【解决方案1】:

    查看binding this 上的backbone.js 文档,然后在您的日历中添加一个initialize- 函数并使用下划线bindAll - 函数绑定渲染和其他方法以获得正确的上下文

    不是咖啡脚本:

    initialize: function() {
      _.bindAll(this, 'render', 'display');
    }
    

    希望这会有所帮助!

    【讨论】:

    • 谢谢,但是在使用coffeescript时,我认为您不需要执行“_.bindAll”。
    • 绑定到 this 已经通过在函数定义中使用 => 完成。 => foo; 等价于 javascript/underscore 中的 _.bind(function(){foo;},this)
    • 很好,谢谢你的信息,也许我会看看 CoffeeScript
    【解决方案2】:

    我通过改变解决了它

    ($, Backbone, _, days) =>
    

    ($, Backbone, _, days) ->
    

    这似乎行得通。

    【讨论】:

      【解决方案3】:

      为了澄清为什么将胖箭头 => 更改为细箭头 -> 有效,是因为 Coffeescript 编译器故意在这两者之间进行区分。

      简而言之:胖箭头在外部范围内创建对this 关键字的引用,并使@ 符号引用外部this

      # Coffeescript
      fatArrow => @
      thinArrow -> @
      

      现在是编译好的 Javascript:

      // make a reference to the 'this' keyword (might be the global scope)
      // for the @ symbol inside the fat arrow function
      var _this = this;
      
      fatArrow(function() {
         // the @ symbol does not actually reference 'this'
         // but the outer scope _this variable
         return _this;
      });
      
      thinArrow(function() {
         // the @ symbol in a thin arrow function
         // is the same as the 'this' keyword in javascript
         return this;
      });
      

      为什么?

      javascript 中的许多模式都需要引用外部范围 this,通常称为 self 或在 Coffeescript 的情况下为 _this。例如在事件回调中,常见于 jQuery 等框架中。 Coffeescript 让这一切变得简单,因为您可以只使用粗箭头,而不是使用外部范围 this 参考来混乱您的代码。

      # Coffeescript
      initializeFatGuy = ->
          @eat = (food) -> alert 'eating some #{food}'  
      
          # common example of event callback with double arrow
          $('body').on 'click', (event) =>
              # call the eat method
              # @ is the outer scope _this variable generated by Coffeescript
              @eat 'chips'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-12
        • 2012-05-18
        • 2023-03-27
        • 2012-01-20
        • 2012-05-04
        • 2018-07-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多