views:

24

answers:

1

I have some sample code that looks like this:

var myDrawingArea = new DrawingArea(document.getElementById("drawing_canvas"));

function DrawingArea(aCanvas) {
    this.brushSize = 2;

    this.buildToolbar = (function () {
         $("#brush-size")
            .slider({
                value: this.brushSize, // this is DrawingArea instance
                slide: function (event, ui) {
                     //*************** PROBLEM ***************
                     // this is referring to the slider DOM element not my DrawingArea instance
                     // how can I access both the outer "this" and the inner one?
                     this.brushSize =  ui.value;
                     $(this).find(".ui-slider-handle").text(this.brushSize);
                }
            })
            .find(".ui-slider-handle").text(this.brushSize);
    });
}

As it says in the comment "how can I access both the outer "this" and the inner one?"

A: 

You can store a reference to it, like this:

function DrawingArea(aCanvas) {
    var self = this;
    self.brushSize = 2;    
    self.buildToolbar = (function () {
         $("#brush-size")
            .slider({
                value: self.brushSize,
                slide: function (event, ui) {
                     self.brushSize = ui.value;
                     $(this).find(".ui-slider-handle").text(self.brushSize);
                }
            })
            .find(".ui-slider-handle").text(this.brushSize);
    });
}

You could use this or self outside the slide callback, but I think it's clearer to be consistent.

Nick Craver
Thank you that idea improved my code quality by about 20%. I am not sure why I could not find such an answer when I searched on prior questions.
Geordie Korper
@Geordie - Welcome :) Did that resolve your issue?
Nick Craver