1

In the last line, how can I ensure that the "this" i'm referring to is the instantiated k8rModal object and NOT the object running the function?

For other items in the future I'll need to dynamically construct lambda functions as well. Is that possible WITHOUT a global variable?

function k8rModal(DOMnamespace){
    var _ = this._ = DOMnamespace+"_"; // for DOM namespacing

    this.tightWrap=1;

    $('body').prepend('<div id="'+_+'stage"></div>');
    this.stage = stage = $('#'+_+'stage');
    stage.css({
        'display':'none',
        'width':'100%',
        'height':'100%',
        'color':'#333'
    });

    $('body').append('<div id="'+_+'slate"></div>');
    this.slate = slate = $('#'+_+'slate');
    slate.css({
        'display':'none',
        'width':'640px',
        'height':'480px',
        'color':'#eee'
    });

    $('body').delegate('.'+_+'caller','click',function(){
        /* this... but not, this? */.appear();
    });
}

k8rModal.prototype.appear = function(){
    //make the modal box appear
}
1
  • 6
    Instead of using this everywhere, just use var that = this; at the top of your function and use that from then on. So then in other scopes, they can still use their own this but still reference the higher this as that. Commented Oct 28, 2012 at 21:50

1 Answer 1

1

While you could use variable reference to refer to the proper object as @ianpgall suggested, another possibility is to use jQuery's event data for this purpose.

$('body').delegate('.'+_+'caller','click', {k8r: this}, function(event){
    event.data.k8r.appear();
});

Or if you're using jQuery 1.7 or later, you should probably be using .on() instead.j

$('body').on('click', '.'+_+'caller', {k8r: this}, function(event){
    event.data.k8r.appear();
});

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

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.