4
I’m creating a plugin simple 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',
// ...
}
When using the plugin everything has worked well.
$('#minhaDiv').myPlugin({
param1: 'alguma_coisa',
param2: 'outra_coisa',
// ...
});
I like to set all the translations on the page of _Layout
, 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’d like to call the function clearAll
for elements that have already instantiated myPlugin
of any other file .js
.
Imagine the following passage:
Obs: I enter a new class for each calling element myPlugin
.
$(".myPlugin").each(function(){
$(this).clearAll();
});
Well, in that case I have a mistake, as if clearAll
had not been defined.
Then I added the following excerpt below my civil service clearAll
in the file of myPlugin
:
element.data({ clearAll: element.clearAll});
Now I can perform the function as follows:
$(".myPlugin").each(function(){
$(this).data('clearAll')();
});
Even though it worked properly, I found it a little ugly. And I would like of an approach such as:
$(this).myPlugin.clearAll();
I then tried to do the way I am using Resources:
$.fn.myPlugin.clearAll= function () {
$(this).data('clearAll')();
};
But every time I call the above snippet, the plugin runs as if I wanted to create a new one myPlugin
.
element variable is private brother...
– petersonfortes
Thank you very much! but even with the change to a global context, I can’t use a more "beautiful syntax".
– Jedaias Rodrigues
Something similar here: http://answall.com/questions/100091/accessmodifiers-em-javascript/101754#101754
– petersonfortes
In the "plugin start" part, you are returning . each(...)? You need to.
– bfavaretto