Chaplin.js’s container, containerMethod, and listSelector options

Category : Code · No Comments · by Jan 15th, 2014

I’ve been dabbling with Chaplin.js recently, a javascript MVC framework built upon Backbone.js. I’ve used Backbone.js in the past, and found it lacking convention on how to structure your app. Chaplin.js adds sensible structure and convenient ways to avoid common pitfalls in Backbone.js, like memory leaks. This post also highlights some Chaplin.js/Backbone.js code to give you an small sample of how models, collections, views, collectionviews, templates interact.

I recently had a frustrating bug which I solved by tracing through chaplin.js for hours. Granted, the solution was in the docs all along, but sequentially reading every documented method is a tiring and often rushed process. I probably should have asked StackOverflow, found an IRC channel, or posted an issue on github, but alas. So if you’re coming from Google, hopefully this post saves you some time.

So here was the problem: I wanted to add a collection’s child view into a certain DOM element from the template of the CollectionView. The child view had autoAttach and autoRender set to true. I thought the appropriate options to use were container and containerMethod, but child views just weren’t be added in the right place. After some tracing, I realized I needed to look at the insertView method, which led to the listSelector option, which is clearly what I needed.

Wrong way (uses the container option in a child view):

Correct way (uses the listSelector option in the collection view):

tl;dr use listSelector to define the DOM element where child Views are inserted in a CollectionView, not the container option