简体   繁体   中英

How to properly use KnockoutJS visible bindings?

I have a quick (hopefully simple) problem with KnockoutJS and the visible binding. I just can't seem to get it working for the code below. All it is supposed to do is display a form while "signedIn" is false and once the form is submitted the form should disappear and it should display "You are signed in as (username)".

<form class="pad-bottom" data-bind="visible: !signedIn, submit: signIn"      onsubmit="signIn()">
    <div class="form-group">
        <label for="username">Sign In</label>
        <input class="form-control" type="text" name="username" id="username"  placeholder="Enter your userame" />
    </div>
  <button type="submit" class="btn btn-primary">Sign In</button>  
    <br />
</form>

<div data-bind="visible: signedIn">
    <p>You are signed in as <strong data-bind="text: username"></strong></p>

var vm = {
    username: ko.observable(),
    signedIn: ko.observable(false),

    signIn: function () {
        vm.username($('#username').val());
        vm.signedIn(true);
    }
}

Currently none of my visible bindings seem to be working as it always shows the form and always shows the "You are signed in as" text. I feel like I'm missing something obvious but I hope a set of fresh eyes might help me find it. I'm using Visual Studio 2013 if that is of any help.

With Knockout observables you don't have to call the observable function by using () if you are binding directly to the observable such as data-bind="visible: signedIn . But as soon as you do something on the observable in the binding such as negate it or if you use an equality check then you will need to call the observable function to read the value first before negate it or comparing it.

So in your code you need to call the observable function as follows:

data-bind="visible: !signedIn()

In light of this I think it's best practice to always call the observable function to avoid mistakes such as this.

Instead of using jquery to get the value of username use Knockout value binding to do that.

Since you are using the Knockout submit binding there is no need to use onsubmit .

<form class="pad-bottom" data-bind="visible: !signedIn(), submit: signIn">
    <div class="form-group">
        <label for="username">Sign In</label>
        <input data-bind="value: username" class="form-control" type="text" name="username" id="username"  placeholder="Enter your userame" />
    </div>
  <button type="submit" class="btn btn-primary">Sign In</button>  
    <br />
</form>
var vm = {
    username: ko.observable(),
    signedIn: ko.observable(false),

    signIn: function () {
        vm.signedIn(true);
    }
};

JsFiddle

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