gpt4 book ai didi

javascript - 如何在 View 模型不是函数的情况下创建 KnockoutJS 计算可观察对象?

转载 作者:行者123 更新时间:2023-11-30 08:35:24 25 4
gpt4 key购买 nike

我不知道如何从匿名 computed function 内部访问 View 模型中的其他项目.如何获取 this/self/sys 或对 View 模型的引用?

http://jsfiddle.net/2z66yxkz/

var sys = {

viewModel: {

first: ko.observable('John'),
last: ko.observable('Doe'),
name: ko.computed(function() {

// this.first?
// this.viewModel.first()?
// sys.viewModel.first?

console.log(this);
return 'first + last';
}),
}
};


$(function() {

ko.applyBindings(sys.viewModel, $('#cont')[0]);
});

最佳答案

由于对象的布局方式以及 knockout 如何运行您提供给计算的函数,您目前无法轻松访问这些属性。您可以改为稍微更改布局以使用 IIFE 来创建对象实例:

var sys = new (function(){
this.viewModel = new (function() {
this.first = ko.observable('John');
this.last = ko.observable('Doe');
this.name = ko.computed(function() {
return this.first() + ' ' + this.last();
}, this); //Note "this" - see below
})();
})();

Knockout 计算采用第二个参数来指定运行时 this 的值。通过以这种方式重写的 View 模型,我们可以将当前对象作为 this 参数传递给计算回调使用。

这是 an update to your fiddle .

关于javascript - 如何在 View 模型不是函数的情况下创建 KnockoutJS 计算可观察对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31810767/

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