I've encountered a problem I don't understand. I'm playing with Backbone and one of my initializer is called twice, one on purpose (when I instantiate my object) and it seems like it's called a second time from the constructor itself.
Here is my code :
class Views extends Backbone.Collection
model: View
initialize: ->
_.bindAll @
class View extends Backbone.View
initialize: ->
_.bindAll @
console.error 'Inner'
views = new Views
console.log 'Outer'
views.add new View
When I run this code, Outer
is displayed once while Inner
is displayed 2 times. Here is the stack trace :
Any idea about this ?
When you initialize a collection, the first argument is the list of models to pre-populate it with.
Not directly related to your question, but hopefully helpful.
More directly related: don't create a collection of views.
Collection
s are for storingModel
s.Backbone.View
is not a type ofBackbone.Model
; they're separate. It doesn't really make sense -- you can just create an array of views -- and a lot of operations won't work right on that view collection.Which is what's happening here.
When you call
Backbone.Collection::add
, it tries to see if what you're adding is aBackbone.Model
. Since it's not, it assumes you're trying to add a JSON blob that it wants to turn into aModel
. So it tries to do that...using itsthis.model
class as a guide. But since that'sView
, it creates another one and adds that instead (not checking after the fact that it actually produced aBackbone.Model
).You can follow the call stack from add to set to _prepareModel, where the second
View
is instantiated.