5

I have a problem, I want to create a JavaScript class:

function Calculatore(txt,elements) {
    this.p= new Processor();
    this.output=txt;
    $(elements).click(this.clickHandler);   

}
Calculatore.prototype.clickHandler = function() {
var element=$(this);

// Code Here

// "this" contains the element.
// But what if I want to get the "output" var?
// I tried with Calculatore.prototype.output but no luck.

}

So how can I solve this?

2 Answers 2

3

You can use jQuery's $.proxy:

function Calculatore(txt,elements) {
    this.p= new Processor();
    this.output=txt;
    $(elements).click($.proxy(this.clickHandler, this));
}

Calculatore.prototype.clickHandler = function(event) {
    var clickedElement = event.target;
    alert(this.output);
}

Edited. Jason brought up a good point in the comments. It's probably better to use event.target which references only the element clicked, rather than elements which may reference an array of objects matching the selection.

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

3 Comments

or use event.target instead of saving the elements (event is the first parameter in the clickHandler)
Note that event.target (which is W3C spec) is not IE compatible - You'll have to check event.srcElement as well.
@MikeChristensen, since the OP is using jQuery, the check is handled by the library. So, event.target will work for all browsers. github.com/jquery/jquery/blob/master/src/event.js#L540
3

You have a collision between this values. You currently don't have access to the instance because this has been set to the element inside a click handler.

You could make a proxy function to pass both the this value (the element) and the instance:

function Calculatore(txt,elements) {
    this.p= new Processor();
    this.output=txt;
    var inst = this; // copy instance, available as 'this' here

    $(elements).click(function(e) {
        return inst.clickHandler.call(this, e, inst); // call clickHandler with
                                                      // 'this' value and 'e'
                                                      // passed, and send 'inst'
                                                      // (the instance) as well.
                                                      // Also return the return
                                                      // value
    });

}

Calculatore.prototype.clickHandler = function(e, inst) {
    var element = $(this);

    var output = inst.output;
};

Comments

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.