tags:

views:

401

answers:

1

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.

+2  A: 

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);
        }
    }
}
);
Jonathan Fingland
Thanks for the example Johathan, this works.Artem, I'm not following the callback().apply(this) approach. Where do I need to do what you're suggesting?
Kieran Hall