0

我有以下代码

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”级别。

这里发生了什么?

4

3 回答 3

1

Check the backbone.js docs on binding this and then add an initialize- function into your Calendar and use the underscore bindAll -function to bind render and other methods to have the right context

NOT COFFEESCRIPT:

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

Hope this helps!

于 2012-08-02T11:39:00.103 回答
1

I solved it by changing

($, Backbone, _, days) =>

to

($, Backbone, _, days) ->

That seems to work.

于 2012-08-02T11:39:33.357 回答
1

为了澄清为什么将胖箭头 => 更改为细箭头 -> 有效,是因为 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'
于 2012-10-29T17:09:41.707 回答