How to trigger functions outside the scope of the Plugin?

Asked

Viewed 72 times

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.

2 answers

3


Without using the method on, assigning the event using attribute onclick of input.

(function($) {
  $.fn.foo = function(options) {
    var opts = $.extend({}, $.fn.foo.defaults, options);

    this.init = function() {
      this.css('background', opts.background);
      this.attr(opts.action[0],opts.action[1]);
    };
    this.init();
    return this;
  };


  $.fn.foo.defaults = {
    action: ["onclick", "bar()"],
    background: "#ccc"
  };

}(jQuery));

function bar() {
  alert("Hello world")
}

$("#act").foo();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-warning btn-lg" id="act"> Action </button>

  • 1

    +1, Com attr é legal did not know :) I think this is the coolest way to do it: https://jsfiddle.net/gabrielr47/sw1d41j6/

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

2

Just use it as a callback. For this you must pass the function as function itself and not as string, because maybe it may not be known within the scope of your plugin.

Exemplifying:

$.fn.foo = function(callback){ 
  $(this).html(callback()); //uso o retorno do callback aqui...
  console.log(callback()); //...e aqui também
}

function bar(){ //Aqui defino da função bar
  return "Hello, world";
}

$("#teste").foo(bar); //Aqui passo a função bar como um callback
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="teste"> </div>

  • @Gabrielrodrigues The logic would be the same, passing the event as string and the function as callback. Look at the modified example in this fiddle: https://jsfiddle.net/1m4yhqv/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.