manix
manix

Reputation: 14747

Method is not called inside of another method

I am trying to make an object named Dialogo. The idea is create it some functions and then call them inside of another method itself. Take a look:

function Dialogo(tamano){
    this.tamano = tamano;

    this.cerrar = function(){
        $('#dialogo_fondo').remove();
    };

    this.mostrar = function(){
        var dialogo_fondo = $('<div>').attr({id: 'dialogo_fondo' });
        $('body').fadeIn("slow", function(){$(this).append(dialogo_fondo);});
        $('#dialogo_fondo').css( {"width": $(window).width(), "height": $(window).height()});
        $('#dialogo_fondo').click(function(){ 
            this.cerrar(); 
        });
    };  
}  

Using jquery 1.7.2. According to the code, when I do click over #dialogo_fondo element, it should be removed, because the cerrar() method was triggered in click event. But it does not work. Can you point me to the right direction?

Upvotes: 0

Views: 65

Answers (1)

zerkms
zerkms

Reputation: 255155

this in mostrar declaration points to the anonymous function instance, check it with console.log(this);. So you need to create another reference to outer object var that = this; and use it instead:

function Dialogo(tamano){
    var that = this; // <--- here is the magic

    this.tamano = tamano;

    this.cerrar = function(){
        $('#dialogo_fondo').remove();
    };

    this.mostrar = function(){
        var dialogo_fondo = $('<div>').attr({id: 'dialogo_fondo' });
        $('body').fadeIn("slow", function(){$(this).append(dialogo_fondo);});
        $('#dialogo_fondo').css( {"width": $(window).width(), "height": $(window).height()});
        $('#dialogo_fondo').click(function(){ 
            that.cerrar(); // <---- use "that", not "this"
        });
    };  
}  

Upvotes: 1

Related Questions