Click here to Skip to main content
15,887,877 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
<html>
<script type='text/javascript' src='js/knockout-3.1.0.js'></script>
<body>
<form data-bind="submit: addItem">
New item:
<input data-bind='value: itemToAdd, valueUpdate: "afterkeydown"' />
<button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
<p>Your items:</p>
<select multiple="multiple" width="50" data-bind="options: items"> </select>
</form>
------------------------------------------------------------
<div>You've clicked <span data-bind='text: numberOfClicks'>&nbsp;</span> times</div>

<button data-bind='click: registerClick, disable: hasClickedTooManyTimes'>Click me</button>

<div data-bind='visible: hasClickedTooManyTimes'>
That's too many clicks! Please stop before you wear out your fingers.
<button data-bind='click: resetClicks'>Reset clicks</button>
</div>
</body>
</html>

<script type='text/javascript'>

var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(2);

this.registerClick = function() {
this.numberOfClicks(this.numberOfClicks() + 1);
};

this.resetClicks = function() {
this.numberOfClicks(0);
};

this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() >= 10;
}, this);
};

ko.applyBindings(new ClickCounterViewModel());


var SimpleListModel = function(items) {
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function() {
if (this.itemToAdd() != "") {
this.items.push(this.itemToAdd()); // Adds the item. Writing to the "items" observableArray causes any associated UI to update.
this.itemToAdd(""); // Clears the text box, because it's bound to the "itemToAdd" observable
}
}.bind(this); // Ensure that "this" is always this view model
};

ko.applyBindings(new SimpleListModel(["Alpha", "Beta", "Gamma"]));

</script>
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900