简体   繁体   中英

How to get knockoutjs visible binding work with expressions containing observable strings?

Lets say there is an observable string stringVal defined in the view model.

data-bind="visible:!stringVal()" or any other expression containing stringVal() doesnt work. The error thrown is that a function stringVal() is expected in the view model.

Similar expression easily works with boolean observables.

Try this http://jsfiddle.net/w00t_/h6dy46s7/1/

HTML:

<h1 data-bind="visible: notstringval">
    <span data-bind="text: stringval()"></span>
    <span>yo</span>
</h1>

JS:

function myViewModel() {
    self = this;
    self.stringval = ko.observable("hello");
    self.notstringval = ko.pureComputed(function () {
        return !self.stringval();
    })
}

ko.applyBindings(myViewModel);

It's probably your version of Knockout. It works with versions 3.0+ but not with 2.x

 function myViewModel() { self = this; self.stringval = ko.observable("hello"); } ko.applyBindings(myViewModel); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script> <h1 data-bind="visible: !stringval()"> <span data-bind="text: stringval()"></span> <span>yo</span> </h1> <input data-bind="value: stringval" /> 

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