Javascript get reference to parent object/class from event handler

前端 未结 4 842
慢半拍i
慢半拍i 2020-12-16 19:36

I have a class (or function-containing object; I\'ve heard that there is no such thing as a Javascript class) called Foo, with an event handler that is attached to a click e

相关标签:
4条回答
  • 2020-12-16 19:58
    function Foo() {
        var _self = this;
        this.num=0;
    
        $('element').click(this.eventHandler);// jQuery to attach an onclick event to my element.
    
        this.eventHandler=function() {
            _self.num++;
        }
    }
    

    use a reference _self = this defined in the outer scope

    0 讨论(0)
  • 2020-12-16 20:01
    function Foo() {
       this.num=0;
       $(document).on('click', 'element', this, this.eventHandler);
       this.eventHandler=function(e) {
          var _this = e.data; 
          _this.num++;
       }
    }
    

    1) Use JQuery on() method to attach event listeners. 2) Use a reference _this for accessing parent class.

    0 讨论(0)
  • 2020-12-16 20:05

    You can store a reference to this in the constructor that you can access in your event handler.

    function Foo() {
    
        this.num=0;
        $('element').click(this.eventHandler);// jQuery to attach an onclick event to my element.
    
        var that = this;
        this.eventHandler=function() {
            that.num++;// This doesn't work.
        }
    }
    
    0 讨论(0)
  • 2020-12-16 20:08

    You need to bind the function's context; otherwise this will be the global object:

    $('element').click($.proxy(this.eventHandler, this));
    

    In a modern browser you can also use Function.prototype.bind:

    $('element').click(this.eventHandler.bind(this))
    
    0 讨论(0)
提交回复
热议问题