Knockout.js与CoffeeScript,继承,对象实例化

时间:2014-06-12 03:52:51

标签: javascript inheritance knockout.js coffeescript

我在调用Test方法时遇到问题。我希望能够调用子Test方法。我不确定我的遗产是否正确。

WORKS

<a href="javascript:void(0);" data-bind="click: Save">Save</a>

不起作用

<a href="javascript:void(0);" data-bind="click: Test">Test</a> 

另外..不起作用

<a href="javascript:void(0);" 
   data-bind="click: ContributionMappings().DebitAccount().Test">Test</a> 

代码:

class DebitAccount
    constructor: () ->
        @SortOrder = ko.observable()
        @Entity = ko.observable()
        @Field = ko.observable()
        @FieldValue = ko.observable()
        @Constant = ko.observable()
        @Default = ko.observable()
        @Entity2 = ko.observable()
        @Field2 = ko.observable()

    Test: () =>
        alert 'test'

class ContributionMappings
    constructor: () ->
        @DebitAccount = ko.observable()

class Mapping
    constructor: () ->
        @ContributionMappings = ko.observable()

    Save: () =>
        alert 'save'

$ () =>
    @viewModel = new Mapping    

    # connect items with observableArrays
    ko.applyBindings(viewModel)    

jsbin demo

1 个答案:

答案 0 :(得分:1)

有关如何为类实现原型继承的详细信息,请查看CoffeeScript页面的Classes, Inheritance, and Super部分。简而言之,您的代码应该类似于:

class DebitAccount
    constructor: () ->
        @SortOrder = ko.observable()
        # etc.

    Test: () =>
        alert 'test'

class ContributionMappings extends DebitAccount
    constructor: () ->
        super

class Mapping extends ContributionMappings
    constructor: () ->
        super

    Save: () =>
        alert 'save'

但是我不确定你想要实现的目标 - 你的班级名称并没有暗示我与你的继承关系。如果您试图编写类而不是扩展它们,那么您的代码看起来与您所拥有的类似:

class DebitAccount
    constructor: () ->
        @SortOrder = ko.observable()
        #etc.

    Test: () =>
        alert 'test'

class ContributionMappings
    constructor: () ->
        @DebitAccount = ko.observable(new DebitAccount())

class Mapping
    constructor: () ->
        @ContributionMappings = ko.observable(new ContributionMappings())

    Save: () =>
        alert 'save'

但是当您使用Knockout绑定引用内部属性时,您需要遍历中间对象:

<a href="javascript:void(0);" data-bind="click: ContributionMappings.DebitAccount.Test">Test</a>