I had the following setup now in three different projects, so I thought maybe it's worth asking here. There's a chance I'm not the only person wondering about this.
So there it comes:
- I have a list of objects
- The list items have a special function like draggable or onClick-Events
My question: How do I build this scenario with Backbone?
I guess I create a model and a view for my list objects. I use a collection for keeping together my objects.
Now I wonder: Do I instantiate the object view in the model constructor and instantiate the models in the collection constructor? Or is there a better way to achieve what I want?
Neither; use a mediator to instantiate the views and inject them with their model/collection.
Marionette.js has a nice implementation for this sort of mediating object, called
Controller
- I suggest you check it out.Further more, you don't have to explicitly instantiate the collection models - just declare their type in the collection's prototype, e.g.:
Taking our mediator/controller approach further, this is how it could be done (with Marionette.js):
This, of course, is just a skeleton code, meant to roughly demonstrate the MVC approach, but it's a good starting point.