Hilmi
Hilmi

Reputation: 3439

Closure Variable is not assigned

Simply i have the following:

jQuery.fn.X = function(){
    var elements = jQuery(this);
    elements.click(function(){
        var self = jQuery(this);
        //elements here is not defined why?
    });

why elements is not defined at the on click function while it should take it as a closure variable ?

Upvotes: 0

Views: 89

Answers (1)

Tomalak
Tomalak

Reputation: 338158

This is the correct approach to creating a jQuery plugin.

jQuery.fn.X = function () {
    // here, "this" will be a jQuery object containing all elements you matched
    // with X(). You must return that object.
    return this.click(function () {
        // here, "this" will be a DOM element. You don't have to return it.
        var self = jQuery(this);
        // ...
    });
});

You must return jQuery in order to keep the method chaining working.

Upvotes: 3

Related Questions