开发者

Javascript and jQuery getting the right this

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;
       开发者_StackOverflow中文版              $(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?"


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜