What Are Backbone Events for Model/ Views?

What are Events?

In Backbone, events are modules that can be put into any object that gives the object the ability to bind or trigger events. Events are named, never truly have to be declared before they are bound to an object and they may rake in arguments.

How do Events relate to Models/Views?

In Backbone, the focus of the passing of data is through model, views, and collections. This article will focus on the first two. Models are the object that can be bound to events and is just code. The view is the user interface or UI for short. The view renders the model into a visualized form. Due to the separation of concerns being a model for backbone, the model should be unaware of the view but the view should always listen to changes made to the model.

What are some Backbone Events?

Some basic backbone events are on, trigger, and the listenTo event. Each event relies on changing different aspects of the UI or even the model itself. Let’s look at three individual events.

  • On — object.on(event, callback, [context])

On works by binding a call back function to a model that is executed when the event is run. The convention for this is that if multiple events are being used, a programmer should use colons to namespace them.

  • Trigger — object.trigger(event, [*args])

Trigger does exactly what it says, it triggers a callback for a named event and passes its arguments into callbacks of the event.

  • ListenTo — object.listenTo(other, event, callback)
Example of listenTo()

ListenTo is one of the most useful backbone events and works by telling the model to listen for specific events on other models. The listenTo event also keeps track of the events which makes it a more useful tool in instances with multiple events rather than an event like on. Another fact about listenTo is that the callback will always be called with the object as the context for it.

Conclusion

In conclusion, backbone events are made to help change the model and aid in the visualization of the view.