Re-Learning Backbone.js – View Events

It is common for Backbone.js views to include elements that the user can interact with. For example, the user can enter text in a text box, hover over a div, or click a button. These types of interaction can trigger events. If a Backbone.js view is bound to these events, then the view can react to these events. Reaction to these events could be validating data, displaying a message box, or saving or updating data in the model.

While we learning about Backbone.js view events, we will keep it very simple. In the following example we will not have templates or models, we will be working with a very simple view. In this example we will bind an input textbox key-up event to a view’s function. Whenever the user presses a key, an event should be triggered and a function should be called to log the value of the textbox to the browser console.


Close Bitnami banner

The HTML is very simple in this example. We have a “div” with id of “container-movieInput”. This “div” element will be referenced by the Backbone.js view “el” property. This “div” element will include an input element with the id “txtMovieTitle”. Whenever a key-up event occurs on the input element, an event should be fired. The reason we reference this element, is so that we can monitor its child element for changes.

The view event hash provides a simple way to bind events on a DOM element to a function. In this example, whenever a key-up (keyup) event occurs on the element with the id of “#txtMovieTitle”, then call the function titleChange”. The event hash can include multiple bindings. The event hash is loaded when the view constructor is called.

In this example, the “titleChange” method will be executed when the key-up event is triggered for input element. There is an argument passed to the function that we called “event”. In the browser console you can see event logged. The event value that is passed-in will include the target and type as properties. “target” is the item that triggered the event and “type” is the action that occurred. In our example, the event “keyup” on the “input” element triggered the event.

In the example you can see that we are using jQuery “$(” to reference the target element that triggered the event and logging the value of the input element.

2 thoughts on “Re-Learning Backbone.js – View Events”

Leave a Reply

Your email address will not be published. Required fields are marked *