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

これをバインドする際に backbone.js のドキュメントを確認してから、初期化関数を Calendar に追加し、アンダースコア関数を使用してbindAllrender およびその他のメソッドをバインドし、適切なコンテキストを取得します。

コーヒースクリプトではない:

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

お役に立てれば!

于 2012-08-02T11:39:00.103 に答える
1

変更したら解決しました

($, Backbone, _, days) =>

($, Backbone, _, days) ->

それはうまくいくようです。

于 2012-08-02T11:39:33.357 に答える
1

太い矢印 => から細い矢印 -> に変更する理由を明確にするのは、Coffeescript コンパイラがこれら 2 つを意図的に区別するためです。

一言で言えば:太い矢印は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 に答える