2012-03-28 21 views
1

イベントハンドラでイベントを発生させたImageListItemViewへの参照を取得するにはどうすればよいですか?ここでBackbone.jsのイベントハンドラで元のオブジェクトへの参照を取得する

addOne: function(image){ 
    var imageListItemView = new ImageListItemView({model: image}); 
    imageListItemView.on('imageListItemView:click', this.itemViewClick, this) 
    imageListItemView.render(); 
    this.$el.append(imageListItemView.el); 
}, 

itemViewClick: function(){ 
    //Get reference to ImageListItemView that originated event 
} 

はImageListItemViewです:

// ImageListItemView 
//-------------------------------------------------------------------------------// 

window.ImageListItemView = Backbone.View.extend({ 

    initialize: function(){ 
     this.model.on('change', this.render, this); 
     this.model.on('destroy hide', this.remove, this); 
     this.model.on('image:selectionChange', this.select, this); 
    }, 

    events : { 
     "click" : "onClick" 
    }, 

    className: 'item_view', 
    template: _.template($('#image_list_item_view_template').html()), 

    render: function(){ 
     this.$el.html(this.template(this.model.toJSON())); 

     if(this.model.selected){ 
      this.$el.addClass('selected'); 
     }else{ 
      this.$el.removeClass('selected'); 
     } 
    }, 

    remove: function(){ 
     this.$el.remove(); 
    }, 

    select: function(){ 
     this.render(); 
    }, 

    onClick: function(e){ 
     this.trigger('imageListItemView:click'); 
    } 


}) 

そして、ここではImageListViewです:

// ImageListView 
//-------------------------------------------------------------------------------// 

window.ImageListView = Backbone.View.extend({ 


    className: 'image_list_view', 
    tagName: 'nav', 

    initialize: function(){ 
     this.collection.on('add', this.addOne, this); 
     this.collection.on('reset', this.addAll, this); 
    }, 

    render: function(){ 
     this.addAll(); 
     return this; 
    }, 

    addAll: function(){ 
     this.$el.empty(); 
     this.collection.forEach(this.addOne, this); 
    }, 

    addOne: function(image){ 
     var imageListItemView = new ImageListItemView({model: image}); 
     imageListItemView.on('imageListItemView:click', this.itemViewClick, this) 
     imageListItemView.render(); 
     this.$el.append(imageListItemView.el); 
    }, 

    itemViewClick: function(e){ 
     //Get reference to ImageListItemView that originated event 
     //e is undefined 
     //this.collection.setSelectedImage(this.model); 
    } 

}) 

答えて

0

まあ、私はバックボーンを持つ専門家ではないんだけど、あなたがイベントを交換しようとしていますコンテキスト?

すなわち

imageListItemView.on('imageListItemView:click', this.itemViewClick, imageListItemView); 

私が正しく理解していれば、その後、itemViewClick内部thisImageListItemViewを参照してください。

+0

ありがとうございます。イベントハンドラでイベントを取得する必要がありますか? 'e'は定義されていません。カスタムイベントまたはDOMイベントだけでイベントオブジェクトを取得しますか? – Undistraction

+0

はい、そうすべきです。申し訳ありませんが、私は完全な例を編集します。 – iMoses

+0

問題ありません。私のハンドラに渡されたイベントオブジェクトを取得できません。なぜ取り組むことはできません。 – Undistraction

関連する問題