Updating Views with Events, Models and Rivets

In this Backbone.js recipe, we’re going to allow updating a view via events triggered from any sub-view. The view won’t need a refresh(), because it will be bound to model change events using Rivets.

tl;dr; live demo and gist

The header view below will initialize and bind a model to our view’s element using Rivets. Updating the model will cause Rivets to refresh our view based on data- attributes in the HTML, and the updating of the model is triggered by an ‘updateHeader’ event bound to the BODY element. This means that any sub-view can trigger updates to our header.

The application view will setup event handlers on buttons so we can toggle between status states. These button click events trigger an ‘updateHeader’ event sending new data for our model, which will bubble-up to the handler defined in the header view.

The HTML contains the Rivets data- directives to hide and show alternative status text.

See the live demo or browse the gist

Leave a Reply