5

I'm trying to get the data attribute of a div when clicked in Backbone events(View).

I'm able to achieve this if I click on the div listItem but if I was to click on the child element span it will fail because $(e.target) will be the span.

So how do I get the data attribute of the parent element, even if the child element is clicked?

<div class="listItem" data-showInfo="true">
    <span class="arrow"></span>
</div>

events:{
  "click .listItem": function(e) {

    var $listItem= $(e.target);

    console.log($listItem.data('showInfo'));
  }
}
manraj82
  • 5,929
  • 24
  • 56
  • 83

3 Answers3

10

Use event.currentTarget instead of event.target, it will be set to the .listItem selector independently of the DOM node you click

var V = Backbone.View.extend({
    events: {
        'click .listItem' : function(e) {
            console.log($(e.currentTarget).data('showinfo'));
        }
    }
});

And a demo http://jsfiddle.net/nikoshr/QyP3Z/

nikoshr
  • 32,926
  • 33
  • 91
  • 105
6

You can do it like this:

$('.arrow').click(function(){
alert($(this).parent().attr('data-showInfo'));
});

Your example is in this JSFiddle

Debopam Mitra
  • 1,842
  • 4
  • 27
  • 51
2
events:{    
    "click .arrow": function(){
        console.log($(this).parent('.listItem').attr('data-showInfo'));
    };
}  
Venkat Kotra
  • 10,413
  • 3
  • 49
  • 53