gpt4 book ai didi

javascript - 在类中初始化自定义 ko.computed

转载 作者:行者123 更新时间:2023-11-30 17:38:55 25 4
gpt4 key购买 nike

我不知道这是否可能,但我想实现这样的目标:

function templateCheck(Properties,ComputedFunction){
var self = this;
self.Prop1 = ko.observable(Properties.Prop1);
self.CustomCaltulation = ko.computed(ComputedFunction);
return {
returningValue: self.CustomCalculation
}
}

// This doesn't work
var test = new templateCheck({Prop1: "something"},function(){ return self.Prop1(); })
// Error: TypeError: Object [object global] has no method 'Prop1'

到目前为止,我没有成功实现这一目标。

最佳答案

不需要“ self ”变量。它实际上让你更难,因为你发现“self”不是在 templateCheck 的上下文之外定义的。诀窍是使用计算变量的“所有者”属性,它设置 this

的“含义”
function templateCheck(Properties, ComputedFunction){
this.Prop1 = ko.observable(Properties.Prop1);
this.CustomCalculation = ko.computed({
read: ComputedFunction,
owner: this
});
return {
returningValue: this.CustomCalculation
};
}

var test = new templateCheck({Prop1: "something"},function(){ return this.Prop1(); })

不过我确实想知道您为什么要尝试这样做。我觉得有点像代码味。也许有更好的方法?

关于javascript - 在类中初始化自定义 ko.computed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21455049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com