locked
removing an event

    Question

  • Hi There!

    first, add event listener..

     just like >>>>>> document.addEventListener('MSPointerDown', this.handler_down);

    and i will remove event listener..

    >>>>>> document.removeEventListener('MSPointerDown', this.handler_down);

    it's work well....but

    >>>>>> document.addEventListener('MSPointerDown', this.handler_down.bind(this) );     // i just added the binding context at the end of the code...

    above event listener is can't remove....

    How can I remove such an event listenenr?

    Thank you.


    Thursday, August 09, 2012 8:46 AM

Answers

  • Hello,

    You need to store the result of your call to `bind` in order to remove it later.  If you read the documentation for `bind` (http://msdn.microsoft.com/en-us/library/ff841995(v=VS.94).aspx), you will see that it returns a new function.  You need will need the reference to that new function.  For example, you could do something like this:

    var newHandler = this.handler_down.bind(this);
    document.addEventListener('MSPointerDown', newHandler);
    
    // ... Other code ...
    
    document.removeEventListener('MSPointerDown', newHandler);

    • Proposed as answer by soxley Thursday, August 09, 2012 12:08 PM
    • Marked as answer by pavane1 Thursday, August 09, 2012 3:06 PM
    Thursday, August 09, 2012 12:07 PM

All replies

  • Hello,

    You need to store the result of your call to `bind` in order to remove it later.  If you read the documentation for `bind` (http://msdn.microsoft.com/en-us/library/ff841995(v=VS.94).aspx), you will see that it returns a new function.  You need will need the reference to that new function.  For example, you could do something like this:

    var newHandler = this.handler_down.bind(this);
    document.addEventListener('MSPointerDown', newHandler);
    
    // ... Other code ...
    
    document.removeEventListener('MSPointerDown', newHandler);

    • Proposed as answer by soxley Thursday, August 09, 2012 12:08 PM
    • Marked as answer by pavane1 Thursday, August 09, 2012 3:06 PM
    Thursday, August 09, 2012 12:07 PM
  • Cool, thanks Soxley!  

    I did't know The bind method return a new function.


    • Edited by pavane1 Friday, August 10, 2012 1:22 AM
    Friday, August 10, 2012 1:21 AM
  • Cool, thanks Soxley!  

    I did't know The bind method return a new function.


    You're welcome!  And indeed it does.

    The `bind` implementation basically does this:

    Function.prototype.bind = function (context) {
        var self = this;
        return function () {
            self.apply(context, arguments);
        };
    };

    In other words, this:

    var newHandler = this.handler_down.bind(this);

    should be equivalent to this:

    var self = this, newHandler = function () { self.handler_down.apply(self, arguments); }; // Following code does not change the value of self

    Friday, August 10, 2012 3:00 PM