淘汰赛订阅语法

时间:2013-11-06 16:13:20

标签: javascript knockout.js

如何在“subscribe”中调用函数而不是内联编写?

例如,如果我有:

function Car(name) {

var self = this;
self.name = name;
self.isRed = ko.observable(isRed);

self.isRed.subscribe(function (value) {console.log(this.name()}, this)

}

一切都按预期工作,输出[this.name]的值。

但是我想替换函数体,比如:

self.isRed.subscribe(function (value) {outputLog(value)}, this)

但是,如果我这样做,则[this.name]的值在outputlog函数中是未定义的。

我是javascript和淘汰赛的新手,所以我怀疑我遗漏了一些关于javascript的基本信息。我假设它与[this]的范围有关,但我无法弄清楚如何使语法正确。

2 个答案:

答案 0 :(得分:2)

试试这个(小提琴:http://jsfiddle.net/hv9Dx/12/):

self.isRed.subscribe(
   function (value) {
     outputLog.call(this, value);
   }
, this)

以下是关于此关键字的精彩文章:http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/

答案 1 :(得分:1)

在你的函数中,'this'现在有不同的上下文。 如果你的outputLog函数是car的属性,你已经在对象中声明了self,你可以改为使用self.name。

相关问题