Keysle
Keysle

Reputation: 77

How can I pass a variable into a lambda function? Dynamic Lambda functions

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
}

Upvotes: 1

Views: 719

Answers (1)

I Hate Lazy
I Hate Lazy

Reputation: 48771

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();
});

Upvotes: 1

Related Questions