addEventListener 리스너 함수에 인수를 전달하는 방법은 무엇입니까?
상황은 다소 비슷합니다.
var someVar = some_other_function();
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
문제는 someVar
의 리스너 함수 내 에서 값이 표시되지 않아 addEventListener
새 변수로 취급 될 수 있다는 것입니다.
작성한 코드에는 아무런 문제가 없습니다. 모두 some_function
와 someVar
액세스 할 수 있어야합니다, 경우에 그들은 익명 곳 맥락에서 사용할 수 있었던
function() { some_function(someVar); }
창조되었다.
알림이 원하는 값을 제공하는지 확인하십시오. 익명 함수 범위에서 액세스 할 수 있는지 확인하십시오 ( someVar
에 대한 호출 옆에 동일한 변수 에서 작동하는 더 많은 코드가없는 경우 addEventListener
)
var someVar;
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
왜 이벤트의 대상 속성에서 인수를 가져 오지 않습니까?
예:
var someInput = document.querySelector('input');
someInput.addEventListener('click', myFunc, false);
someInput.myParam = 'This is my parameter';
function myFunc(evt)
{
window.alert( evt.target.myParam );
}
JavaScript는 프로토 타입 지향 언어입니다. 기억하십시오!
이 질문은 오래되었지만 후손을 위해 ES5의 .bind ()를 사용하는 대안을 제공 할 것이라고 생각했습니다. :)
function some_func(otherFunc, ev) {
// magic happens
}
someObj.addEventListener("click", some_func.bind(null, some_other_func), false);
bind에 전달할 인수로 첫 번째 param을 사용하여 리스너 함수를 설정해야하며 (다른 함수) 두 번째 param은 이제 이벤트가됩니다 (첫 번째 매개 변수 대신). .
필요한 모든 인수를 'bind'로 바인딩 할 수 있습니다.
root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));
이러한 방법으로 당신은 항상거야 event
, arg1
전달 및 기타 물건을 myPrettyHandler
.
http://passy.svbtle.com/partial-application-in-javascript-using-bind
아주 오래된 질문이지만 오늘도 같은 문제가있었습니다. 내가 찾은 가장 깨끗한 해결책은 카레 개념을 사용하는 것입니다 .
그 코드 :
someObj.addEventListener('click', some_function(someVar));
var some_function = function(someVar) {
return function curried_func(e) {
// do something here
}
}
커리 함수의 이름을 지정하면 나중에 실행 시간에 eventListener를 등록 취소하기 위해 Object.removeEventListener를 호출 할 수 있습니다.
함수를 변수로 선언하여 인수로 이벤트 리스너를 추가 및 제거 할 수 있습니다.
myaudio.addEventListener('ended',funcName=function(){newSrc(myaudio)},false);
newSrc
매개 변수로 myaudio를 사용하는 메소드 funcName
는 함수 이름 변수입니다.
리스너를 제거 할 수 있습니다 myaudio.removeEventListener('ended',func,false);
클로저로 알려진 자바 스크립트 기능을 통해 somevar를 값으로 (참조가 아닌) 전달할 수 있습니다 .
var someVar='origin';
func = function(v){
console.log(v);
}
document.addEventListener('click',function(someVar){
return function(){func(someVar)}
}(someVar));
someVar='changed'
또는 다음과 같은 일반적인 랩 함수를 작성할 수 있습니다 wrapEventCallback
.
function wrapEventCallback(callback){
var args = Array.prototype.slice.call(arguments, 1);
return function(e){
callback.apply(this, args)
}
}
var someVar='origin';
func = function(v){
console.log(v);
}
document.addEventListener('click',wrapEventCallback(func,someVar))
someVar='changed'
여기는 다음 wrapEventCallback(func,var1,var2)
과 같습니다
func.bind(null, var1,var2)
someVar
값은 some_function()
리스너가 아닌 컨텍스트 에서만 액세스 할 수 있어야합니다 . 리스너 내에서 사용하려면 다음과 같은 작업을 수행해야합니다.
someObj.addEventListener("click",
function(){
var newVar = someVar;
some_function(someVar);
},
false);
사용이 newVar
대신.
다른 방법은 리스너에서 새로운 로컬 변수로 사용하여 someVar
값 을 반환 some_function()
하는 것입니다.
var someVar = some_function(someVar);
또 다른 방법이 있습니다 (이 방법은 for 루프 내에서 작동합니다).
var someVar = some_other_function();
someObj.addEventListener("click",
function(theVar){
return function(){some_function(theVar)};
}(someVar),
false);
Function.prototype.bind () 는 대상 함수를 특정 범위에 바인딩하고 선택적으로 this
대상 함수 내에 개체를 정의하는 방법 입니다.
someObj.addEventListener("click", some_function.bind(this), false);
또는 일부 어휘 범위를 캡처하려면 (예 : 루프)
someObj.addEventListener("click", some_function.bind(this, arg1, arg2), false);
마지막으로, this
목표 함수 내에 매개 변수가 필요하지 않은 경우 :
someObj.addEventListener("click", some_function.bind(null, arg1, arg2), false);
사용하다
el.addEventListener('click',
function(){
// this will give you the id value
alert(this.id);
},
false);
그리고이 익명 함수에 사용자 정의 값을 전달하려면 가장 쉬운 방법은
// this will dynamically create property a property
// you can create anything like el.<your variable>
el.myvalue = "hello world";
el.addEventListener('click',
function(){
//this will show you the myvalue
alert(el.myvalue);
// this will give you the id value
alert(this.id);
},
false);
내 프로젝트에서 완벽하게 작동합니다. 이것이 도움이되기를 바랍니다.
eventListener의 콜백 함수에 인수를 보내려면 격리 된 함수를 만들고 해당 격리 된 함수에 인수를 전달해야합니다.
사용할 수있는 멋진 도우미 기능이 있습니다. 위의 "hello world 's 예제를 기반으로합니다.)
리스너를 깨끗하게 제거 할 수 있도록 함수에 대한 참조를 유지하는 것도 필요합니다.
// Lambda closure chaos.
//
// Send an anonymous function to the listener, but execute it immediately.
// This will cause the arguments are captured, which is useful when running
// within loops.
//
// The anonymous function returns a closure, that will be executed when
// the event triggers. And since the arguments were captured, any vars
// that were sent in will be unique to the function.
function addListenerWithArgs(elem, evt, func, vars){
var f = function(ff, vv){
return (function (){
ff(vv);
});
}(func, vars);
elem.addEventListener(evt, f);
return f;
}
// Usage:
function doSomething(withThis){
console.log("withThis", withThis);
}
// Capture the function so we can remove it later.
var storeFunc = addListenerWithArgs(someElem, "click", doSomething, "foo");
// To remove the listener, use the normal routine:
someElem.removeEventListener("click", storeFunc);
한 가지 방법은 외부 함수를 사용 하여이 작업을 수행하는 것입니다 .
elem.addEventListener('click', (function(numCopy) {
return function() {
alert(numCopy)
};
})(num));
익명 함수를 괄호로 묶고 즉시 호출하는이 방법을 IIFE (즉시 호출 함수 표현식)라고합니다.
http://codepen.io/froucher/pen/BoWwgz 에서 두 개의 매개 변수로 예제를 확인할 수 있습니다 .
catimg.addEventListener('click', (function(c, i){
return function() {
c.meows++;
i.textContent = c.name + '\'s meows are: ' + c.meows;
}
})(cat, catmeows));
또한 다음을 시도하십시오 (IE8 + Chrome. FF는 모르겠습니다).
function addEvent(obj, type, fn) {
eval('obj.on'+type+'=fn');
}
function removeEvent(obj, type) {
eval('obj.on'+type+'=null');
}
// Use :
function someFunction (someArg) {alert(someArg);}
var object=document.getElementById('somObject_id') ;
var someArg="Hi there !";
var func=function(){someFunction (someArg)};
// mouseover is inactive
addEvent (object, 'mouseover', func);
// mouseover is now active
addEvent (object, 'mouseover');
// mouseover is inactive
오타가 없기를 바랍니다 :-)
요소를 찾고 리스터를 추가하기 위해 루프에서 사용 하면서이 문제가 발생했습니다. 루프에서 사용하면 완벽하게 작동합니다.
for (var i = 0; i < states_array.length; i++) {
var link = document.getElementById('apply_'+states_array[i].state_id);
link.my_id = i;
link.addEventListener('click', function(e) {
alert(e.target.my_id);
some_function(states_array[e.target.my_id].css_url);
});
}
내가 함수를 호출하는 것을 잘못 사용하지 않으면 bind
실제로 bind
메소드 가 반환하는 새로운 함수를 만듭니다 . 기본적으로 익명 함수처럼 이벤트 리스너를 제거하려는 경우 나중에 문제가 발생합니다.
// Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', myCallback);
someObject.removeEventListener('event', myCallback);
// Not Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', function() { myCallback });
someObject.removeEventListener('event', /* can't remove anonymous function */);
그러니 염두에 두십시오.
ES6을 사용하는 경우 제안 된 것과 동일하지만 약간 더 깨끗할 수 있습니다.
someObject.addEventListener('event', () => myCallback(params));
$form.addEventListener('submit', save.bind(null, data, keyword, $name.value, myStemComment));
function save(data, keyword, name, comment, event) {
이것이 내가 이벤트를 올바르게 통과시키는 방법입니다.
var EV = {
ev: '',
fn: '',
elem: '',
add: function () {
this.elem.addEventListener(this.ev, this.fn, false);
}
};
function cons() {
console.log('some what');
}
EV.ev = 'click';
EV.fn = cons;
EV.elem = document.getElementById('body');
EV.add();
//If you want to add one more listener for load event then simply add this two lines of code:
EV.ev = 'load';
EV.add();
다음과 같은 접근 방식이 저에게 효과적이었습니다. 여기 에서 수정했습니다 .
function callback(theVar) {
return function() {
theVar();
}
}
function some_other_function() {
document.body.innerHTML += "made it.";
}
var someVar = some_other_function;
document.getElementById('button').addEventListener('click', callback(someVar));
<!DOCTYPE html>
<html>
<body>
<button type="button" id="button">Click Me!</button>
</body>
</html>
좋은 한 줄 대안
element.addEventListener('dragstart',(evt) => onDragStart(param1, param2, param3, evt));
function onDragStart(param1, param2, param3, evt) {
//some action...
}
다음 대답은 정확하지만 yuicompressor를 사용하여 js 파일을 압축했다고 가정하면 IE8에서 아래 코드가 작동하지 않습니다. (실제로 대부분의 미국 사람들은 IE8을 사용합니다)
var someVar;
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click",
function(){
some_function(someVar);
},
false);
따라서 위의 문제를 다음과 같이 해결할 수 있으며 모든 브라우저에서 제대로 작동합니다.
var someVar, eventListnerFunc;
someVar = some_other_function();
eventListnerFunc = some_function(someVar);
someObj.addEventListener("click", eventListnerFunc, false);
희망은 프로덕션 환경에서 js 파일을 압축하는 일부 사용자에게 유용 할 것입니다.
행운을 빕니다!!
모든 함수에는 특별한 변수가 있습니다 : arguments . 매개 변수를 익명 매개 변수로 전달하고 arguments 변수를 통해 순서대로 액세스 할 수 있습니다 .
예:
var someVar = some_other_function();
someObj.addEventListener("click", function(someVar){
some_function(arguments[0]);
}, false);
다음 코드는 나를 위해 잘 작동했습니다 (firefox).
for (var i=0; i<3; i++) {
element = new ... // create your element
element.counter = i;
element.addEventListener('click', function(e){
console.log(this.counter);
... // another code with this element
}, false);
}
산출:
0
1
2
당신이 필요합니다 :
newElem.addEventListener('click', {
handleEvent: function (event) {
clickImg(parameter);
}
});
이 솔루션은보기에 좋습니다.
var some_other_function = someVar => function() {
}
someObj.addEventListener('click', some_other_function(someVar));
또는 유가 증권을 묶는 것도 좋습니다
아마도 최적은 아니지만 슈퍼 js에 정통하지 않은 사람들에게는 충분할 것입니다. addEventListener를 호출하는 함수를 자체 함수에 넣습니다. 이렇게하면 전달 된 함수 값이 자체 범위를 유지하므로 원하는만큼 해당 함수를 반복 할 수 있습니다.
예 이미지와 파일 이름의 미리보기를 캡처하고 렌더링하는 데 필요한 파일 읽기 작업을 수행했습니다. 다중 파일 업로드 유형을 사용할 때 비동기 문제를 피하는 데 시간이 걸렸습니다. 다른 파일을 업로드하더라도 실수로 모든 렌더에서 동일한 '이름'을 볼 수 있습니다.
원래 모든 readFile () 함수는 readFiles () 함수 내에있었습니다. 이로 인해 비동기 범위 지정 문제가 발생했습니다.
function readFiles(input) {
if (input.files) {
for(i=0;i<input.files.length;i++) {
var filename = input.files[i].name;
if ( /\.(jpe?g|jpg|png|gif|svg|bmp)$/i.test(filename) ) {
readFile(input.files[i],filename);
}
}
}
} //end readFiles
function readFile(file,filename) {
var reader = new FileReader();
reader.addEventListener("load", function() { alert(filename);}, false);
reader.readAsDataURL(file);
} //end readFile
그냥 추가하고 싶습니다. 누구나 체크 박스를 이벤트 리스너에 업데이트하는 기능을 추가하는 경우 체크 박스를 업데이트하는 event.target
대신 사용해야 합니다 this
.
다른 대안, 아마도 바인드를 사용하는 것만 큼 우아하지는 않지만 루프의 이벤트에 유효합니다.
for (var key in catalog){
document.getElementById(key).my_id = key
document.getElementById(key).addEventListener('click', function(e) {
editorContent.loadCatalogEntry(e.srcElement.my_id)
}, false);
}
Google 크롬 확장 프로그램에 대해 테스트되었으며 다른 브라우저에서 e.srcElement를 e.source로 바꿔야 할 수도 있습니다.
Imatoria가 게시 한 의견을 사용 하여이 솔루션을 찾았 지만 평판이 충분하지 않아 유용하다고 표시 할 수 없습니다.
'IT' 카테고리의 다른 글
CSS : even 및 : odd 의사 클래스를 목록 항목과 함께 사용 (0) | 2020.03.28 |
---|---|
사용자가 Android 활동을 종료 할 것인지 확인하는 대화 상자를 표시하는 방법은 무엇입니까? (0) | 2020.03.28 |
“CPU 바운드”및“I / O 바운드”라는 용어는 무엇을 의미합니까? (0) | 2020.03.28 |
VS 코드 확장명 목록을 내보내는 방법 (0) | 2020.03.28 |
MySQL에서 테이블 이름 바꾸기 (0) | 2020.03.28 |