使用参数添加和删除事件侦听器

时间:2013-02-26 11:31:02

标签: javascript dom javascript-events

我正在编写一个 vanilla JavaScript 工具,启用后会为传递给它的每个元素添加事件侦听器。

我想做这样的事情:

var do_something = function (obj) {
        // do something
    };

for (var i = 0; i < arr.length; i++) {
    arr[i].el.addEventListener('click', do_something(arr[i]));
}

不幸的是,这不起作用,因为据我所知,在添加事件监听器时,参数只能传递给匿名函数

for (var i = 0; i < arr.length; i++) {
    arr[i].el.addEventListener('click', function (arr[i]) {
        // do something
    });
}

问题是我需要能够在禁用该工具时删除事件侦听器,但我认为不可能删除具有匿名函数的事件侦听器

for (var i = 0; i < arr.length; i++) {
    arr[i].el.removeEventListener('click', do_something);
}

我知道我可以轻松地使用jQuery来解决我的问题,但我正在尝试最小化依赖性。 jQuery必须以某种方式解决这个问题,但代码有点像丛林!

4 个答案:

答案 0 :(得分:8)

这是无效的:

arr[i].el.addEventListener('click', do_something(arr[i]));

侦听器必须是函数引用。您无法在侦听器分配时指定参数。将始终调用处理程序函数,并将event作为第一个参数传递。要传递其他参数,您可以将侦听器包装成一个匿名函数,如下所示:

elem.addEventListener('click', function(event) {
  do_something( ... )
}

为了能够通过removeEventListener删除你只需命名处理函数:

function myListener(event) {
  do_something( ... );
}

elem.addEventListener('click', myListener);

要在处理函数中访问其他变量,可以使用闭包。 E.g:

function someFunc() {
  var a = 1,
      b = 2;

  function myListener(event) {
    do_something(a, b);
  }

  elem.addEventListener('click', myListener);
}

答案 1 :(得分:0)

您可以使用

for (var i = 0; i < arr.length; i++) {
    arr[i].el.addEventListener('click', do_something);
}

当事件作为第一个参数传递给do_something函数时,您可以从事件中获取元素

function do_something(e) {
    var obj = e.currentTarget
    // do something
}

删除侦听器

for (var i = 0; i < arr.length; i++) {
    arr[i].el.removeEventListener('click', do_something);
}

如果你想传递另一个obj作为参数做这个

for (var i = 0; i < arr.length; i++) {
    arr[i].el.addEventListener('click', do_something, obj);
}

答案 2 :(得分:-1)

这可以很容易地完成,就像你现在没有那样。

您需要添加或删除处理其他函数执行的函数,而不是尝试添加和删除随机匿名函数。

var
    // Here we are going to save references to our events to execute
    cache = {},

    // Create a unique string to mark our elements with
    expando = String( Math.random() ).split( '.' )[ 1 ],

    // Global unique ID; we use this to keep track of what events to fire on what elements
    guid = 1,

    // The function to add or remove. We use this to handler all of other 
    handler = function ( event ) {

        // Grab the list of functions to fire
        var handlers = ( cache[ this[ expando ] ] && cache[ this[ expando ] ][ event.type ] ) || false;

        // Make sure the list of functions we have is valid
        if ( !handlers || !handlers.length ) {
            return;
        }

        // Iterate over our individual handlers and call them as we go. Make sure we remeber to pass in the event Object
        handlers.forEach( function ( handler ) {
            handler.call( this, event );
        });

    },

    // If we want to add an event to an element, we use this function
    add = function ( element, type, fn ) {

        // We test if an element already has a guid assigned
        if ( !element[ expando ] ) {
            element[ expando ] = guid++;
        }

        // Grab the guid number
        var id = element[ expando ];

        // Make sure the element exists in our global cache
        cache[ id ] = cache[ id ] || {};

        // Grab the Array that we are going to store our handles in
        var handlers = cache[id ][ type ] = cache[ id ][ type ] || [];

       // Make sure the handle that was passed in is actually a function
        if ( typeof fn === 'function' ) {
            handlers.push( fn );
        }

        // Bind our master handler function to the element
        element.addEventListener( type, handler, false );

    };

// Add a click event to the body element
add( document.body, 'click', function ( event ) {
    console.log( 1 );
});

这只是我之前写过的一个简化版本,但你希望能得到它的要点。

答案 3 :(得分:-1)

对于带有某些参数的“ addEventListener”,您可以使用以下代码:

{
   myButton.addEventListener("click",myFunction.bind(null,event,myParameter1,myParameter2)); 
}

函数'myFunction'应该是这样的:

{
   function myFunction(event, para1, para2){...}
}
相关问题