您的位置:首页 > Web前端 > JavaScript

#7 事件处理

2017-07-16 22:30 281 查看
英文原版:https://guides.emberjs.com/v2.14.0/components/handling-events/

你可以在你的组件上通过事件处理函数响应用户事件,比如:双击、悬停等。实现这样的方式比较简单。

例子,比如我们现在有个模板:

{{#double-clickable}}
This is a double clickable area!
{{/double-clickable}}


让我们实现double-click组件,并且当用户点击后弹出一个提示框:

app/components/double-clickable.js

import Ember from 'ember';

export default Ember.Component.extend({
doubleClick() {
alert("DoubleClickableComponent was clicked!");
}
});


浏览器事件会冒泡到父组件。如果你需要开启冒泡,那么在事件处理函数的最后返回true。

app/components/double-clickable.js

import Ember from 'ember';

export default Ember.Component.extend({
doubleClick() {
Ember.Logger.info("DoubleClickableComponent was clicked!");
return true;
}
});


本节的末尾有事件名称列表,并且可以直接使用事件名称来定义你的事件处理函数。

发送Actions

在一些情况下你的组件需要定义事件处理函数,或许是要处理各种拖拽行为。例子,组件会在接收到一个drop事件的时候发送一个id。

{{drop-target action=(action "didDrop")}}


你可以定义事件处理函数来管理drop事件。并且如果你觉得有必要,你也可以在处理函数的默认返回false来阻止事件冒泡。

app/components/drop-target.js

import Ember from 'ember';

export default Ember.Component.extend({
attributeBindings: ['draggable'],
draggable: 'true',

dragOver() {
return false;
},

drop(event) {
let id = event.dataTransfer.getData('text/data');
this.get('action')(id);
}
});


在上面的组件中,didDrop是被传入的action。这个action在drop事件处理函数中被调用,并且传入了一个参数—-id参数从drop事件对象中得到。

另一种保留本地事件行为和使用action的方式,是赋值一个内嵌的行内action给事件处理函数。看下面的定义事件处理函数的形式:

<button onclick={{action 'signUp'}}>Sign Up</button>


signUp Action是一个定义在actions对象中的一个简单的函数。一旦action被赋值给了事件属性,那么这个action函数的第一个参数就会是事件对象。

actions: {
signUp(event){
// Only when assigning the action to an inline handler, the event object
// is passed to the action as the first parameter.
}
}


正常的action函数不会收到事件对象参数。下面的例子是使用action的默认的方式:

<button {{action 'signUp'}}>Sign Up</button>


actions: {
signUp(){
// No event object is passed to the action.
}
}


所以,获取事件对象有2种方式:

通过事件名称定义事件处理函数。

将action赋值给事件属性。

事件名称

内键的事件名称参见下面的名单。自定义事件可以通过Ember.Application.customEvents来注册使用。

触摸事件:

touchStart

touchMove

touchEnd

touchCancel

键盘事件

keyDown

keyUp

keyPress

鼠标事件

mouseDown

mouseUp

contextMenu

click

doubleClick

mouseMove

focusIn

focusOut

mouseEnter

mouseLeave

表单事件

submit

change

focusIn

focusOut

input

HTML5 拖放事件

dragStart

drag

dragEnter

dragLeave

dragOver

dragEnd

drop

本节完
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息