Friends Complete Sample |
|
<html>
<head><title></title>
<script type="text/javascript" src="../Scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="../Scripts/knockout-3.3.0.js"></script>
</head>
<body>
<h3>Details</h3>
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<p>Full name: <span data-bind="text: fullName"></span></p>
<h2>Friends (<span data-bind="text: friends().length"></span>)</h2>
<ul data-bind="template: { name: 'friendsTemplate', foreach: friends }"></ul>
<script id="friendsTemplate" type="text/html">
<li><input data-bind="value: name" />
<button data-bind="click: remove">Remove</button>
<label><input type="checkbox" data-bind="checked: isOnTwitter"/> Is on Twitter</label>
<input data-bind="value: twitterName, visible: isOnTwitter" /></li>
</script>
<button data-bind="click: addFriend, enable: friends().length < 5">Add friend</button>
<script type="text/javascript">
/*class*/
function friend(name) {
return {
name: ko.observable(name),
isOnTwitter: ko.observable(false),
twitterName: ko.observable(),
remove: function () { viewModel.friends.remove(this); }
};
}
var viewModel = {
firstName: ko.observable("Bert"),
lastName: ko.observable("Smith"),
friends: ko.observableArray( [new friend("Steve"), new friend("Andy")] ),
addFriend: function () { this.friends.push(new friend("Another")) }
};
viewModel.fullName = ko.dependentObservable(function () {
return this.firstName() + " " + this.lastName();
}, viewModel);
$(document).ready(function () {
ko.applyBindings(viewModel);
});
</script>
</body>
</html>