Alexandre
Alexandre

Reputation: 759

Externally call function inside this.each(function(){}) from a jquery plugin

(function( $ ){

$.fn.foo = function(params) {

    params = $.extend( {
        on: false
    }, params);

    this.each(function(){
        if(params.on) {
            function alertDate(){
                alert('FOO BAR!!!');
            }
        }
    });
};
})( jQuery );

How can i access the "alertDate()" function from out of the script?

if i use:

$('#test').foo()

will give-me access for the function, ok, everything fine, i will gain access to function "alertDate()" internally at this.each(function(){}).

I want to access the function "alertDate()" externally by something like:

$('#text').foo({on: 'true'}).each().alertDate();

How can i do this?

Thanks in advance and sorry for the poor english

Upvotes: 3

Views: 1558

Answers (2)

Wally Lawless
Wally Lawless

Reputation: 7557

Here's how I would handle it, so that your alertDate() function can be used both internally and externally:

$.fn.foo = function(params) {
    params = $.extend( {
        on: false
    }, params);

    this.alertDate = function(){
        alert("FOO BAR!!!");
    }

    this.each(function(){
        if(params.on) {
            this.alertDate();
        }
    });

    return this; 
};

//Externally the alertDate function could be called as:
$("test").foo().alertDate();

Upvotes: 2

epascarello
epascarello

Reputation: 207511

You can do something like this, but this is not how plugins normally work.

$.fn.foo = function() {
    function bar() { 
        alert("bar");
    } 
    this.bar = bar; 
    return this; 
};

$("a").foo().bar();

Upvotes: 0

Related Questions