看博客:https://www.zhihu.com/question/27791075
1.简答的应用:
html
--------------------------------------------------
<div id="content1">
userName:<input type="text" id="useNameText" value="inputValue" data-bind="value:UserName" />
<p>
hello <b id="userNameView" data-bind="html:UserName" >inputValue</b>
</p>
<p>
hello <b id="userNameAgainView" data-bind="html:UserName" >inputValue</b> again
</p>
</div>
Js
--------------------------------------------------
var ViewModel = function(){
var self = this;
self.UserName = ko.observable("");
}
var currentViewModel = new ViewModel();
ko.applyBindings(currentViewModel);
2.数组类型双向数据的绑定
<select id="userNameList" data-bind="options:userNames,selectedOptions:selectedUserName">
</select>
<b id="selectValue" data-bind="html:selectedUserName"></b>
var ViewModel = function(){
var self = this;
self.userNames = ko.observableArray(["tom","jerry","david"]);
self.selectedUserName = ko.observable();
};
var currentViewModel = new ViewModel();
ko.applyBindings(currentViewModel);
3.循环绑定
<div id="content1">
<table>
<thead>
<tr>
<th>id</th>
<th>英文名</th>
<th>中文名</th>
<th>描述</th>
</tr>
</thead>
<tbody id="tableBody" data-bind="foreach:Planets" >
<tr>
<td data-bind="html:$index"></td>
<td data-bind="html:englishName"></td>
<td data-bind="html:chineseName"></td>
<td data-bind="html:description"></td>
</tr>
</tbody>
</table>
</div>
var Planets = [
{id:1,englishName:"Mercury",chineseName:"水星",description:"离太阳最近的一颗行星"},
{id:2,englishName:"Venus",chineseName:"金星",description:"拥有非常厚的大气层的一颗行星"},
{id:3,englishName:"Earth",chineseName:"地球",description:"我们的家园"},
{id:4,englishName:"Mars",chineseName:"火星",description:"一颗红色的星球"},
{id:5,englishName:"Jupiter",chineseName:"木星",description:"太阳系最大的行星"},
{id:6,englishName:"Saturn",chineseName:"土星",description:"拥有最美丽光环的行星"},
{id:7,englishName:"Uranus",chineseName:"天王星",description:"内核是个巨大的海洋(8000千米)"},
{id:8,englishName:"Neptune",chineseName:"海王星",description:"一颗优雅的淡蓝色行星"},
{id:9,englishName:"Pluto",chineseName:"冥王星",description:"曾经是行星的行星"}
];
var ViewModel = function(){
var self = this;
self.Planets = ko.observableArray(Planets);
self.newPlanet = function(){
self.Planets.push({id:10,englishName:"unknow",chineseName:"未知行星",description:"等待人类去发现"});
return false;
}
};
var currentViewModel = new ViewModel();
ko.applyBindings(currentViewModel);
4. 组合类型数据绑定的使用
<div id="content1">
Year:<input data-bind="value:Year"><br/>
Month:<input data-bind="value:Month"><br/>
Day:<input data-bind="value:Day"><br/>
Date:<span data-bind="html: Date " ></span><br/>
<input data-bind="value:Date" />
</div>
var ViewModel = function(){
var self = this;
self.Year = ko.observable("");
self.Month = ko.observable("");
self.Day = ko.observable("");
self.Date = ko.pureComputed({
write: function(value){
var indexOfYear = value.indexOf('年');
var indexOfMonth=value.indexOf('月');
var indexOfDay=value.indexOf('日');
self.Year(value.substring(0,indexOfYear));
self.Month(value.substring(indexOfYear+1,indexOfMonth));
self.Day(value.substring(indexOfMonth+1,indexOfDay));
},
read: function(){
return self.Year()+'年'+self.Month()+'月'+self.Day()+'日';
},
owner:self
});
};
var currentViewModel = new ViewModel();
ko.applyBindings(currentViewModel);
5.knockout中各种事件的绑定
<div id="content1">
<b id="countView" data-bind="html:CurrentIndex,style:{color:IndexColor}">0</b><br/>
<input type="button" value="点击" id="countButton" data-bind="event:{click:CounterAdd,mouseover:CounterOver,mouseout:CounterOut}">
</div>
var ViewModel = function(){
var self = this;
self.CurrentIndex = ko.observable(0);
self.CounterAdd= function(){
var currentIndex = self.CurrentIndex();
currentIndex=currentIndex+1;
self.CurrentIndex(currentIndex);
}
self.IndexColor = ko.observable("black");
self.CounterOver=function(){
self.IndexColor("red");
};
self.CounterOut=function(){
self.IndexColor("black");
};
};
var currentViewModel = new ViewModel();
ko.applyBindings(currentViewModel);
6.定义组件,避免重复造轮子
<div data-bind="component:'MessagerAndList'"></div>
<div data-bind="component:{name:'MessagerAndList',params:'jerry'}"></div>
ko.components.register(
'MessagerAndList',{
viewModel:function(){
var self = this;
self.Account = ko.observable(para);
self.Account = ko.observable(params!=null?params:"bob");
self.MessageText = ko.observable("");
self.Send = function(){
self.MessageList.push({message:self.MessageText(),account:self.Account()});
self.MessageText("");
}
self.MessageList = ko.observableArray([]);
},
template:'<input type="text" data-bind="value:MessageText" /><button id="Send" data-bind="click:Send" >发送</button><ul data-bind="foreach:MessageList"><li><p data-bind="html:message">文本内容1</p><b data-bind="html:account"></b></li></ul>'
}
);
ko.applyBindings();
7.
<div><label>地址:</label>
<select data-bind="options:CityList,optionsText:'Name',optionsValue:'Code',value:City,optionsCaption:'请选择城市'"></select>
<select data-bind="options:CurrentAreaList,optionsText:'Name',optionsValue:'Code',value:Area,optionsCaption:'请选择区县'"></select>
</div>
var ViewModel = function(){ var self = this; self.Name = ko.observable(""); self.Email = ko.observable(""); self.City = ko.observable(""); self.Area = ko.observable(""); self.CityList = ko.observableArray([ {Name:'上海市',Code:1001}, {Name:'北京市',Code:1002}, ]); self.AreaList = ko.observableArray([ {Name:'静安区',Code:1001001,CityCode:1001}, {Name:'徐汇区',Code:1001002,CityCode:1001}, {Name:'浦东区',Code:1001003,CityCode:1001}, {Name:'朝阳区',Code:1002001,CityCode:1002}, {Name:'宣武区',Code:1002002,CityCode:1002}, {Name:'海淀区',Code:1002003,CityCode:1002}, {Name:'通州区',Code:1002004,CityCode:1002} ]); self.CurrentAreaList = ko.computed(function(){ return ko.utils.arrayFilter(self.AreaList(),function(area){ return area.CityCode == self.City(); }); },self); };
8.错误验证(不常用)
代码:
<div id="content1"> <form data-bind="submit:SubmitForm"> <div><label>姓名:</label><input data-bind="value:Name"></input></div> <div><label>邮箱:</label><input data-bind="value:Email"></input></div> <div><label>地址:</label> <select data-bind="options:CityList,optionsText:'Name',optionsValue:'Code',value:City,optionsCaption:'请选择城市'"></select> <select data-bind="options:CurrentAreaList,optionsText:'Name',optionsValue:'Code',value:Area,optionsCaption:'请选择区县'"></select> </div> <div> <label>爱好:</label> <select multiple="multiple" data-bind="options:Hobbies,selectedOptions:MyHobbies"></select> </div> <div> <input type="submit" value="提交" > </div>
<div class="errors">
<p data-bind="validationMessage:Name"></p>
<p data-bind="validationMessage:Email"></p>
</div>
</form> </div>
ko.validation.configure({
registerExtenders: true,//可以添加extend的方法
insertMessages:true,//可以在输入框的右边提示,如果false的话,那么就不能再右边显示
errorClass:'errors'//代表
});
var ViewModel = function(){ var self = this; self.Name = ko.observable("").extend({required:{message:'请输入您的姓名'}}); self.Email = ko.observable("").extend({required:{message:'请输入您的邮箱地址'}}).extend({pattern:{message:'请输入正确的邮箱地址',params:'([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$'}}); self.SubmitForm = function(){ if(self.errors().length>0){ self.errors.showAllMessages(); return false; } else{ return true; } }; }
如果extend后边的require:true的话,那么提示的错误信息是英文
9.一个页面绑多个ViewModel
<div id="content1" data-model="content1"> 请选择银行:<b data-bind="click:ShowBankList" style="cursor:pointer;">选择</b> <span style="color:blue;" data-bind="html:SelectedBank"> </span> </div> <div id="content2" data-model="content2" > <div data-bind="visible:ModelVisible" > <select data-bind="options:Banks,value:SelectedBank"> <select> </div> </div>
var currentViewModel,currentViewModelNew;
$(document).ready(function(){
currentViewModel = new ViewModel("tom");
ko.attach("content1", currentViewModel);
currentViewModelNew = new ViewModelBankList("jerry");
ko.attach("content2", currentViewModelNew);
});
var ViewModel = function(name){
var self = this;
self.Name = ko.observable(name);
self.SelectedBank = ko.observable('');
self.ShowBankList = function(){
//显示银行选择列表
currentViewModelNew.Init(self.SelectedBank);
};
};
var ViewModelBankList = function(name){
var self = this;
self.ModelVisible = ko.observable(false);
self.SelectedBank = ko.observable('');
self.Banks = ko.observableArray(['中国银行','中国建设银行','花旗银行']);
self.Init=function(messageBank){
self.SelectedBank = messageBank;
self.ModelVisible(true);
}
};
10.一个简单的demo
<div id="content1" data-model="content1"> <div style="500px;"> <textarea style="height:80px;100%;" data-bind="value:MessageContent,event:{'change':MessageContentChange}"></textarea> <div> <p style="float:left;margin:0;" >还剩<b data-bind="html:RemainCount" >0</b>字</p> <label data-bind="visible:IsSendMessage()">发表中...</label> <button style="float:right;" data-bind="visible:!IsSendMessage(),click:SendMessage">发表</button> <div style="clear:both;"></div> </div> </div> <div style="500px; margin-top:12px; border:1px solid #efefef;" data-bind="foreach:MessageList"> <div style="border-bottom:1px dashed #eee;"> <span data-bind="html:Detail.Account">tom</span> <p data-bind="html:Detail.Content">微博内容</p> <span>发表于:<label data-bind="html:Detail.CreateTime" ></label></span> <span>评论(<label data-bind="html:ReplyList.length"></label>)</span> </div> </div> </div>
var MessageEntity = function(messageDetail,replyList){
var self = this;
self.Detail = messageDetail;
self.ReplyList = ko.observableArray(replyList);
}
var MessageDetailEntity = function(detail){
var self = this;
self.Account = detail.Account;
console.log(detail.Content);
self.Content = detail.Content;
self.CreateTime = detail.CreateTime;
}
var ReplyEntity = function(replyDetail){
var self = this;
self.ReplyId = replyDetail.Id;
self.Content = replyDetail.Content;
self.CreateTime = replyDetail.CreateTime;
self.ReplyAccount = replyDetail.ReplyAccount;
}
var currentViewModel;
$(document).ready(function(){
currentViewModel = new ViewModel();
ko.attach("content1", currentViewModel);
});
var ViewModel = function(){
var self = this;
self.MessageList = ko.observableArray();
self.DateTime = new Date();
self.TimeNow =ko.observable( new Date(self.DateTime.getTime()).format("yyyy-MM-dd- hh:mm:ss"));
self.MessageContent = ko.observable("");
self.CurrentMessage = ko.observable(new MessageDetailEntity({Account:"tom",Content:self.MessageContent(),CreateTime:self.TimeNow()}));
self.IsSendMessage=ko.observable(false);
self.HasNewMessage = ko.observable(false);
self.RemainCount = ko.observable(0);
self.MessageContentChange = function(){
var currentCount = self.MessageContent().length;
self.RemainCount(140-currentCount);
}
self.SendMessage = function(){
self.IsSendMessage(true);
//AJAX POST DATA TO SERVER
var messageEntity = new MessageEntity(new MessageDetailEntity({Account:"tom",Content:self.MessageContent(),CreateTime:self.TimeNow()}),[]);
self.MessageList.push(messageEntity);
self.IsSendMessage(false);
};
};