AddeventListener 청취자 기능에 인수를 전달하는 방법은 무엇입니까?
-
05-07-2019 - |
문제
상황은 다소 비슷합니다.
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);
바인드에 전달하는 인수 (다른 함수)로 첫 번째 매개 변수를 사용하여 청취자 기능을 설정해야하며 두 번째 매개 변수는 이제 이벤트 (첫 번째 대신)입니다. .
변수로 함수를 선언하여 인수로 eventListeners를 추가하고 제거 할 수 있습니다.
myaudio.addEventListener('ended',funcName=function(){newSrc(myaudio)},false);
newSrc
매개 변수로서 MyAudio의 메소드입니다funcName
함수 이름 변수입니다
리스너를 제거 할 수 있습니다 myaudio.removeEventListener('ended',func,false);
꽤 오래된 질문이지만 오늘도 같은 문제가있었습니다. 내가 찾은 가장 깨끗한 해결책은 카레.
그것의 코드 :
someObj.addEventListener('click', some_function(someVar));
var some_function = function(someVar) {
return function curried_func(e) {
// do something here
}
}
Curried 함수의 이름을 사용하여 Object.removeEventListener를 호출하여 이후 실행 시간에 이벤트 리스트너를 등록 해제 할 수 있습니다.
필요한 모든 인수를 'bind'로 바인딩 할 수 있습니다.
root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));
이런 식으로 당신은 항상 얻을 수 있습니다 event
, arg1
, 그리고 다른 것들이지나 갔다 myPrettyHandler
.
http://passy.svbtle.com/partial-application-in-javaScript-using-bind
당신은 JavaScript 기능을 통해 값 (참조가 아닌)별로 일부를 전달할 수 있습니다. 폐쇄:
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) :
var someVar = some_function(someVar);
또 다른 방법은 다음과 같습니다 (이것은 루프 내부에서 작동합니다) :
var someVar = some_other_function();
someObj.addEventListener("click",
function(theVar){
return function(){some_function(theVar)};
}(someVar),
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);
내 프로젝트에서 완벽하게 작동합니다. 이것이 도움이되기를 바랍니다
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);
또한 이것들 (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
오타가 없기를 바랍니다 :-)
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));
요소를 찾고 Listner를 추가하기 위해 루프로 사용하면서 이것에 갇혀있었습니다. 루프에서 사용하는 경우 완벽하게 작동합니다.
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));
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>
$form.addEventListener('submit', save.bind(null, data, keyword, $name.value, myStemComment));
function save(data, keyword, name, comment, event) {
이것이 제가 이벤트를 제대로 통과 한 방법입니다.
다음 답변은 정확하지만 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 파일을 압축하는 사람들에게 유용 할 것입니다.
행운을 빕니다!!
모든 기능에는 특수 변수가 있습니다. 논쟁. 당신은 당신의 매개 변수를 익명 매개 변수로 전달하고 (순서별로) 논쟁 변하기 쉬운.
예시:
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));
또는 바인드 밸리에이블도 좋을 것입니다
좋은 한 줄 대안
element.addEventListener('dragstart',(evt) => onDragStart(param1, param2, param3, evt));
function onDragStart(param1, param2, param3, evt) {
//some action...
}
아마도 최적은 아니지만 슈퍼 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
다른 대안, 아마도 바인딩 사용만큼 우아하지는 않지만 루프의 이벤트에 유효합니다.
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 Chrome 확장에 대한 테스트를 거쳤으며 E.Srcelement를 다른 브라우저에서 E.Source로 대체해야합니다.
이 솔루션을 사용하여 찾았습니다 논평 게시자에 의해 이마토리아 하지만 명성이 충분하지 않아서 유용하다고 표시 할 수 없습니다 : D