为什么Backbone模型在使用CoffeeScript类继承时不能正常工作

时间:2015-02-07 21:37:04

标签: javascript backbone.js coffeescript

我已经看过几篇关于如何使用CoffeeScript扩展Backbone功能的帖子,但我无法让它发挥作用。以下代码:

Backbone = require 'Backbone'

# The backbone way
Base = Backbone.Model.extend (
    initialize: ->
)

Model  = Base.extend (

    initialize: ->
        console.log 'initialize called'
        @on 'change:foo', ->
            console.log 'foo changed (Base)'

    defaults: (
        foo: 'bar'
    )
)

model = new Model()
model.set 'foo', 'baz'
console.log model.get 'foo'



# The coffeescript way with double ineritance
class Base2 extends Backbone.Model
    constructor: ->

class Model2 extends Base2

    constructor: ->
        console.log 'constructor called (Base2)'
        @on 'change:foo', ->
            console.log 'foo changed (Base2)'

    defaults: (
        foo: 'bar'
    )

model2 = new Model2 (foo: 'bar')

model2.set 'foo', 'baz2'
console.log model2.get 'foo'

抛出:

  % coffee index.coffee                                                                                                                                                                            
initialize called
foo changed (Base)
baz
constructor called (Base2)
TypeError: Cannot read property 'foo' of undefined
  at Model2._.extend.set 

你也可以在这里玩http://codepen.io/guyht/pen/LEOdZr?editors=001

1 个答案:

答案 0 :(得分:3)

您的问题是您通过指定自己的constructor来替换Backbone的构造函数。 Backbone需要使用自己的构造函数来设置所有Backbone内部,类似构造函数的代码应该在initialize中,就像使用Backbone的extend函数而不是CoffeeScript的extends关键字一样:

class Base2 extends Backbone.Model
    initialize: ->

class Model2 extends Base2

    initialize: ->
        console.log 'initialize called (Base2)'
        @on 'change:foo', ->
            console.log 'foo changed (Base2)'

    defaults: (
        foo: 'bar'
    )

更新了演示:http://codepen.io/anon/pen/myqxWY