Can an event listener listen two elements? Can you give the handler more parameters?
I am experimenting with goog.events.listen(src, type, listener, opt_capt, opt_handler)
.
Sometimes I have more than one source but always the same event-type and function 开发者_StackOverflow社区that should be called when this event happens (listener).
Should I simply type this once for every source or is there a better way to do it?
As I like to handle this within the object I am creating the listener, I set opt_handler = this
. I think that in my application it can't happen that two events which have listeners are called at the same moment, so I let opt_capt = false
.
In my JavaScript-file looks like:
var htmlElement = goog.dom.getElement(el[0]);
goog.events.listen(htmlElement, goog.events.EventType.CLICK, this.myFunction, false, this);
Now myFunction
gets only the event as an argument. But I would like to know which htmlElement was clicked. How do I get this information?
The argument myFunction
takes will be of type goog.events.Event
. Its target
property contains the actual event target, while currentTarget
contains the object to which the listener was attached.
you should always be able to use the event via the variable e
and get it's target, which will be the element you clicked.
But do not put this.myFunction(e) in goog.events.listen. goog.event.myFunction is just fine and you did it right from the beginning. If you later on, want to pass additional parameters to myFunction (and maybe do some currying), look at the goog.bind
example and also check out goog.partial
Greetings,
Jan
goog.events.listen(
htmlElement,
goog.events.EventType.CLICK,
this.myFunction,
false,
this
);
//alternative
goog.events.listen(
htmlElement,
goog.events.EventType.CLICK,
goog.bind(myFunction, this)
);
myfunction = function(e) {
//maybe this
window.console.log(e.target)
//or this
var event = e.getBrowserEvent()
window.console.log(event.target)
}
精彩评论