Coffeescript,RequireJS,Backbone - @超出了范围

时间:2012-08-02 11:04:06

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

我有以下代码

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请求及其响应。

但是,在“渲染”功能中,看起来“@”处于全局级别,而不是“日历”级别。

这里发生了什么?

3 个答案:

答案 0 :(得分:1)

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

NOT COFFEESCRIPT:

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

希望这有帮助!

答案 1 :(得分:1)

我通过改变

解决了这个问题
($, Backbone, _, days) =>

($, Backbone, _, days) ->

这似乎有效。

答案 2 :(得分:1)

澄清为什么改变脂肪箭头=>细箭头 - >因为Coffeescript编译器故意在这两者之间产生歧视。

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

# 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中的许多模式都需要引用外部作用域,通常称为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'
相关问题