2011-07-27 3 views
4

だからここに私の見解である:理解BACKBONE.JSイベントハンドラ

$(function() { 
var ImageManipulation = Backbone.View.extend({ 

    el: $('body'), 
    tagName: "img", 

    events: { 
     'mouseover img': 'fullsize', 
     'click img#current': 'shrink' 
    }, 
    initialize: function() { 
     _.bindAll(this, 'render', 'fullsize', 'shrink'); 

     //var message = this.fullsize; 
     //message.bind("test", this.fullsize); 
    }, 
    render: function() { 

    }, 
    fullsize: function() { 
     console.log("in fullsize function"); 
     console.log(this.el); 
     $('.drop-shadow').click(function() { 
      console.log(this.id); 
      if (this.id != 'current') { 
       $('.individual').fadeIn(); 
       $(this).css('position', 'absolute'); 
       $(this).css('z-index', '999'); 
       $(this).animate({ 
        top: '10px', 
        height: '432px', 
       }, 500, function() { 
        this.id = "current"; 
        console.log("animation complete"); 
        return true; 
       }); 
      }; 
     }); 
    }, 
    shrink: function() { 
     $('.individual').fadeOut(); 
     $('#current').animate({ 
      height: '150px', 
     }, 500, function() { 
      this.id = ""; 
      $(this).css('position', 'relative'); 
      $(this).css('z-index', '1'); 
      console.log("animation complete"); 
      return true; 
     }); 
    } 
}); 
var startImages = new ImageManipulation(); 
}); 

私は理解していない何これは "フルサイズで私が持ってクリック機能を引き継ぐ作るためにエルを変更する方法です。私はむしろクリックjQuery関数を削除して、マウスオーバー機能を別のクリックにすることはできますが、クリックする特定の画像に 'this'を割り当てる方法を見つけることはできません。私の質問が意味をなさないことを願っている

+0

を私はあなたがシリアライズを使用する必要がかもしれないと思う 'ます。http:// documentcloud.github.com /バックボーン/#表示-extend'も' el: 'body''は '$(' body ')ではありません。例の1つで、おそらくオブジェクトではなく文字列になると期待しています – Val

答えて

16

バックボーンのイベントハンドラは、すべてのイベントのオブジェクト(そのコードとそのDOM表現、View.elオブジェクト)について知りたいと仮定し、イベントはビューの一部の外観を変更することを意図していると仮定します。モデル。クリックの実際のターゲットは、あなたが知っていると仮定しているか、または引き出せると想定されているものです。

導出はかなり単純です:

fullsize: function(ev) { 
    target = $(ev.currentTarget); 

そしてtarget.へお電話内のすべてのあなたのthis.の参照を交換してください。 this.は引き続きViewインスタンスを参照します。内部関数では、.drop-shadowthis.に割り当てられた匿名の人物は、ちょうどクリックされたオブジェクトを参照します。あなたは、周囲の状況へのアクセス、閉鎖転送イディオムを使用する場合:

fullsize: function(ev) { 
    var target = ev.currentTarget; 
    var self = this; 
    $('.drop-shadow').click(function(inner_ev) { 
     console.log(this.id); // the same as inner_ev.currentTarget 
     console.log(self.cid); // the containing view's CID 
+1

ファンタスティックな説明エルフ!私のコードはもっと簡潔になりました。私はBackboneについてもっと理解しています! – thatmiddleway

+2

一般的な方法は、内部関数を 'this'(Viewオブジェクト)にバインドし、代わりに' ev.currentTarget'を使う '_.bind()'メソッド(バックボーンの依存関係、underscore.jsによって提供)を使用することです「自己/この」トリックの –