0

I have a JavaScript class like this

function Palette() {

  this.selectedItem = "";

  this.addBox = function() {
    // Different approach, create a fake box
    b = $("<div id='box-palette' class='box'>Box</div>");
    b.insertBefore('#cont');

    b.mousedown(function() {
        this.selectedItem = "box"; // Here I want to access Palette#selectedItem
        console.log(Palette);
    });
  }
}

How can I access the property of the class in the function I want to pass to jQuery?

Any help will be appreciated. Thanks!

1

1 Answer 1

2

Since it is tagged with jQuery use $.proxy() to pass the parent context to the callback method

function Palette() {

    this.selectedItem = "";

    this.addBox = function () {
        // Different approach, create a fake box
        b = $("<div id='box-palette' class='box'>Box</div>");
        b.insertBefore('#cont');

        b.mousedown($.proxy(function () {
            this.selectedItem = "box"; // Here I want to access Palette#selectedItem
            console.log(Palette);
        }, this));
    }
}

Note: bind() was not used because of lack IE<9 support

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, it would be great if you could let me know the use of bind() in this context also. I am accepting the answer, thanks!
@jaibatrik both are used to pass a custom context to a function... bind() is a native extension to Function.prototype - but it is supported only in newer versions of browsers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.