亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

KnockoutJS 3.X API 第四章之事件event綁定

 更新時間:2016年10月10日 11:27:30   作者:SmallProgram  
event綁定即為事件綁定,即當觸發(fā)相關(guān)DOM事件的時候回調(diào)函數(shù),這篇文章主要介紹了KnockoutJS 3.X API 第四章之事件event綁定的相關(guān)知識,感興趣的朋友一起看看吧

目的

event綁定即為事件綁定,即當觸發(fā)相關(guān)DOM事件的時候回調(diào)函數(shù)。例如keypress,mouseover或者mouseout等

例如:

Mouse over me

源碼:

<div>
<div data-bind="event: { mouseover: enableDetails, mouseout: disableDetails }">
Mouse over me
</div>
<div data-bind="visible: detailsEnabled">
Details
</div>
</div>
<script type="text/javascript">
var viewModel = {
detailsEnabled: ko.observable(false),
enableDetails: function() {
this.detailsEnabled(true);
},
disableDetails: function() {
this.detailsEnabled(false);
}
};
ko.applyBindings(viewModel);
</script>

如上述例子,當鼠標指針移入或者移出Mouse over me時,對于detailsEnabled的值設(shè)定true或者false。進而控制Details的顯示和隱藏。

和click一樣,event后邊所跟的格式一般為:event { mouseover: someObject.someFunction },其中的回調(diào)函數(shù)并不一定非要是視圖模型的函數(shù),他可以時任何對象的函數(shù)。

備注1:傳遞一個當前項目作為參數(shù)

London
Paris
Tokyo
You seem to be interested in:

源碼:

<ul data-bind="foreach: places">
<li data-bind="text: $data, event: { mouseover: $parent.logMouseOver }"> </li>
</ul>
<p>You seem to be interested in: <span data-bind="text: lastInterest"> </span></p>
<script type="text/javascript">
function MyViewModel() {
var self = this;
self.lastInterest = ko.observable();
self.places = ko.observableArray(['London', 'Paris', 'Tokyo']);

// The current item will be passed as the first parameter, so we know which place was hovered over
self.logMouseOver = function(place) {
self.lastInterest(place);
}
}
ko.applyBindings(new MyViewModel());
</script>

需要注意,如果你使用的是嵌套綁定上下文,比如foreach或者with,而需要處理的回調(diào)函數(shù)在視圖模型中或者在父模型中,需要使用$parent或者$root前綴來進行綁定

與click綁定一樣,給this取個別名比較好。

備注2:傳遞多個參數(shù)

此處請參考click綁定:

<div data-bind="event: { mouseover: myFunction }">
Mouse over me
</div>
<script type="text/javascript">
var viewModel = {
myFunction: function(data, event) {
if (event.shiftKey) {
//do something different when user has shift key down
} else {
//do normal action
}
}
};
ko.applyBindings(viewModel);
</script>

封裝多參數(shù)示例:

<div data-bind="event: { mouseover: function(data, event) { myFunction('param1', 'param2', data, event) } }">
Mouse over me
</div>

使用bind函數(shù)示例:

<button data-bind="event: { mouseover: myFunction.bind($data, 'param1', 'param2') }">
Click me
</button>

備注3:允許默認動作

同click綁定一樣,ko禁止默認動作,比如你將event的keypress事件綁定到一個Input元素上,那這個input元素輸入的值將會被keypress回調(diào)占用而無法輸入任何信息。解決方案很簡單,就是在回調(diào)函數(shù)中返回true即可。

備注4:防止冒泡事件

如果要防止冒泡事件,可以直接在事件綁定后附加一個youreventBubble綁定。將該附加綁定設(shè)置為false則禁止冒泡事件的發(fā)生,例如:

<div data-bind="event: { mouseover: myDivHandler }">
<button data-bind="event: { mouseover: myButtonHandler }, mouseoverBubble: false">
Click me
</button>
</div>

備注5:Jquery互動

以上所述是小編給大家介紹的KnockoutJS 3.X API 第四章之事件event綁定,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評論