James Kyle
James Kyle

Reputation: 4178

How to use a jQuery Plugin Parameter Variable

I'm attempting to build a fairly basic jQuery plugin (mostly for learning reasons) and I haven't had an error until I added the limit method, which seems pretty straight forward, however I get the following error in the console

Uncaught ReferenceError: limit is not defined

It's applying to the second if method below (marked with comment)

$.fn.query = function(params) {

    // Parameters //
    var options = $.extend({
        'shuffle' : false,
          'limit' : undefined
    }, params),
        output = this;

    // Shuffle //
    if (shuffle) {
        output = shuffle(this);
    }

    // Limit // !!!ERROR!!! //
    if (limit !== undefined) {
        output = output.slice(0, limit);
    }

    return output;
};

Then running the plugin

var query = $(example).query({
    shuffle: true,
    limit: 5
});

I was trying to follow all of the best practices but if you notice anything odd at all please let me know.

Here is a jsFiddle with all of the code, you can see the error in the console.

http://jsfiddle.net/JamesKyle/CfXhw/

Upvotes: 0

Views: 436

Answers (1)

Simon
Simon

Reputation: 1201

Add options. in front of limit.

options.limit

http://jsfiddle.net/JamesKyle/UWDsz/

You're creating an object, so in order to access it you use the object and variable name split by a period object.variable

Corrected jQuery code:

$.fn.query = function(params) {

    // Parameters //
    var options = $.extend({
        'shuffle' : false,
          'limit' : undefined
    }, params),
        output = this;

    // Shuffle //
    if (options.shuffle) {
        output = shuffle(this);
    }

    // Limit // !!!ERROR!!! //
    if (options.limit !== undefined) {
        output = output.slice(0, options.limit);
    }

    return output;
};

Upvotes: 4

Related Questions