visible、text、html、css、style、attr、foreach、if、with、click、enable/disable、event、submit、value、checked、options、selectOptions、uniqueName、
1、visible綁定:依賴元素是否可見
demo:
<div data-bind="visible:!arrayBoolen()">This is not a number</div>
<script>
var vm = {
var arrayBoolen : ko.observableArray([]);
}
vm.arrayBoolen.push("aaa");
ko.applyBindings(vm);
</script>
2、text綁定:讓DOM元素顯示參數(shù)值 demo:
Today's message is:<span data-bind="text:myMessage"></span>
<script>
var vm = {
var myMessage : ko.observable();
}
vm.myMessage("hello");
</script>
注:如果需要在不使用多余的元素的情況下通過Text綁定來設(shè)置文本內(nèi)容,如:在option元素中是不允許其他元素的,所以解決這種問題,可以使用容器語法,它基于一個注釋元素<!-ko-><!-/ko->
eg: <select data-bind="items">
<option>Item<!-ko text:name-><!-/ko-></option>
</select>
3、HTML綁定:讓元素的innerHTML顯示你綁定的參數(shù)值,之前的內(nèi)容將被覆蓋 eg:
<div data-bind="html:details"></div>
<script>
var vm={details:ko.observable()};
vm.details("<em>For further details,view the report<a href='report.html'></a>.</em>")
</script>
注意:由于綁定設(shè)置元素的innerHTML,可能會引起腳本注入攻擊,所以如果你不確定是否安全,比如顯示用戶輸入的內(nèi)容,應(yīng)該使用text綁定,因為這個綁定只是設(shè)置元素的text值
4、CSS類名綁定:css綁定是添加或刪除一個或多個CSS class到DOM上,參數(shù)是一個js對象,屬性是css的class名稱,值是true或false,用來決定是否使用該class(true的時候添加,false的時候刪除)
eg:當(dāng)aa<0時,添加class=profileWaring到元素上,大于0則不添加:
<div data-bind="css:{profileWaring:aa()<0}"></div>
<script>
var vm={aa:ko.observalbe(150)};
</script>
class也可以添加多個,用逗號隔開
eg:<div data-bind="css:{profileWaring:aa()<0 , 'my-class':someValue}"></div>
5、style綁定:添加或刪除DOM元素的一個或多個style值,參數(shù)是一個js對象,屬性是style名稱
eg:
<div data-bind="style:{color:aa()<0?'red':'green'}"></div>
<script>
var vm = {aa:ko.observalbe(150)};
</script>
如果為多個屬性:逗號隔開
<div data-bind="style:{color:aa()<0?'red':'green' , fontWeight:bb()>0?'bold':'normal'}"></div>
注:如果要使用屬性為-隔開的,去掉-,采用js的駝峰命名的方式,如font-weight-->fontWeight
6、attr綁定:給DOM元素添加自定義屬性,或綁定到已有屬性
eg:
<a data-bind="href:url , title:descript"></a>
<script>
var vm = {
url:ko.observable("www.baidu.com"),
descript:ko.observalbe("this is a smark")
}
</script>
7、foreach綁定:此功能可以幫助我們方便的循環(huán)遍歷輸出某個數(shù)組,集合的內(nèi)容
eg:table表格動態(tài)添加刪除:
<button data-bind="click:addGuest">Add</button>
<table>
<thead>
<tr><th>First name</th><th>Last name</th><th>operate</th></tr>
</thead>
<tbody data-bind="foreach:guests">
<tr>
<td data-bind="text:firstName"></td>
<td data-bind="text:lastName"></td>
<td><a data-bind="click:$parent.removeGuest">remove</a>
<a data-bind="click:$parent.addGuest">add</a></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function operateArray(){
var self = this;
self.guests = ko.observableArray(
[{firstName:"jane",lastName:"jones"},
{firstName:"jack",lastName:"brown"},
{firstName:"baby",lastName:"huang"}]
);
self.addGuest = function(){
self.guests.push({firstName:"aaa",lastName:"_aa"});
};
self.removeGuest = function(){
self.guests.remove(this);
}
}
ko.applyBindings(new operateArray());
</script>
注:如果綁定的循環(huán)數(shù)組中的每個值都是數(shù)組而不是json對象,想要輸出所有數(shù)組值,綁定$data即可
eg:
<ul data-bind="foreach: people">
<li>
Name at position <span data-bind="text: $index"> </span>:
<span data-bind="text: $data"> </span>
</li>
</ul>
var vm = {
people = ko.observableArray(["aa","bb","cc"]);
}
$index:數(shù)組下標(biāo)
$parent:調(diào)用循環(huán)體foreach之外的依賴屬性
另:使用foreach的時候,是默認(rèn)不顯示被標(biāo)記為刪除但是實際未被刪除的元素的,如果要顯示的話,可以使用includeDestroyed:true
eg:<div data-bind="foreach:{data:myArray,includeDestroyed:true}"></div>
8、if綁定:可以控制某個組件動態(tài)顯示,類似visible,但不同的是,if綁定是真正的控制html標(biāo)簽是否出現(xiàn)在DOM中,是會修改DOM結(jié)構(gòu)的,因此處于性能考慮,不應(yīng)該頻繁使用if
eg:通過勾選與否來確定div內(nèi)容是否顯示
<input type="checkbox" data-bind="checked:showMessages"/>
<div data-bind="if:showMessages">this is a test div</div>
var vm = {showMessages:ko.observable(false)};
9、with綁定:通過使用with綁定來重新定義一個上下文綁定,從而可以直接使用它里面的屬性
eg:
<h1 data-bind="text:province"></h1>
<div data-bind="with:city">
<p data-bind="city1"></p>
<p data-bind="city2"></p>
</div>
var vm = {
province:"hubei",
city:{
city1:"wuhan",
city2:"enshi"
}
}
10、click綁定 eg:點擊按鈕,click次數(shù)加1
Click times: <p data-bind="text:clickTimes">
<button data-bind="click:AddClickTimes"></button>
function clickCount(){
var self = this;
self.clickTimes = ko.observable(0);
self.AddClickTimes = function(){
var previous = self.clickTimes()+1;
self.clickTimes = ko.observable(previous);
}
}
click綁定注意事項:
1、如果在foreach或者with塊中使用click綁定,而click對應(yīng)的方法在view model的根部或者他的父上下文,則需通過$parent或者$root來定位我們的方法
2、通常會在view model中為this起一個別名,防止this指向的地方改變導(dǎo)致程序錯誤
3、定義事件:eg:myFunction:function(event){...}
4、傳遞多個參數(shù)
eg: <button data-bind="click:function(data,event){myFunction('param1','param2',data,event)}"></button>
如果不想在標(biāo)簽中出現(xiàn)這么多內(nèi)容的話,可以使用KO的綁定方法進(jìn)行傳遞
如:<button data-bind="click:myFunction.bind($data,'param1','param2')"></button>
5、防止事件沖突:
如果子元素和父元素同時綁定了click事件,點擊子元素的時候,兩個事件都會執(zhí)行,為了阻止事件執(zhí)行,可以用clickBubble:false
eg:<div data-bind="click:myDIVFunction"><p data-bind="click:myPFunction,clickBubble:false"></p></div>
11、enable/disable綁定: 一般用在input select textarea等上面
eg:
Your phone number is:
<input type="text" data-bind="value:cellPhoneNumber,enable:hasCellPhone">
var vm = {
hascellPhone:ko.observable(false),
cellPhoneNumber:""
}
12、event綁定: 一般用在keypress,mouseover,mouseout上面,需要傳入一個js對象,屬性名是事件名稱,值是你所需要執(zhí)行的函數(shù)
eg:
<div data-bind="event:{mouseover:enableDetail,mouseout:disableDetail}"></div>
注1:傳參:最簡單的傳一個function包裝的匿名函數(shù):
data-bind="event:{function(){vm.myFunction('params1','params2')}}"
注2:訪問事件源對象:
var vm={myFunction:function(event){if(event.shiftKey){}}}
注3:訪問事件源對象同時傳參:
data-bind="event:{function(event){vm.myFunction(event,'param1','param2'){}}}"
注4:允許執(zhí)行默認(rèn)事件:
knockout默認(rèn)情況是阻止默認(rèn)事件的,但是有時候我們需要默認(rèn)事件繼續(xù)執(zhí)行,如在input上面綁定了keypress事件,這樣在輸入內(nèi)容時,就會只調(diào)用keypress事件而不會將輸入值添加到input輸入框中,此種情況下,我們需要讓默認(rèn)事件繼續(xù)執(zhí)行,需要在event自定義函數(shù)中返回true
注5:防止事件冒泡:
默認(rèn)情況下,knockout允許event事件繼續(xù)往上層事件句柄冒泡執(zhí)行,如父元素和子元素都綁定了click事件,點擊子元素的click執(zhí)行之后,默認(rèn)會繼續(xù)執(zhí)行父元素的click事件,如需禁止冒泡,可以通過eventBubble:false來禁止冒泡
eg:
<div data-bind="event:{mouseover:myFunction}">
<button data-bind="event:{mouseover:myButtonFunction},mouseoverBubble:false"><>
</div>
13、submit綁定:只用在form表單上,knockout會阻止form表單默認(rèn)的submit動作,如果要執(zhí)行form表單默認(rèn)的submit動作,可以在綁定的submit句柄里返回true
14、value綁定:鍛煉DOM元素的值到view model的屬性上,一般用在input,select,textarea上
只有當(dāng)用戶離開焦點(如onchange事件)的時候,KO才更新這個值,但是我們可以通過第二個參數(shù)valueUpdate來特別指定改變值的時間
valueUpdate:'change'(默認(rèn)值)--當(dāng)失去焦點的時候更新,或者是select被選擇的時候
valueUpdate:'keyup'---當(dāng)用戶敲完一個字符以后立即更新到view model
valueUpdate:'keypress'--當(dāng)用戶正在敲一個字符但是沒有釋放鍵盤的時候就更新,類似keydown
valueUpdate:'afterkeydown'--當(dāng)用戶開始輸入字符的時候就更新,主要是捕獲瀏覽器的keydown事件或者是異步handle事件(如果讓vm實時更新,afterkeydown是最好的選擇)
eg:
<input data-bind="value:someValue,valueUpdate:'afterkeydown'">
<span data-bind="text:console_"></span>
function vm(){
var self = this;
self.someValue = ko.observable("begin");
selft.console_ = ko.computed(function(){
return console.log(self.someValue());
});
}
15、checked:checkBox、radio 注:checkbox關(guān)聯(lián)到數(shù)組:
eg:
want to begin to select? Y:<input data-bind="checked:beginSelect">
<div data-bind="visible:beginSelect">
<div><input type="checkbox" value="cherry" data-bind="checked:kindSelect"></div>
</div>
<div data-bind="visible:beginSelect">
<div><input type="checkbox" value="almond" data-bind="checked:kindSelect"></div>
</div>
<div data-bind="visible:beginSelect">
<div><input type="checkbox" value="msg" data-bind="checked:kindSelect"></div>
</div>
var vm = {
beginSelect:ko.observable(true),
kindSelect:ko.observableArray(["cherry","almond"])
}
16、options:綁定在select標(biāo)簽上 1)單選:
<select data-bind="options:availableCountries"></select>
var vm = {availableCountries:ko.observable(["france","germany","spain"])}
2)多選:
<select data-bind="options:availableCountries" size="3" multiple="true"></select>
3)dropdown list展示的是任意js對象,不僅僅是字符串
<select data-bind="options:availableCountries , optionText:'countryName' , value:selectedCountry,optionsCaption:'Choose...'"></select>
<span data-bind="visible:selectedCountry,text:selectedCountry()?selectedCountry().countryName:'unknow'"></span>
var coutry = function(name,population){this.name=name;this.population=population}
var vm = {
availableCountries:ko.observableArray([new country("US",11111),new country("Sweden,22222"),new country("china,33333")]),
selectedCountry:ko.observable();
}
參數(shù)說明:
主參數(shù):options:一個數(shù)組
如果是一個string數(shù)組,<select>會將每個string展示成一個option,不在需要其他參數(shù)
如果是一個js對象數(shù)組,那就需要設(shè)置optionsText和optionsValue這兩參數(shù)了
其他參數(shù):
optionsCaption:有時不需要有默認(rèn)選擇值,可以通過optionsCaption添加一個“請選擇..”之類的提示語,如optionsCaption:“please select an item...”
optionsText:對于option上綁定是JS數(shù)組的,需要設(shè)置哪個值作為text值來顯示在select框中,如上例中的optionsText:'countryName';如果不想僅僅顯示對應(yīng)的屬性值為每個item的text值,可以設(shè)置optionsText為js函數(shù),在函數(shù)中通過自己的邏輯返回相應(yīng)的值,如:optionsText:function(item){return item.countryName+'(prop: '+item.population+')'}
optionsValue:通過額外參數(shù)聲明對象哪個屬性值為該<option>的value值
17、selectOptions:用于控制select列表已經(jīng)被選擇的元素
18、uniqueName:確保所綁定的元素有一個非空的name屬性。uniqueName:true