Backbone构造函数调用自身

时间:2013-12-02 12:11:53

标签: javascript backbone.js coffeescript backbone-views backbone-collections

我遇到了一个我不明白的问题。我正在使用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次。这是堆栈跟踪:

enter image description here

对此有何想法?

1 个答案:

答案 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用于存储ModelBackbone.View不是Backbone.Model的类型;他们是分开的。它没有多大意义 - 您可以创建一个视图数组 - 并且许多操作无法在该视图集合上正常工作。

这是发生了什么。

当您致电Backbone.Collection::add时,它会尝试查看您添加的内容是否为Backbone.Model。由于不是,它假设您正在尝试添加要转换为Model的JSON blob。所以它尝试这样做......使用this.model类作为指导。但是,因为那是View,它会创建另一个并改为添加(不会在实际生成Backbone.Model之后进行检查)。

您可以按照添加的调用堆栈设置为_prepareModel,其中第二个View已实例化。

相关问题