Global function for plugin

4

I am creating a simple plugin with jQuery and Bootstrap, and in my JavaScript I have the following excerpt:

$.fn.myPlugin = function(options) {
   var element = this;

   var settings = $.extend({
       param1: null,
       param2: null,
       minhaLabel1: $.fn.myPlugin.defaults.translate_MINHA_LABEL_1,
       // Sequência de parâmetros
   }, options);

   // Funções de validação
   // ...

   // Eventos
   // ...

   // Funções privadas
   // ...

   // Funções Públicas
   element.clearAll = function (){
       console.debug('Elemento para ser limpo:', $(this));
       // ...
   };
   // ...

   // Start do Plugin
   // ... 

};

$fn.myPlugin.defaults = {
   translate_MINHA_LABEL_1: 'Minha Label 1',
   // ...
}


By using the plugin everything has worked well.

$('#minhaDiv').myPlugin({
   param1: 'alguma_coisa',
   param2: 'outra_coisa',
   // ...
});


I like to set all the translations in the _Layout page, so I created the property defaults in myPlugin , and everything has worked well!

$.fn.myPlugin.defaults.translate_MINHA_LABEL_1 = '@Html.Raw(RESOURCES.LABEL_1)';


Now I would like to call the clearAll function for elements that have instantiated myPlugin of any other .js .

Imagine the following excerpt:

Obs: I enter a new class for each element that calls myPlugin .

$(".myPlugin").each(function(){
   $(this).clearAll();
});

Well, in that case I have an error, as if clearAll had not been set.

Then I added the following excerpt below my public function clearAll in the myPlugin file:

element.data({ clearAll: element.clearAll});

Now I can execute the function as follows:

$(".myPlugin").each(function(){
   $(this).data('clearAll')();
});


  

Even though it worked correctly, I found it a bit ugly. And I would like   of an approach such as:

$(this).myPlugin.clearAll();

I then tried to do the way I'm using the resources:

$.fn.myPlugin.clearAll= function () {
    $(this).data('clearAll')();
};

But every time I call the above excerpt, the plugin runs as if I wanted to create a new myPlugin .

    
asked by anonymous 29.12.2016 / 13:53

3 answers

1

It may not be pretty as you wish, but one approach to working with public methods would be:

(function($){
$.fn.meuPlugin = function(opcoes) {
    // variáveis privadas
    var punzim = '';
    
    // métodos privados   
    var punzaum = function() {
        //...
    }
    
    // métodos públicos       
    this.flatus = function() {
        //...
        return this;
    };

    this.pum = function() {
        alert("Pum!");
    };
    
    return this.flatus();
}
})(jQuery);

var meuPlugin = $('#metano').meuPlugin();

$(".peristaltar").on("click", function(){
	meuPlugin.pum();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="metano">
  <a href="" class="peristaltar">Executar Pum</a>
</div>
    
29.12.2016 / 14:42
1

Here's a suggestion:

I found a generic way of doing this, it works very simply:

In the myPlugin function you use the pure element and define a property called "myPluggin-attached" with value true :

$.fn.myPlugin = function(params) {

  // .. código

  this.get(0)['myPluggin-attached'] = true;
};

In the clearAll function, it checks whether the applied element has the property defined in "myPlugin" with value true :

$.fn.clearAll = function(param) {
    if(this.get(0)['myPluggin-attatched'] == true){
        // ..código

    }
};

Demo

Using .myPlugin before:

var myPlugin = function(params) {
  var elementMasterValue = $(this).data('teste');
  console.log('Teste myPlugin', elementMasterValue);
  this.get(0)['myPluggin-attatched'] = true;
};

$.fn.myPlugin = myPlugin;
$.fn.clearAll = function(param) {
	if(this.get(0)['myPluggin-attatched'] == true){
    var elementValue = $(this).data('teste');
    console.log('Teste clearAll:', elementValue);
  }
};


// Instanciando plugin
$(".myPlugin").each(function() {
  $(this).myPlugin();
});

// Testando limpeza
$(".myPlugin").each(function() {
  $(this).clearAll();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="myPlugin" data-teste="1"></div>
<div class="myPlugin" data-teste="2"></div>

Not using .myPlugin before:

var myPlugin = function(params) {
  var elementMasterValue = $(this).data('teste');
  console.log('Teste myPlugin', elementMasterValue);
  this.get(0)['myPluggin-attatched'] = true;
};

$.fn.myPlugin = myPlugin;
$.fn.clearAll = function(param) {
	if(this.get(0)['myPluggin-attatched'] == true){
    var elementValue = $(this).data('teste');
    console.log('Teste clearAll:', elementValue);
  }
};

/*
// Instanciando plugin
$(".myPlugin").each(function() {
  $(this).myPlugin();
});
*/
// Testando limpeza
$(".myPlugin").each(function() {
  $(this).clearAll(); // Nada é logado
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="myPlugin" data-teste="1"></div>
<div class="myPlugin" data-teste="2"></div>
    
29.12.2016 / 14:50
1

This would be kind of wrong in the context of the selected element, so:

$.fn.myPlugin.clearAll= function () {
    $(this).data('clearAll')();
};

You will be selecting the function and not the context of the object, to select the most appropriate context would be to make a return , thus:

$("seletor").myPlugin().clearAll();

Or so:

var selecioandos1 = $("seletor 1").myPlugin();
var selecioandos2 = $("seletor 2").myPlugin();

$("a.removetodos").click(function() {
     selecioandos1.clearAll();
     selecioandos2.clearAll();
});

The function would be:

$.fn.myPlugin = function(options) {
   var element = this;

   var settings = $.extend({
       param1: null,
       param2: null,
       minhaLabel1: $.fn.myPlugin.defaults.translate_MINHA_LABEL_1,
       // Sequência de parâmetros
   }, options);

   return {
       "clearAll": function() {
             $(element).each(function() {
                  //Ação para cada elemento selecionado
             });
        }
   }
};
  

All plugins I've used use something similar when having a remove method

Note also that it may even be possible to use .myPlugin.clearAll without passing the object, but you will be limited to the last selected element (of the previous call), ie there will be no new call $("selector"). , which can cause several inconsistencies.

Another suggestion that I believe to be cleaner would be:

$.fn.myPlugin = function(type, params) {
    switch(type) {
        case "create":
            $(this).each(function() {
                var elementMasterValue = $(this).data('teste');
                console.debug('Teste myPlugin', elementMasterValue);
            });
        break;
        case "clear":
            $(this).each(function() {
                var elementMasterValue = $(this).data('teste');
                console.debug('Teste clear', elementMasterValue);
            });
        break;
    }
};

// Instanciando plugin
$(".myPlugin").myPlugin("create", {});


// Testando limpeza
$(".myPlugin").myPlugin("clear");

Note that I put .each inside the function, so you can use:

 $(".seletor").myPlugin();

E:

 $(this).myPlugin();
    
29.12.2016 / 20:36