【问题标题】:Backbone constructor calls itselfBackbone 构造函数调用自身
【发布时间】:2013-12-02 22:30:32
【问题描述】:
我遇到了一个我不明白的问题。我在玩 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 显示两次。这是堆栈跟踪:
对此有什么想法吗?
【问题讨论】:
标签:
javascript
backbone.js
coffeescript
backbone-views
backbone.js-collections
【解决方案1】:
当你初始化一个集合时,第一个参数是模型列表来预填充它。
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
与您的问题没有直接关系,但希望对您有所帮助。
更直接相关:不要创建视图集合。 Collections 用于存储Models。 Backbone.View 不是 Backbone.Model 的类型;他们是分开的。这没有任何意义——你可以只创建一个视图数组——而且很多操作都不能在那个视图集合上正常工作。
这里发生了什么。
当您调用Backbone.Collection::add 时,它会尝试查看您添加的内容是否为Backbone.Model。由于它不是,它假定您正在尝试添加一个它想要转换为Model 的JSON blob。所以它试图做到这一点......使用它的this.model 类作为指导。但由于那是View,它会创建另一个并添加它(在它实际生成Backbone.Model 的事实之后不检查)。
您可以按照调用堆栈从 add 到 set 到 _prepareModel,其中第二个 View 被实例化。