我遇到了我不明白的问题。我正在玩Backbone,我的一个初始化器被两次调用,一个是有意的(当我实例化对象时),似乎它被构造函数本身第二次调用。
这是我的代码:
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
当我运行此代码时,
Outer
显示一次,而Inner
显示2次。这是堆栈跟踪:有什么想法吗?
最佳答案
初始化集合时,第一个参数是预填充模型的列表。
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
与您的问题没有直接关系,但希望会有所帮助。
更直接相关:不要创建视图集合。
Collection
用于存储Model
。 Backbone.View
不是Backbone.Model
的类型;他们是分开的。这实际上没有任何意义-您可以创建一个视图数组-并且很多操作都无法在该视图集合上正常进行。这是怎么回事。
调用
Backbone.Collection::add
时,它将尝试查看您要添加的内容是否是Backbone.Model
。由于不是,因此假定您正在尝试添加要转换为Model
的JSON Blob。因此,它尝试使用它的this.model
类作为指南。但是由于是View
,它会创建另一个并添加它(而不是在实际生成Backbone.Model
之后再检查)。您可以遵循从添加到设置为_prepareModel的调用堆栈,在此实例化第二个
View
。关于javascript - Backbone 构造器自称,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20328030/