Kieran Hall
Kieran Hall

Reputation: 2627

JQuery Widget Events in Object Orientated Javascript

I'm attempting to write a custom widget and I want to use existing UI widgets within the class that I'm writing. The problem is that when an event fires the class method that is invoked seems out of scope from the rest of the class, as any members I attempt to read are undefined. Here is the code:

<script type="text/javascript">
MyClass = function()
{
    this.init();
}

$.extend(MyClass.prototype, 
    {   
        init: function()
        {
            this.field = 'Hello world.';

            /* Let's try using a slider. */
            this.slider = $("#slider");

            this.slider.slider(
                {
                    change: this.callback,
                    min: 270,
                    max: 800,
                    slide: this.callback
                }
            );
        },

        callback: function()
        {
            alert(this.field);
        }
    }
);
</script>

<div id="slider"></div>
<script type="text/javascript">
var myClass = new MyClass();
</script>

This is a simplification of the problem, and I have tried a few methods to get around this, such as using bind instead of the callback notation:

this.slider.bind('slidechange', this.callback(this));
this.slider.bind('slide', this.callback(this));

However, this just leads to the call back being invoked despite the event occuring.

Thanks.

Upvotes: 2

Views: 1158

Answers (1)

Jonathan Fingland
Jonathan Fingland

Reputation: 57157

See http://www.alistapart.com/articles/getoutbindingsituations/ for methods on binding this, using closures

EDIT: As a concrete example of how this can be achieved...

$.extend(MyClass.prototype, 
{   
    init: function()
    {
        this.field = 'Hello world.';

        /* Let's try using a slider. */
        this.slider = $("#slider");

        this.slider.slider(
            {
                change: this.callback(this),
                min: 270,
                max: 800,
                slide: this.callback(this)
            }
        );
    },

    callback: function(that)
    {
        return function() {
            alert(that.field);
        }
    }
}
);

Upvotes: 3

Related Questions