0

I will highly appreciate any help. I can't write properly read & write for computed property in 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()
}
4

1 回答 1

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

高威

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

坏的

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

令人困惑 (=>)

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: @
}
于 2013-01-03T19:14:57.937 回答