ChatGPT解决这个技术问题 Extra ChatGPT

backbone.js - events, knowing what was clicked

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?


J
Jamie Wong

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


If I'm correct, this works with jquery events (the one's the poster asked about). Note however that events triggered through backbone's trigger() function does not carry this information (it instead gives you the arguments used when calling trigger())
@roufamatic — because those are really standard JavaScript events, so it's out of the scope of BackboneJS. Those docs does not include reference of HTML nor CSS too.
"Backbone views are set up so that this always refer to the view" — this applies only to events defined with delegateEvents([events]) or with events object passed to Backbone.View.extend (which uses the former method behind the scenes). This does not apply to events bound in initializer, render method etc.
p
pawlik

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


Good to know about - but it looks like it's not implemented in IE - or does jQuery do normalization to fix this?
Looks like jQuery normalizes both ev.target as the dom element initializing the event and ev.currentTarget as the current DOM element within the event bubbling phase api.jquery.com/category/events/event-object
I was just playing with this, and to clarify, you probably want ev.currentTarget. It is normalized and safe for use in all jQuery supported browsers.
Yes, you want to use currentTarget instead of target. For example, if you bind a link that contain child objects "text" target can point to and not .
This should be the answer. event.target only get you what is clicked.
N
Nvan

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

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