【问题标题】:Can you extend initialized models?你能扩展初始化模型吗?
【发布时间】:2011-09-13 07:57:06
【问题描述】:
class TheModel extends Backbone.Model
    foo: 
        #bar

Entity = new TheModel(#pass in attributes)

然后我可以扩展实体并维护模型属性/状态吗?

class User extends Entity
    foo: 
        super
        #more

编辑:

class Entity extends Backbone.Model
    initialize: (options) ->
        @_events options

        _events: (options) -> 
            entity.bind 'foo'

class Entity1 extends Entity
    _events: (options) ->  
        super options
        entity.bind 'bar'

class Entity2 extends Entity
    _events: (options) -> 
        super options
        entity.bind 'baz'

#a new entity arrives, we don't know if he is type one or two yet so he is...
entity = new Entity

#now we find out he is type 2
entity = new Entity2(entity.attributes)

【问题讨论】:

    标签: backbone.js coffeescript


    【解决方案1】:

    没有。让一个类扩展一个对象(而不是一个函数)是没有意义的。如果你试图实例化你的 User 类,你会得到错误

    TypeError: Cannot read property 'constructor' of undefined
    

    如果您想覆盖Entity 上的foo 方法,您应该直接这样做,但请注意super 语法不起作用。相反,你应该写

    entity.foo = ->
      @constructor::foo.apply arguments  # equivalent to super
      # ...
    

    【讨论】:

    • 是的。您的代码将起作用,除了您将丢失绑定到 entity 的任何事件侦听器,新的 entity 将不属于旧的 entity 所属的任何集合,等等。通常,您会最好动态附加 foo 函数(如我的回答),或者放弃多态性以支持一刀切的 foo 函数,该函数类似于 if @type is 1...
    猜你喜欢
    • 1970-01-01
    • 2013-04-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多