Knockout.js 打字稿—;比较可观察的基因敲除<;数量>;有数字
我试图做一个简单的操作,但我遇到了一个特殊的问题。我需要禁用一个按钮,除非某个值高于0。基本上,我的代码是这样的:Knockout.js 打字稿—;比较可观察的基因敲除<;数量>;有数字,knockout.js,visual-studio-2013,typescript,Knockout.js,Visual Studio 2013,Typescript,我试图做一个简单的操作,但我遇到了一个特殊的问题。我需要禁用一个按钮,除非某个值高于0。基本上,我的代码是这样的: currentIndex: KnockoutObservable<number> = ko.observable<number>(); canActivate: KnockoutComputed<boolean>; this.canActivate = ko.computed<boolean>(function ()) {
currentIndex: KnockoutObservable<number> = ko.observable<number>();
canActivate: KnockoutComputed<boolean>;
this.canActivate = ko.computed<boolean>(function ()) {
if (this.currentIndex > 0) {
return true;
}
else {return false;}
});
this.canActivate = ko.computed<boolean>(() => {
return this.currentIndex() > 0;
});
currentIndex:KnockoutObservable=ko.observable();
canActivate:KnockoutComputed;
this.canActivate=ko.computed(函数()){
如果(this.currentIndex>0){
返回true;
}
else{return false;}
});
在这种形式下,它总是返回false。如果我将>替换为!=,它总是返回真的。我有一个显示currentIndex的功能,当我点击不同的项目时,它会改变我的预期。然而,我无法将它与一个数字进行比较。有什么想法吗?谢谢 在Knockout中,您需要评估可观察对象以获得其值,这是因为可观察对象是函数。在这种情况下,要获取currentIndex的值,您需要: 而不是:
this.currentIndex
你会做:
this.currentIndex()
下面是一个完整的工作示例:
/// <reference path="scripts/typings/knockout/knockout.d.ts" />
class Example {
currentIndex: KnockoutObservable<number> = ko.observable<number>();
canActivate: KnockoutComputed<boolean> = ko.computed<boolean>(() => {
if (this.currentIndex() > 0) {
return true;
} else {
return false;
}
});
};
//
课例{
currentIndex:KnockoutObservable=ko.observable();
canActivate:KnockoutComputed=ko.computed(()=>{
如果(此.currentIndex()大于0){
返回true;
}否则{
返回false;
}
});
};
就像上面所说的海报一样,您需要使用fat箭头创建canActivate
,并评估可观察对象。大概是这样的:
currentIndex: KnockoutObservable<number> = ko.observable<number>();
canActivate: KnockoutComputed<boolean>;
this.canActivate = ko.computed<boolean>(function ()) {
if (this.currentIndex > 0) {
return true;
}
else {return false;}
});
this.canActivate = ko.computed<boolean>(() => {
return this.currentIndex() > 0;
});
this.canActivate=ko.computed(()=>{
返回此.currentIndex()>0;
});
Typescript使用胖箭头语法来捕获
此
上下文。如果使用function()
创建它,则上下文将不是您期望的上下文,这就是为什么会出现未定义的函数错误。您是否尝试过console.log(this.currentIndex)
或console.log(this.currentIndex的类型)
?另外(我不熟悉Typescript),我认为this.currentIndex
可能是一个巨大的敲除函数。这是获得其价值的正确方法吗?(例如,在vanilla Knockout中this.currentIndex()
)?我还没有尝试过console.log,但我有一个类似的函数在我的UI中显示它。每次我选择一个项目时,索引号都会发生我所期望的变化。此外,使用此.currentIndex()返回错误“Undefined is not a function.”。在计算return语句之前,当canActivate()
激发时,您应该在控制台中记录this.currentIndex
的值,以便查看此.currentIndex是什么。我想你是想把它定义为一个敲除的可观测对象,它是一个函数而不是一个值。如果它不是一个敲除可观测值,那么使用this.currentIndex()>0
将失败。另外,this.currentIndex>0
应该自动失败,就像Wayne在他的回答中说的那样。你知道为什么我会得到“undefined is not a function”错误吗?你能点击它并发布发生的行吗?我想你也应该使用this.canActivate=ko.computed(()=>{});