Question 1
Which of the following 4 methods remove an event listener on Android?
var id = view.addEventListener('click', onClick);
view.removeEventListener('click', onClick);
view.removeEventListener('click', id);
view.removeListener('click', onClick);
view.removeAllListeners('click');
The correct answer: all of them!
Question 2
Which of the following 4 methods then add an event listener on Android?
view.addEventListener('click', onClick);
view.addListener('click', onClick);
view.on('click', onClick);
view.once('click', onClick);
Of course the correct answer again: all.
Once
And yes, once()
will automatically remove the event listener on its first call, just like you can do yourself with:
view.addEventListener('click', function onClick() {
view.removeEventListener('click', onClick);
// do stuff once
});
Getting active listeners
And last but not least, did you know on Android you can also get an array of active listeners to a certain event on a view?
var listeners = view.listeners('click');
var firstListenerMethod = listeners[0].listener;
Why is this useful?
Well, not if you’re doing a cross-platform app, which of course is what you use Titanium for. I just love stumbling on this kind of stuff while browsing Titanium’s source code.
What actually might be useful to know is that on Android events on proxy objects don’t actually cross the native bridge (if they don’t need to), making just as fast as using a Backbone dispatcher like I suggested earlier.
Comments
Brian McBride
This is great. Although I wish that all these worked cross-platform. The more Appcelerator bridges the differences in the platforms on this level, the more useful the platform is.
Thanks for the info! Love your blog.
Fokke Zandbergen Post author
Please watch this ticket: https://jira.appcelerator.org/browse/TC-4986
Manuel Conde
Hi Fokke. As always your post is very interesting.
I saw your JIRA ticket, but I don’t like it very much the aliases policies. Why you want alias? Why we need to have two or three methods to call the same thing? Noobs, like me one year ago, are lost when they see different code from different people calling different methods to do the same.
I prefer to have a unique method to do a unique thing (addEventListener, addListener, on). Different case is the “once” method, that does different things.