webdevRefinery Forum: jquery - Using $(this) inside custom jquery plugin options - webdevRefinery Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Rate Topic: -----

User is offline Maciek 

  • Group: Members
  • Posts: 2
  • Joined: 07-January 12
  • LocationPszczyna, Poland
  • Expertise:HTML,CSS,PHP,Javascript

Posted 04 May 2012 - 01:07 PM (#1)

jquery - Using $(this) inside custom jquery plugin options


Hi,

I am writting custom jquery plugin and I wonder If there is a possibilty to use $(this) selector inside custom jquery pugin options. For example:

$("#myDiv").customPlugin({
  fisrtProperty: $(this).attr('id'), //I want "$(this)" points to the "$('#myDiv')" 
  myCallback: function() {
    alert($(this).attr('id')); //inside callback $(this) works fine because I pass it in call function
  }
});


My test plugin:
;(function($) {
   
  var pluginName = "customPlugin"; //to easy renaming
  
  var defaults = {
    firstProperty: null,
    myCallback: null
  }
  
  var Plugin = function(element, options) {
    var $elem = $(element),
    obj = this, //plugin object
    settings = $.extend({}, defaults, options);
  
    $elem.click(function() {
      if ($.isFunction(settings.myCallback)) {
        settings.myCallback.call($(this)); //very important to pass $(this)
      }
      $(this).append(settings.firstProperty);
    });
  }
  
  $.fn[pluginName] = function(options) {
    return this.each(function() {  //to preserve chaining
    var element = $(this);
      if (element.data(pluginName)) {
        return; //quick ends if element stores data of pluginname
      }
      var plugin = new Plugin(this, options);
      //stores plugin object in this element's data object
      element.data(pluginName, plugin);
    });
  }
})(jQuery);

0


User is online callumacrae 

  • {{ post.author }}
  • Group: Members
  • Posts: 2862
  • Joined: 20-January 11
  • LocationWarwickshire, England
  • Expertise:HTML,CSS,PHP,Javascript,Node.js,SQL

Posted 04 May 2012 - 01:12 PM (#2)

Nope, it isn't possible there as you're not controlling the scope.
Front-end developer and writer
Twitter | GitHub | phpBB Contributor and Website Team Member | lynxphp
1


User is offline Maciek 

  • Group: Members
  • Posts: 2
  • Joined: 07-January 12
  • LocationPszczyna, Poland
  • Expertise:HTML,CSS,PHP,Javascript

Posted 04 May 2012 - 01:23 PM (#3)

View Postcallumacrae, on 04 May 2012 - 01:12 PM, said:

Nope, it isn't possible there as you're not controlling the scope.


Ok thanks for quick reply. That's what I thought, but I wasn't sure 100%.
0


Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Enter your sign in name and password


Sign in options
  Or sign in with these services