0

My plugin creates links that then invoke functions of the plugin itself. I could directly manipulate DOM and use something like $link.click(function() {...}), but I do not want to use this approach, because -

  1. my code gets a lot more complex and
  2. string manipulation is faster

How can I invoke a function of the plugin via a string link?

The problem is finding the actual DOM element, on which the plugin was created. I cannot just use/set the HTML id, as it might be used by the page for some other purpose or might not be unique. I came up with the idea to add a unique class to find the plugin later:

 // init function of plugin
 init : function( options ) {
     return this.each(function () {
        var data = $this.data("myPlugin");
        if (!data) {
          data.uniqueClass = 'p' + new Date().getTime() + '_' + Math.random().toString().substring(2);
          $this.addClass(data.uniqueClass);  
          this.data('myPlugin', data);
          // generate link
          $this.html('<a onclick="jQuery(\'.' + data.uniqueClass + '\').myPlugin(\'func\');">Do func</a>');
        }   
     });
 }

 // function that i want to call of my plugin
 func : function() { 
    return this.each(function () {
       // do stuff
    });
 }

But is there a nicer way to do this?

Community
  • 1
  • 1
Flo
  • 1,469
  • 1
  • 18
  • 27

1 Answers1

0

Don't do this. The added performance you'd get is negligible.

I'm not posting this as a comment because this should be the answer. Don't do it!!.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292