[英]Backbone constructor calls itself
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. 我在玩Backbone,我的一个初始化程序被两次调用,一个是故意的(当我实例化对象时),似乎它从构造函数本身被第二次调用。
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. 当我运行此代码时, Outer
显示一次,而Inner
显示2次。 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. 初始化集合时,第一个参数是预填充模型的列表。
class Models extends Backbone.Collection
model: Model
initialize: (@rawModels) ->
# CoffeeScript has the fat arrow that renders this unnecessary.
# But it's something you should use as sparingly as possible.
# Whatever. Not the time to get into that argument.
_.bindAll @
# At this point in time, all the models have been added to the
# collection. Here, you add them again. IF the models have a
# primary key attribute, this will detect that they already
# exist, and not actually add them twice, but this is still
# unnecessary.
_.each @rawModels, @addItem
# assuming this was a typo
addItem: ( place ) -> @add new Model model
models = new Models json
Not directly related to your question, but hopefully helpful. 与您的问题没有直接关系,但希望会有所帮助。
More directly related: don't create a collection of views. 更直接相关:不要创建视图集合。 Collection
s are for storing Model
s. Collection
用来存储Model
。 Backbone.View
is not a type of Backbone.Model
; Backbone.View
不是一个类型的Backbone.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 a Backbone.Model
. 当您调用Backbone.Collection::add
,它将尝试查看您要添加的内容是否是Backbone.Model
。 Since it's not , it assumes you're trying to add a JSON blob that it wants to turn into a Model
. 由于不是 ,因此假定您正在尝试添加要转换为Model
的JSON Blob。 So it tries to do that...using its this.model
class as a guide. 因此,它尝试使用this.model
类作为指导来做到这一点。 But since that's View
, it creates another one and adds that instead (not checking after the fact that it actually produced a Backbone.Model
). 但是既然是View
,它就会创建另一个并添加它(而不是在它实际产生Backbone.Model
之后再检查)。
You can follow the call stack from add to set to _prepareModel , where the second View
is instantiated. 您可以按照从add到set到_prepareModel的调用堆栈进行操作 ,在此实例化第二个View
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.