1

所以我试图将淘汰模型转换为咖啡脚本类,直到现在才使用咖啡,在如何通过咖啡脚本(和我的班级)调用 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 方法,我尝试了几种不同的语法但无济于事。任何人都可以对此有所了解吗?非常感谢提前。

4

1 回答 1

2

相当于您的 JavaScript 将是这样的:

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

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

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

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

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

箭头 ( =>)将匿名函数绑定到当前函数this

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

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

于 2012-10-25T17:23:36.323 回答