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 -
- my code gets a lot more complex and
- 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?