简介
KnockOut是什么呢?他是一个很优秀的JavaScript库,可以使用很少的代码实现双向绑定,大大的减少了代码量,这种双向绑定类似于angularJS中的双向绑定,所以,学过angularJS的读者学习KnockOut可能更好上手。如下是官网上的介绍,介绍中说到了KO,KO就是knockOutJS的缩写,在实现中用来调用applyBindings方法激活KnockOut,说到这里你可能有点云里雾里了,没关系,如果你想学习,请坚持看完本篇文章,敲出第一个Demo,相信会有很大的收获。官方网址:http://knockoutjs.com/documentation/introduction.html
Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.
MVVM模式与ViewModel
声明、激活与绑定
1.声明:使用KO需要声明一个viewmodel,例如:
var myViewModel={
name:zhangzhang,
age:25
};
2.激活:有两种方式,全部激活和指定部分激活。
全部激活:
ko.applyBindings(myViewModel);
指定部分激活:
ko.applyBindings(myViewModel, document.getElementById('someElementId'));
3.绑定:创建一个view进行绑定。
<p>Name: <input data-bind='value: name' /></p>
Demo
1.先去官网下载需要引用到项目中的knockout核心类库
2.下载需要引用到项目中的jquery的核心类库,网址:http://pan.baidu.com/s/1bFiZ3w
3.打开VS,依次选择File>New>web site,按照下图操作,创建出空白的web程序后,右键你的项目-->添加--->添加新建项目-->选择html页,至此我们就创建出了html页,如有疑问,请参考:http://jingyan.baidu.com/article/219f4bf799c0ccde442d3811.html
建立完项目之后,将前两步下载的js拷贝到项目所在文件夹下,拷贝完之后的解决方案布局如下:
4.在前期的工作做好之后我们就开始敲代码了。在head标签中添加了两个js的引用,在body标签中添加一个div,其中input标签的data-bind是knockout用来双向绑定的属性,再添加一个script标签,我们首先定义一个viewmodel,然后 ko.applyBindings用来激活。代码如下:
<!DOCTYPE html>
<html>
<head>
<title>myFirstDemo</title>
<meta charset="utf-8" />
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript" src='knockout-3.4.1.js'></script>
</head>
<body>
<!--静态绑定-->
<div class='liveExample'>
<p>First name: <input data-bind='value: firstName' /></p>
<p>Last name: <input data-bind='value: lastName' /></p>
<h2>Hello, <span data-bind='text: fullName'> </span>!</h2>
</div>
<script>
// 定义一个ViewModel
var ViewModel = function (first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function () {
// 根据firstName和lastNamecomputed出fullName
return this.firstName() + " " + this.lastName();
}, this);
};
//knockout调用applybindings激活ViewModel,即,使得ViewModel与上述div中的静态绑定联系起来
ko.applyBindings(new ViewModel("zhang", "zhang")); // This makes Knockout get to work
</script>
</body>
</html>
5.效果图:
遇到的问题
刚开始是将body中的script标签添加到了head中,结果导致如下错误,错误原因是,若将绑定写在view之前,那么在激活的时候就不知道是要绑定谁,则会报错,解决办法就是将script标签写在view之下。