3
I am making a plugin that at a certain stage performs a function.
Example:
<button class="btn btn-warning btn-lg" id="act"> Action </button>
(function($) {
$.fn.foo = function(options) {
var opts = $.extend({}, $.fn.foo.defaults, options);
this.init = function() {
this.css('background', opts.background);
this.on(opts.action[0],opts.action[1]);
};
this.init();
return this;
};
$.fn.foo.defaults = {
action: ["click", "bar()"],
background: "black"
};
}(jQuery));
function bar() {
console.log('hello,world');
}
$("#act").foo();
I want to run a function force of the plugin scope, an example and if I declare $("#act").foo({action:["dblclick","bar()"]});
, how can I run it inside my plugin? I tried this using the new Function(opts.action[1]) too, says that the function is undefined.
+1, Com attr é legal did not know :) I think this is the coolest way to do it: https://jsfiddle.net/gabrielr47/sw1d41j6/
– Gabriel Rodrigues
Yes, the difference is that instead of using the jQuery("click") event name, you use the input attribute name. With
attr
you can set any property of the element.– Laerte