如何在coffeescript中使用读取和写入敲除计算属性

时间:2013-01-03 19:09:16

标签: coffeescript knockout-2.0

我将非常感谢任何帮助。我写得不好读&在CoffeeScript中为计算属性写。

@allChecked = ko.computed => {
  read: ()->
    console.log 'allChecked->read()'
    firstUnchecked = ko.utils.arrayFirst @contactGroups(), (item) ->
                      item.IsSelected() == false
    firstUnchecked == null
  write: (value)->
    console.log 'allChecked->write()', value
    g.IsSelected(value) for g in @contactGroups()
}

1 个答案:

答案 0 :(得分:2)

我只是在这里盲目猜测,因为我无法访问您的其余代码。

第一

ko.computed接受读取函数,或者接受具有readwrite函数的对象。它不会使用返回具有read / write属性的对象的函数。

实施例

正确ko.computed -> 5

正确ko.computed { read: -> 5 }

错误ko.computed -> { read: -> 5 }

第二

@严格意味着this,这意味着取决于函数的调用方式(f()f.apply(_)new F()),它可能具有不同的值。如果您要特定this的值,则可以在创建owner时指定ko.computed

computed = ko.computed {
  read: -> @getValue()
  owner: @
}

实施例

不可

class Thing
  constructor: (@number) ->
    self = @
    ko.computed -> self.number

<强> KO-方式

class Thing
  constructor: (@number) ->
    ko.computed {
      read: -> @number
      owner: @
    }

<强>坏

class Thing
  constructor: (@number) ->
    ko.computed -> @number # means this.number

令人困惑 (=&gt;)

class Thing
  constructor: (@number) ->
    ko.computed => @number

最后

全部放在一起。

示例

@allChecked = ko.computed {
  read: ->
    console.log 'allChecked->read()'
    firstUnchecked = ko.utils.arrayFirst @contactGroups(), (item) ->
                      item.IsSelected() == false
    firstUnchecked == null

  write: (value) ->
    console.log 'allChecked->write()', value
    group.IsSelected(value) for group in @contactGroups()

  owner: @
}