Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 607
Alexandre Avatar asked Sep 11 '26 05:09

Alexandre


1 Answers

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();
like image 187
Wally Lawless Avatar answered Sep 13 '26 17:09

Wally Lawless



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!