Javascript Knockout.js - 如何在计算出的 observable 中获取 observable 属性的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11045029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:13:08  来源:igfitidea点击:

Knockout.js - how do I get the value of an observable property inside a computed observable?

javascriptknockout.js

提问by Arbejdsgl?de

I have following Knockout.js object:

我有以下 Knockout.js 对象:

var viewModel = {
    description : ko.observable(""),
    Name : ko.observable(""),
    productid : ko.observable(""),
    productmodel : ko.observable(""),
    productnumber : ko.observable(""),
    text_relevance : ko.observable(""),
    mydunamicfield : ko.computed(function() {
        return "bq=(and " +
            ((this.description == "") ? "" : ("description:" + this.description + " ")) +
            ")";
    } , this)
};

But the mydunamicfieldproperty isn't producing the the correct concatenated result. If I try to reference this.description()inside another function, I see the following error message when the page is loading:

但是该mydunamicfield属性没有产生正确的连接结果。如果我尝试this.description()在另一个函数内部进行引用,则在加载页面时会看到以下错误消息:

Property 'description' of object [object Window] is not a function

What is the problem in this case?

在这种情况下有什么问题?

回答by Mark Robinson

Firstly, you must reference this.descriptionas this.description()if you want to get its value.

首先,您必须this.descriptionthis.description()要获取其值一样进行引用。

Secondly, try putting your computedfield outside your viewModel(as 'this'which is the viewModelitself isn't defined at the point you create the computedobservable.

其次,可以尝试在你的computed领域你之外viewModel(因为'this'这是viewModel本身不是在点定义创建computed观测。

See http://jsfiddle.net/rAEqK/2/for a working example.

有关工作示例,请参阅http://jsfiddle.net/rAEqK/2/