淘汰模型到coffeescript类语法转换

时间:2012-10-25 16:25:46

标签: knockout.js coffeescript knockout-2.0

所以我正在尝试将淘汰模型转换为coffeescript类,到目前为止还没有使用过咖啡,如果通过coffeescript(以及我的班级)调用property.subscribe淘汰函数的语法有问题。现在的代码看起来像是(严重愚蠢到达了点)

var Autocomplete = function(){
  var self = this;
  self.displayResults = ko.observable(false);
  self.results = ko.observableArray([]);
  self.hasResults = ko.observable(false);

    self.hasResults.subscribe(function(newValue){
        if(newValue == true) {
            self.displayResults(true);
        } else {
            self.displayResults(false);
        }
    });

}

但基本上我想做的是:

class ClientAutoComplete
  constructor: ->
    @hasResults = ko.observable(false)  
    @results = ko.observableArray([])  
    @displayResults = ko.observable(false)

  hasResults.subscribe: (newValue) ->
    @displayResults(newValue)

我无法弄清楚如何正确调用property.subscribe方法,我尝试了几种不同的语法,但无济于事。任何人都可以对此有所了解吗?非常感谢。

1 个答案:

答案 0 :(得分:2)

相当于你的JavaScript:

class ClientAutoComplete
  constructor: ->
    @displayResults = ko.observable(false)
    @results = ko.observableArray([])  
    @hasResults = ko.observable(false)  

    @hasResults.subscribe (newValue) =>
      @displayResults(newValue)

您必须将@添加到hasResults以使其成为实例变量引用,并且您需要缩进@hasResults.subscribe另一个级别以将其放入构造函数中。你也不希望@hasResults.subscribe上有冒号,这是函数调用,而不是属性定义;你也可以这样写:

@hasResults.subscribe( (newValue) =>
  @displayResults(newValue)
)

如果您需要提醒它是一个函数调用。如果匿名函数大于单行函数,我倾向于包括括号。

fat-arrow (=>)将匿名函数绑定到当前this

  

胖箭头=>可以用来定义一个函数,并将其绑定到当前值this,就在现场。当使用基于回调的库(如Prototype或jQuery)创建迭代器函数以传递给each或事件处理函数与bind一起使用时,这很有用。使用胖箭头创建的函数可以访问定义它们的this的属性。

胖箭是var self = this; JavaScript惯用语的常用替代品。