0

私はJavascriptで次のようなコードを持っています:

 _.each(this.collection.models, function (student) {
            $(this.el).append(new StudCloneItemView({ model: student }).el);
        }, this);    

私がこれをcoffescriptで書いている間

_.each this.collection.models  , (student) => 
$(@el).append new Item ({ model:student }).el   

を生成します

_.each(this.collection.models, function(student) {
      return $(_this.el).append(new Item({
        model: student
      }.el));
    });

私の要件によると、これは望ましくありません。「this」要素の最後のセグメントが、生成されたjavascriptに含まれていません。それは非常に重要です。

_.eachで言及したコーヒースクリプトを使用して、上記のJavaScriptをどのように生成しますか????

とにかくそれをすることはありますか?または、構文が欠落していますか?

4

2 に答える 2

1

このような:

_.each @collection.models, ((student) ->
  $(@el).append new StudCloneItemView(model: student).el
), this
于 2012-09-01T21:00:01.067 に答える
1

あなたの JavaScript:

_.each(this.collection.models, function (student) {
    $(this.el).append(new StudCloneItemView({ model: student }).el);
}, this);

そしてあなたの=>CoffeeScriptが生成するもの:

var _this = this; // This is somewhere above your _.each in the generated JS
_.each(this.collection.models, function(student) {
    return $(_this.el).append(new Item({
        model: student
    }.el));
});

機能的に同等です。は、コールバック内で使用される (と呼ばれる)のエイリアスを生成する_.eachため、 context 引数は必要ありません。=>this_this


余談ですが、Backbone コレクションにはさまざまな Underscore メソッドが混在しているため、言う必要はありません。コレクションで直接_.each(@collection.models, ...)使用できます。each

@collection.each (student) =>
    @$el.append(new StudCloneItemView(model: student).el)

また、ビューが既に持っているビルド済みのものに切り替えました$el。反復ごとに新しい jQuery オブジェクトをビルドする必要はありません。

于 2012-09-01T21:26:30.410 に答える