JQuery plugin callback

ok so what I'm trying to do is a plugin that returns a jquery array to be used in the callback function.

let's say I have this code,

(function($){
$.fn.extend({
    //plugin name
    myPlugin : function(needed){

        var defaults = {
            path : 'action.php',
            source : '' 
        }
        var needed = $.extend(defaults,needed);

        //return
        return this.each(function(){
            //it loads some pictures
            $('#selector').load(needed.path,{'src':nedeed.source})

        });
    }
});

      

}) (Jquery);

I want to return these photos and access them in a callback function. something like that

$('#another_selector').click(function(){
         $(this).myPlugin({'source':'path/...etc'},function(){
                 $('img').click(function(){
                       $(this).remove();
}); 
});
    });

      

thank

+2


source to share


2 answers


(function($){
    $.fn.extend({
    //plugin name
    myPlugin : function(needed,callback){

            var defaults = {
                    path : 'action.php',
                    source : '' 
            }
            var needed = $.extend(defaults,needed);

            //return
            return this.each(function(){
                    //it loads some pictures
                    $('#selector').load(needed.path,{'src':nedeed.source},callback)

            });
    }
});

      

and when you call the plugin, I call it like this:



$('#another_selector').click(function(){
     $(this).myPlugin({'source':'path/...etc'},function(){
             $('img').click(function(){
                   $(this).remove();
 }); 
 });
  });

      

this function after options represents a callback

+1


source


I can see what you are trying to do. If that's all you are doing, you can simply add an event listener to your plugin live

.

Try the following:



(function($){
    $.fn.extend({
        //plugin name
        myPlugin : function(needed){
                // New
                $('img').live('click',function() {
                    $(this).remove();
                });
                // end new
                var defaults = {
                        path : 'action.php',
                        source : '' 
                }
                var needed = $.extend(defaults,needed);

                //return
                return this.each(function(){
                        //it loads some pictures
                        $('#selector').load(needed.path,{'src':nedeed.source})

                });
        }
    });
})(jQuery);

      

With this technology, all img, no matter when they are added to the DOM, will be hidden when clicked. This is ... after the plugin is called, of course.

0


source







All Articles