开发者

JQuery Reference object instance when bind on dynamically created element i.e. Custom Control

开发者 https://www.devze.com 2023-03-21 16:27 出处:网络
I\'m implementing a client-side \'custom control\' but I\'m struggling to get a reference to the the object that created the control in my event handlers. Its best explained with some boiled down code

I'm implementing a client-side 'custom control' but I'm struggling to get a reference to the the object that created the control in my event handlers. Its best explained with some boiled down code;

    function myControl(text) {
        this.Text = text;
        this.DoAlert = function (e) { alert(e.Text); };
        this.Create = function (container) {
            var btn = $('<BUTTON/>');
            btn.html('Click Me');

            container.append(btn);

            btn.bind('click', this, this.DoAlert);
        }
    }

    $(document).ready(function () {
        var control1 = new myControl('Button 1');
        control1.Create($('#container'));

        var开发者_JAVA百科 control1 = new myControl('Button 2');
        control1.Create($('#container'));

    });

As you can see, I'm creating two instances of myControl initialised with different strings, inside DoAlert, how do I get the reference the object that created the button, so that I can get to its properties?

Is this an acceptable approach for Javascript/ jQuery or should I be doing something else?


You have various options:

1) You could include this inside the closure around the event handler:

function MyControl() {
    var _this = this;
    this.DoAlert = function(e) { alert(_this.Text); };
    // ...
}

The variable _this will be bound to this even inside the function DoAlert.

2) You use $.proxy (ref http://api.jquery.com/jQuery.proxy/):

function MyControl() {
    // ...
        btn.bind('click', $.proxy(this.DoAlert, this));
    // ...
}

3) Use the event data properly (ref: http://api.jquery.com/bind/)

function MyControl() {
    this.DoAlert = function(e) { alert(e.data.Text); }
    // ...
}

I would personally recommend 2) because it is very transparent (this in the constructor is the same as this in the event handler).

0

精彩评论

暂无评论...
验证码 换一张
取 消