backbone.js - events, knowing what was clicked

JavascriptJquerybackbone.jsunderscore.js

Javascript Problem Overview


In one of my backbone.js view classes, I have something like:

...

events: {
  'click ul#perpage span' : 'perpage'
},

perpage: function() {
  // Access the text of the span that was clicked here
  // Something like: alert($(element).text())
},

...

because my per page markup might have something like:

<ul id="perpage">
  <li><span>5</span></li>
  <li><span>10</span></li>
</ul>

So how exactly can I find information about the element that caused the event? Or in this instance, that was clicked?

Javascript Solutions


Solution 1 - Javascript

Normally on an event bind, you would just use $(this), but I'm fairly sure Backbone views are set up so that this always refer to the view, so try this:

perpage: function(ev) {
   alert($(ev.target).text());
}

REALLY LATE EDIT: You probably want to use $(ev.currentTarget). See dicussion on pawlik's answer below

Solution 2 - Javascript

ev.target can be misleading, you should use ev.currentTarget as described on http://www.quirksmode.org/js/events_order.html

Solution 3 - Javascript

You can get any attribute you want. ev works as this:

perpage: function(ev) {
        console.log($(ev.target).attr('name'));
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatthewView Question on Stackoverflow
Solution 1 - JavascriptJamie WongView Answer on Stackoverflow
Solution 2 - JavascriptpawlikView Answer on Stackoverflow
Solution 3 - JavascriptNvanView Answer on Stackoverflow