Jump to content

Jquery Plugin Design - Using this / $this ???


GregL83

Recommended Posts

I'm trying to access 'this' from a jquery plugin method that has been called as a result of an event.  'this' becomes the element/object that fired the event instead of the original 'this' object that the plugin was applied on.  The reason is because my init function stores data using the jquery.data() method and I want to nicely retrieve some of that data from inside the event method as a standard OOP language would allow.

 

(function( $ ){

  var methods = {
     init : function( options ) {

       return this.each(function(){
         $("#example").bind('click.name', methods.doSomething);
       });

     },
     destroy : function( ) {

       return this.each(function(){
         $(window).unbind('.tooltip');
       })

     },
     doSomething : function( ) {
       // I WANT TO ACCESS 'THIS' HERE HOWEVER, 'THIS' NOW REFERS TO THE ELEMENT/OBJECT FROM THE ONCLICK EVENT (#example)
       // BEFORE THIS WOULD REFERENCE THE ENTIRE OBJECT WHERE THE .data() FUNCTION COULD BE USED
       // ITS MY UNDERSTANDING YOU CAN DO THIS WITHOUT PASSING THE OBJECT...  HOW???
       // THANKS
     },
  };

  $.fn.tooltip = function( method ) {
    
    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    
  
  };

})( jQuery );

 

Thanks in advance!

Link to comment
https://forums.phpfreaks.com/topic/225217-jquery-plugin-design-using-this-this/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.