Backbone.js View DOM Events – Complete List
I have been working on a few different Backbone projects recently, and recently ran into a problem of binding a DOM event to a couple input radio buttons I was using as a toggle switch. For some reason, the standard click event was not binding to the correct elements when it came to these radio buttons.
After a few searches on Google and StackOverflow, I could not successfully find a complete list of all the DOM events that are allowed to be passed into the “events” hash inside a Backbone.js view. The Backbone.js documentation tells you how to use the delegateEvents method, but it does not give a complete list of all events.
It turns out that all jQuery events are valid events that can be used inside the “events” hash in a view. This makes total sense, but I had not seen this listed anywhere, until I found a short post on StackOverflow.
Here is the complete list of all jQuery events you can listen to in a Backbone.js view:
http://api.jquery.com/category/events/
More information on the Backbone View delegateEvents method and events hash:
http://backbonejs.org/#View-delegateEvents
I ended up using the “change” event combined with an if / else if statement to get the functionality I was looking for with this toggle switch. Here is a snippet of my toggle switch event listener code:
//Backbone View delegateEvents hash events: { 'change .toggle-switch .switch': function(e) { if ($('#live-game').is(':checked')){ console.log('live game'); } else if ($('#completed-game').is(':checked')) { console.log('completed game'); } } }
I used a great CSS library called css-toggle-switch for these toggle switches. It comes with a few well styled themes, and it works great with the Backbone code above. Check it out if you’re looking for a mobile-style toggle switch that is pure CSS.
I am currently in the final phases of my latest personal project here at Hack Reactor. It is a cloud-based poker session tracking app, with a mobile first design. I am using Backbone.js, Node.js, Express, Parse.com, and D3 in my stack. Look for a blog post soon with a link to the live deployment of this app!
1 Comment
[...] http://kevinhamiltonsmith.com/backbone-js-view-dom-events-complete-list/ [...]