Referencing a parent object in callback fuctions with jQuery
<p>I've a page that is generated dynamically, and that includes  certain number (user-dynamically-defined) of advanced scatter plot charts. I intend to create a javascript object which defines the scatter plot itself, i.e. which takes some parameters, some data, and some container ID, and which will create the various elements needed to obtain the visualisation: canvas elements, toolbar, etc.. To do so, I started with the following (simplified) class:</p>

<pre><code>(function () {
    if (!this.namespace) { this.namespace = {};}

    this._instances = { index: 0 };

    this.namespace.ScatterPlot = function (containerId, file, options) {
        _instances.index ++;
        this.id          = this.containerId+"-"+_instances.index ;
        this.containerId = containerId ;
        _instances [this.id] = this;

        // ... Do stuffs with file and options ...

        // Initialize elements once the DOM is ready
        $(this.updateDOM);
    }

    namespace.ScatterPlot.prototype = {
        updateDOM: function() {
            $("&lt;canvas&gt;")
                .click(clickCallback)
                .appendTo("#"+this.containerId);
            //(...)
        },

        clickCallback: function() {
            alert("Some click: "+this.id);
        }
    }


})();
</code></pre>

<p>Each object can be created with:</p>

<pre><code>var v1 = new namespace.ScatterPlot("container1", "foo", "foo");
var v2 = new namespace.ScatterPlot("container2", "foo", "foo");
</code></pre>

<p>There are two problems here: (1) in updateDOM, 'this' does not make reference to my initial ScatterPlot object, which means that this example will never work, and (2) similarly, the clickCallback will not be able reference the scatterplot with 'this' either. </p>

<p>I'm new to javascript, and I'm still struggeling to understand the logic of OO programming in javascript, so <strong>the question is</strong>: I'm I taking the wrong direction here ? After some digging, I could roughly achieve what I wanted by passing this to updateDOM:</p>

<pre><code>$(this.updateDOM(this)); // This blows my eyes but does the trick, at least partially

updateDOM: function(that) {
    $("&lt;canvas&gt;")
        .click(that.clickCallback)
        .appendTo("#"+that.containerId);
    //(...)
},

clickCallback: function() {
    // Not working either... Shoudl pass 'that' to the function too
    alert("Some click: "+this.id);
}
</code></pre>

<p>But I dont feel this patters to be very elegant... And the problem is not fixed either regarding the click callback.</p>

<p>Thoughts ?</p>

<p>Thanks in advance :)</p>
