简体   繁体   English

Knockout Js计算出不在模型中工作

[英]Knockout Js computed not working in a model

I am trying to modify the following knockout js model binding to fit my requirement: http://jsfiddle.net/zrBuL/291/ . 我试图修改以下knockout js模型绑定以符合我的要求: http//jsfiddle.net/zrBuL/291/ The modification is as follows: 修改如下:

HTML: HTML:

<label>Male
   <input type="radio" name="IsMale" value="a" data-bind="checked:IsMale"/>
</label> 
<label>Female
   <input type="radio" name="IsMale" value="b" data-bind="checked:IsMale"/>
</label>
<div data-bind="text: ABC()"/>

Javascript: 使用Javascript:

var vm = {
    IsMale: ko.observable(false),
    ABC:ko.purelyComputed({
    read: function(){
            return this.IsMale();
        }
    },this)  
};
ko.applyBindings(vm);

For framework, I would favor knockout.js 3.0.0. 对于框架,我赞成knockout.js 3.0.0。

The problem is it is not displaying anything for the div above where div's text property is bound to ABC(). 问题是它没有为div的文本属性绑定到ABC()上面的div显示任何内容。

Hint: If I replace following line in read function: 提示:如果我在读取功能中替换以下行:

return this.IsMale();

with the following line: 使用以下行:

return "Hi";

then it works like a charm. 然后它就像一个魅力。

Is there anything I am missing in calling the property IsMale? 在调用IsMale属性时我有什么遗漏的吗?

I think the problem lies with two things: 我认为问题在于两件事:

  1. There is no purelyComputed , it is pureComputed 没有purelyComputed ,它是pureComputed

  2. Also pureComputed as introduced within Knockout 3.2.0, so you will need to upgrade to that version in order to use it. 也是在Knockout 3.2.0中引入的pureComputed ,因此您需要升级到该版本才能使用它。

Pure computed observables 纯计算的可观察量

After changing purelyComputed to pureComputed and upgrading to at least Knockout 3.2.0 you get to another problem. purelyComputed更改为pureComputed并升级到至少Knockout 3.2.0后,您会遇到另一个问题。 this in an object definition is the global window object. this在一个对象定义为全局window对象。

So to get a reference to vm instead of window you need to switch to a function constructor for it: 因此,要获得对vm而不是window的引用,您需要切换到它的function构造function

function MyVM() {
    this.IsMale = ko.observable(false);
    this.ABC = ko.pureComputed({
    read: function(){
            return this.IsMale();
        }
    },this);
};
ko.applyBindings(new MyVM());

Then it will work . 然后它会工作

An alternative way of defining this would be: 另一种定义方法是:

var vm = {
    IsMale: ko.observable(false)
};

vm.ABC = ko.pureComputed({
    read: function(){
        return this.IsMale();
    }
}, vm);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM