简体   繁体   中英

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/ . The modification is as follows:

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:

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.

The problem is it is not displaying anything for the div above where div's text property is bound to ABC().

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?

I think the problem lies with two things:

  1. There is no purelyComputed , it is 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.

Pure computed observables

After changing purelyComputed to pureComputed and upgrading to at least Knockout 3.2.0 you get to another problem. this in an object definition is the global window object.

So to get a reference to vm instead of window you need to switch to a function constructor for it:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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