我已经看过几篇关于如何使用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
答案 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'
)