How to fire functions outside the scope of the Plugin?

3

I'm making a plugin that at some stage runs 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 out of the scope of the plugin, 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, it says the function is undefined.

    
asked by anonymous 02.05.2016 / 19:50

2 answers

3

Without using the on method, assigning the event using attribute onclick of the 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><buttonclass="btn btn-warning btn-lg" id="act"> Action </button>
    
02.05.2016 / 20:39
2

Just use it as a callback. For this you should pass the function as a function in and not as a string, because 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><divid="teste"> </div>
    
02.05.2016 / 20:01