0

I've been trying to get my head around an approach to doing this for a while. Maybe I'm missing something.....

Say I have the plugin pattern:

(function($){

    $.fn.myPlugin = function(options){           
        
        var bindEvents = function(elem){

        // Bind the events here.
        // EDIT
        // My first first thought would be to pass the element to the method 
        // but what you are doing here is actually just bind the event to existing
        // elements and not allowing for ajax added events.
        $(document.body).on("click", $(elem), function(event){
         
           // Do your thang....
        });

        };

        return this.each(function(){

        bindEvents(this);

        });

    };

}(jQuery||_jQuery));

How do I go about binding the events I want to objects using the $.on() function so I can handle any dom element loaded via an Ajax request?

EDIT

To clarify what I mean by this I've added a few more comments to my code.

Community
  • 1
  • 1
James South
  • 10,147
  • 4
  • 59
  • 115
  • what have you tried... on() works the same in a plugin as it does elesewhere in your code – charlietfl Mar 06 '12 at 14:37
  • check out this question. it cleared up things for me: http://stackoverflow.com/questions/9473379/proper-use-of-on-method-in-jquery#comment11988859_9473379 – Rooster Mar 06 '12 at 14:44
  • how you handle events in the plugin also depends on objective of plugin... if plugin is adding the elements then binding is greatly simplified – charlietfl Mar 06 '12 at 14:46

1 Answers1

0

The best solution I can think of at the moment ....

(function($){

    $.myPlugin = function(selector, options){           

        var bindEvents = function(elem){

        // Bind the events here passing the selector.
           $(document.body).on("click", selector, function(event){

           // Do your thang....
        });

        };

        bindEvents(this);

        // Return the jQuery function to allow chaining;
        return $(this);

    };

}(jQuery||_jQuery));

This could then be called using:

$.myplugin(selector,options);
James South
  • 10,147
  • 4
  • 59
  • 115