我遇到了一个我不明白的问题。我正在使用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次。这是堆栈跟踪:
对此有何想法?
答案 0 :(得分: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
已实例化。