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
.