你能扩展初始化模型吗?

时间:2011-09-12 22:56:49

标签: backbone.js coffeescript

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)

1 个答案:

答案 0 :(得分:2)

没有。让类扩展对象(而不是函数)没有意义。如果您尝试实例化User课程,则会收到错误

TypeError: Cannot read property 'constructor' of undefined

如果要覆盖foo上的Entity方法,则应直接执行此操作,但请注意super语法不起作用。相反,你应该写

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