Jump to content

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


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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.