0
All modal windows of my system open via ajax and these have their own JS codes with variables and functions. In order to avoid problems with the variables and functions of the screens that call these modals, I thought to adopt the following strategy in the modal JS:
HTML
<button id="btn">
Valor
</button>
<button id="btnSetar">
Setar
</button>
JS
var nome_da_tela = {
init: function(){
this.varUm = null;
var thisLocal = this;
$("#btn").click(function(){
alert(thisLocal.varUm);
});
$("#btnSetar").click(function(){
thisLocal.SetarValor();
});
},
SetarValor:function(){
var thisLocal = this
$.get('/echo/json/',{},function(data){
thisLocal.varUm = data
});
}
}
$(document).ready(function(){
nome_da_tela.init();
});
Follows link for testing. Have you ever had to do something like this? Do you have a better idea? I didn’t like having to create a variable (thisLocal) just to refer to the object outside its scope.
In this case I would have an interface for each screen? Using two variables, one with the name of the interface and the other instantiated?
– Onaiggac
Not much use?
Module Pattern/Factory Functions
in JS (considering only ES5) is a safer option than working withFunction Constructor
, that usually staff forget they need to use the operatornew
to instantiate and use the function, just because of this it is necessary to pollute the code with a defensive programming, which is done in the first line of Functiontela
. Each technique has its advantage, but don’t go around stating that it "doesn’t serve much", and most of the benefits go alongsidefactory functions
.– Gabriel Katakura
@Gabrielkatakura I agree, but that won’t change the future of the code if it’s protected. This says because it is common to create classes, despite having several advantages for performance.
– Klaider
@Onaiggac You can build the interface whenever you want and assign in any Javascript value. Look at an example:
alert(new tela().varUm); // vai ser undefined porque tela().init não foi executado
– Klaider