block by Rich-Harris b8df60d7eacebde205c0

Backbone adaptor

Ractive isn’t an MVC framework, because MVC isn’t the only way to build apps. Rather than dressing up your data with dedicated Model classes, you can use plain old JavaScript objects - POJOs.

That’s handy, but sometimes it’s not enough - maybe you want to use Backbone (for example) Models and Collections in your app, but you still want to use Ractive to render your interface.

In these situations, we use adaptors. Adaptors are small plugins that allow Ractive to communicate seamlessly with third-party model libraries. In the example above, we’re using the Backbone adaptor. We have a variety of model types (Film, Actor and Director) and a collection type (Films).

As Ractive builds up the view, any time it encounters an instance of a Backbone Model, it does two things. Firstly, it wraps the object so that you can do film.title in your template (rather than film.get('title') or film.attributes.title). Secondly, it adds a handler to the model’s change event, so that changes in the model are reflected in the view. This binding works in both directions - changes in the view will also be reflected in the model, where appropriate.

Later, if the model is no longer in use, the event handler will be removed automatically.

This means we have the best of both worlds - we have Ractive’s simplicity, but with the power of Backbone’s helper methods. For example when you roll over the actor or director name in the top left, you see a list of credits constructed using the collection’s pluck method:

<div class='credits-list'>;Credits: {{ credits.pluck( 'title' ).join( ', ' ) }}</div>

This is possible because each Actor and Director instance has a credits property, which is an instance of the Films collection type.

Notice also that within the highlight event handler, we’re using the set event on the Backbone object rather than on Ractive, which is a more object-oriented approach if that’s your bag.

You’ll find more information about adaptors, including how to create your own, on the docs.

BaseView.html

data.json

main.js