Before we dive into this topic, lets discuss Backbone.js and why it was created for web developers.
The good news is that there are definitely some wrong ways that you should avoid on your way to finding the right solution for your particular problem.
Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
With Backbone, you represent your data as Models, which can be created, validated, destroyed, and saved to the server. Whenever a UI action causes an attribute of a model to change, the model triggers a “change” event; all the Views that display the model’s state can be notified of the change, so that they are able to respond accordingly, re-rendering themselves with the new information. In a finished Backbone app, you don’t have to write the glue code that looks into the DOM to find an element with a specific id, and update the HTML manually ó when the model changes, the views simply update themselves.
Basic Requirement of start backbone coding require Underscore.js,jQuery.js and Backbone.js.
Now, let’s try to create a simple example of event binding using BackboneJS.
Here is the code snippet of above example.
initialize(): Method which will call when the View object is created.
events: Where DOM events are bound to View methods. Backbone doesn't have a separate controller to handle such bindings; it all happens in a View.
render(): Introduces a button to add a new list item.
addItem(): Custom function called via click event defined in events section.
Here in the initialize method there is _.bindAll method which binds all the defined function to the current view.
Click the event of button is define in the events section which will fire addItem function when click event triggers. So, AddItem function will add item to the list. So that’s how dom event binding to the view methods works in Backbone.js.
Looking to learn more about Backbone.js for your team? Check out our custom group training options today.