目的
event綁定即為事件綁定,即當觸發相關DOM事件的時候回調函數。例如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的值設定true或者false。進而控制Details的顯示和隱藏。
和click一樣,event后邊所跟的格式一般為:event { mouseover: someObject.someFunction },其中的回調函數并不一定非要是視圖模型的函數,他可以時任何對象的函數。
備注1:傳遞一個當前項目作為參數
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 overself.logMouseOver = function(place) {self.lastInterest(place);}}ko.applyBindings(new MyViewModel());</script>需要注意,如果你使用的是嵌套綁定上下文,比如foreach或者with,而需要處理的回調函數在視圖模型中或者在父模型中,需要使用$parent或者$root前綴來進行綁定
與click綁定一樣,給this取個別名比較好。
備注2:傳遞多個參數
此處請參考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>封裝多參數示例:
<div data-bind="event: { mouseover: function(data, event) { myFunction('param1', 'param2', data, event) } }">Mouse over me</div>使用bind函數示例:
<button data-bind="event: { mouseover: myFunction.bind($data, 'param1', 'param2') }">Click me</button>備注3:允許默認動作
同click綁定一樣,ko禁止默認動作,比如你將event的keypress事件綁定到一個Input元素上,那這個input元素輸入的值將會被keypress回調占用而無法輸入任何信息。解決方案很簡單,就是在回調函數中返回true即可。
備注4:防止冒泡事件
如果要防止冒泡事件,可以直接在事件綁定后附加一個youreventBubble綁定。將該附加綁定設置為false則禁止冒泡事件的發生,例如:
<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綁定,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答