Knockout JS Binding Update Confusion
I am new to KO and JS and did the following test. I want to see a login button when vm.authenticated == false
and a logout button when vm.authenticated == true
. I can see that the title changes correctly, so I seem to anchor well, but KO if
doesn't seem to work. I tried to make it authenticated
observable, but that fixed it. Any help is appreciated.
Thanks and Regards
Here is the HTML code:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8"/>
<title>Test</title>
</head>
<body>
<script src="../Scripts/libs/jquery-1.9.0.js"></script>
<script src="../Scripts/libs/knockout-2.2.1.debug.js"></script>
<p data-bind="text: title"></p>
<!-- ko if: authenticated == false -->
<form>
<input type="text" data-bind="value: userId"/>
<input type="password" data-bind="value: password"/>
<button type="button" data-bind="click: login">Login</button>
</form>
<!-- /ko -->
<!-- ko if: authenticated == true -->
<form>
<input type="text" data-bind="value: userId"/>
<button type="button" data-bind="click: logout">Logout</button>
</form>
<!-- /ko -->
<script type="text/javascript">
window.onload = function () {
var vm = {userId: 'user', password: 'password', title: 'unsigned', authenticated: false, login: function () {
var vm1 = {
userId: 'user', password: 'password', title: 'unsigned1', authenticated: true, login: function () { }, logout: function () {
var vm2 = { userId: 'user', password: 'password', title: 'unsigned2', authenticated: false, login: function () { }, logout: function () { } };
ko.applyBindings(vm2);
}
};
ko.applyBindings(vm1);
}, logout: function () { }
};
ko.applyBindings(vm);
};
</script>
</body>
</html>
source to share
Is this what you are trying to achieve?
var vm = {
userId: 'user',
password: 'password',
title: ko.observable('unsigned'),
authenticated: ko.observable(false),
login: function () {
vm.userId = 'user';
vm.password = 'password';
vm.title('unsigned1');
vm.authenticated(true);
},
logout: function () {
vm.userId = 'user';
vm.password = 'password';
vm.title('unsigned2');
vm.authenticated(false)
}
};
ko.applyBindings(vm);
And also notice what ben336 said about how you define your binding.
source to share
<!-- ko if: authenticated == true -->
it should be
<!-- ko if: authenticated -->
the if expression tests the plausibility of a variable, not an expression.
See documentation
for
<!-- ko if: authenticated == false -->
you can use
<!-- ko ifnot: authenticated -->
Update
I didn't notice your triple peg right away. You must register one model object to be bound. If you want a property to respond to updates, you can make it observable.
source to share