JQuery없이 리스너에 여러 이벤트를 바인딩 하시겠습니까?
브라우저 이벤트로 작업하는 동안 모바일 장치에 Safari의 touchEvents를 통합하기 시작했습니다. 나는 addEventListener
조건부와 쌓여 있음을 발견했습니다 . 이 프로젝트는 JQuery를 사용할 수 없습니다.
표준 이벤트 리스너 :
/* option 1 */
window.addEventListener('mousemove', this.mouseMoveHandler, false);
window.addEventListener('touchmove', this.mouseMoveHandler, false);
/* option 2, only enables the required event */
var isTouchEnabled = window.Touch || false;
window.addEventListener(isTouchEnabled ? 'touchmove' : 'mousemove', this.mouseMoveHandler, false);
JQuery bind
는 다음과 같은 여러 이벤트를 허용합니다.
$(window).bind('mousemove touchmove', function(e) {
//do something;
});
JQuery 예제와 같이 두 개의 이벤트 리스너를 결합하는 방법이 있습니까? 전의:
window.addEventListener('mousemove touchmove', this.mouseMoveHandler, false);
어떤 제안이나 팁을 부탁드립니다!
POJS에서는 한 번에 하나의 리스너를 추가합니다. 동일한 요소에서 두 개의 다른 이벤트에 대해 동일한 리스너를 추가하는 것은 일반적이지 않습니다. 작업을 수행하기 위해 자신의 작은 함수를 작성할 수 있습니다. 예 :
/* Add one or more listeners to an element
** @param {DOMElement} element - DOM element to add listeners to
** @param {string} eventNames - space separated list of event names, e.g. 'click change'
** @param {Function} listener - function to attach for each event as a listener
*/
function addListenerMulti(element, eventNames, listener) {
var events = eventNames.split(' ');
for (var i=0, iLen=events.length; i<iLen; i++) {
element.addEventListener(events[i], listener, false);
}
}
addListenerMulti(window, 'mousemove touchmove', function(){…});
잘하면 그것은 개념을 보여줍니다.
2016-02-25 수정
Dalgard의 의견은 이것을 다시 방문하게 만들었습니다. 하나의 요소에 여러 이벤트에 동일한 리스너를 추가하는 것이 현재 사용중인 다양한 인터페이스 유형을 포괄하는 데 더 일반적이며, Isaac의 답변은 코드를 줄이기 위해 내장 메소드를 잘 사용하여 코드를 줄입니다. 반드시 보너스는 아닙니다). ECMAScript 2015 화살표 기능으로 확장되어 다음을 제공합니다.
function addListenerMulti(el, s, fn) {
s.split(' ').forEach(e => el.addEventListener(e, fn, false));
}
비슷한 전략으로 여러 요소에 동일한 리스너를 추가 할 수 있지만이를 수행해야 할 필요성은 이벤트 위임에 대한 표시 기일 수 있습니다.
원하는 결과를 달성하는 몇 가지 간단한 구문 인 POJS :
"mousemove touchmove".split(" ").forEach(function(e){
window.addEventListener(e,mouseMoveHandler,false);
});
Isaac의 답변 정리 :
['mousemove', 'touchmove'].forEach(function(e) {
window.addEventListener(e, mouseMoveHandler);
});
편집하다
ES6 도우미 기능 :
function addMultipleEventListener(element, events, handler) {
events.forEach(e => element.addEventListener(e, handler))
}
나를 위해; 이 코드는 잘 작동하며 동일한 (인라인) 함수로 여러 이벤트를 처리하는 가장 짧은 코드입니다.
var eventList = ["change", "keyup", "paste", "input", "propertychange", "..."];
for(event of eventList) {
element.addEventListener(event, function() {
// your function body...
console.log("you inserted things by paste or typing etc.");
});
}
ES2015 :
let el = document.getElementById("el");
let handler =()=> console.log("changed");
['change', 'keyup', 'cut'].forEach(event => el.addEventListener(event, handler));
더 간단한 해결책이 있습니다.
window.onload = window.onresize = (event) => {
//Your Code Here
}
I've tested this an it works great, on the plus side it's compact and uncomplicated like the other examples here.
AddEventListener take a simple string that represents event.type. So You need to write a custom function to iterate over multiple events.
This is being handled in jQuery by using .split(" ") and then iterating over the list to set the eventListeners for each types
.
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native events in IE.
eventHandle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = types.split(" ");
var type, i = 0, namespaces;
while ( (type = types[ i++ ]) ) { <-- iterates thru 1 by 1
One way how to do it:
const troll = document.getElementById('troll');
['mousedown', 'mouseup'].forEach(type => {
if (type === 'mousedown') {
troll.addEventListener(type, () => console.log('Mouse is down'));
}
else if (type === 'mouseup') {
troll.addEventListener(type, () => console.log('Mouse is up'));
}
});
img {
width: 100px;
cursor: pointer;
}
<div id="troll">
<img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">
</div>
참고URL : https://stackoverflow.com/questions/8796988/binding-multiple-events-to-a-listener-without-jquery
'programing tip' 카테고리의 다른 글
배열에서 첫 x 항목 반환 (0) | 2020.07.03 |
---|---|
나열 할 Pandas DataFrame 열 (0) | 2020.07.03 |
길이가 긴 요청을 허용하도록 web.config를 구성하는 방법 (0) | 2020.07.03 |
RVM 설치 중 "gpg : command not found"오류를 해결하는 방법? (0) | 2020.07.03 |
Visual C ++ 2010 Express를 사용하여 64 비트 응용 프로그램을 컴파일하는 방법은 무엇입니까? (0) | 2020.07.03 |