The code below demonstrates some simple features of Knockout (or knockout.js) within a Twitter Bootstrap page. The funny thing is, you need jQuery for Twitter Bootstrap, so you're forced to get the best of both worlds, at the cost of your page loading speed.
The page does 3 things:
As you put text into the input box, the text is synchronised with the H1 tag
When you're happy, you can click the "I'm happy" button
Clicking the button adds the text to the list group below
I've put the Knockout items in red.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap with Knockout</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="row">
<div class="container">
<div class="col-md-6">
<!-- This is used for adding text from the input box to the title -->
<h1 data-bind="text:title"></h1>
<form class="form-inline">
<input type="text" class="form-control" data-bind="value:title, valueUpdate:'afterkeydown'">
<!-- This is used to kick off the 'addOlEntry' function when the button is clicked -->
<button type="submit" class="btn btn-primary" data-bind="click:addOlEntry">I'm happy</button>
</form>
<hr />
<!-- Loop through the olArray -->
<ol class="list-group" data-bind="foreach:olArray">
<!-- Add a list item for each entry in the olArray -->
<li class="list-group-item" data-bind="text:$data"></li>
</ol>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
<script>
/* Create a title variable and make it observable. This becomes synced to the input box within the HTML.
Create an array and make that also observable.
Create a function which is called when the button is clicked and adds the title text to the array.#
Bind it all together. */
var vm =
{
title:ko.observable(),
olArray:ko.observableArray(),
addOlEntry:function()
{
this.olArray.push(this.title());
}
}
ko.applyBindings(vm);
</script>
</body>
</html>
No comments:
Post a Comment