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

目的

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 over
self.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互动

相关推荐