nfplee
nfplee

Reputation: 7977

jQuery Plugin - Passing Custom Events

I've built my own jQuery paging plugin. See below:

$.fn.extend({
    pager: function(options) {
        var settings = {
            pageSize: 10,
            onPageChanged: function() { }
        };

        if (options)
            $.extend(settings, options);

        return this.each(function() {
            // Trigger onPageChanged event
        });
    }
});

Which can be be called by saying:

$('#placeholder').pager({ pageSize: 20, onPageChanged: function() { alert('Page Changed!'); } });

I was wondering how to trigger the function passed in via the options within my plugin. I'm sure this is something simple but i can't seem to find anything in the documentation to help.

I'd appreciate the help. Thanks

Upvotes: 1

Views: 127

Answers (1)

Kevin B
Kevin B

Reputation: 95022

Try using:

settings.onPageChanged.call(this);

You can also optionally add additional arguments to .call() that will be passed to the function.

If you wanted a true custom event that could be bound to using $('#placeholder').on("onPageChanged",handler) later on, do this instead:

this.on("onPageChanged",settings.onPageChanged);

and then trigger it with:

this.triggerHandler("onPageChanged");

Upvotes: 1

Related Questions