2011-09-12 35 views
0
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) 

回答

2

號有一個類延伸的對象(而不是函數)沒有意義。如果你試圖實例化User類,你會得到錯誤

TypeError: Cannot read property 'constructor' of undefined 

如果你想覆蓋foo方法上Entity,你應該這樣做直接,但請注意,super語法將無法正常工作。相反,你應該寫

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

我的編輯是否有意義? – fancy

+0

是的。你的代碼將起作用,除了你會失去任何綁定到'entity'的事件監聽器,新的'entity'不會屬於任何舊''實體'屬於的集合等。一般來說,你會更好的辦法是動態地附加'foo'函數(如我的答案),或者拋棄多態,轉而採用一種全尺寸的'foo'函數來執行類似'if @type is 1 ...' –

+0

我最近的編輯是否有意義? – fancy