Naftali
Naftali

Reputation: 146350

Using `this` in a js object

I have the following js object:

var livePage = {
    delay: 1000,
    loadTables: function(){
        loadTable($("#vbeTable"),'getUpdateA')
        loadTable($("#vbcTable"),'getUpdateB')
        createAlertDialog();
    },
    setClicks: function(){
        $(".expand").live('click',function(){
            expand($(this).attr('expandvalue'));
        })
        $( ".launch" )
            .click(function(){
                newPopup('index.php',1120,550);
            });
        $('.edit').live('click',function(){
            openColPick($(this).attr('colType'))
        });
    },
    setRightClick: function(){
        $('body').contextMenu('mainmenu', {
              bindings: {
                'o_o': function(t) {
                  thePopupWindowsMain('oo','','',220,150,'right','');
                },
                'o_h': function(t) {
                  thePopupWindowsMain('oh','','',285,385,'left','');
                },
                'launch_prog': function(t) {
                  $(".launch").click();
                },
                'logout': function(t){
                    window.top.location = 'logout.php';
                }
              }
            });
    },
    setWindow: function(){
        $(window)
            .resize(function() {
                $('body').css('height', $(this).height())
                alertToCorner();
            })
            .scroll(function(){$(this).resize()});
        $(window).resize();
    },
    checkLogout: function(){
        $.ajax({
            url: 'getLogin.php',
            dataType: "html",
            success: function(data){
                if($.trim(data) == 'LOGOUT'){
                    window.location = 'logout.php';
                }
            },
            complete: function(){
                setTimeout( function () {
                    livePage.checkLogout();},
                livePage.delay)
            },
            timeout: 2000
        });
    },
    init: function(){
        this.checkLogout();
        this.loadTables();
        this.setClicks();
        this.setRightClick();
        this.setWindow();
        console.log(this);
    }
}

For some reason in the checkLogout: function() I have to use livePage.delay and livePage.checkLogout() When i try using for example this.checklogout() i get the following error in Chrome's Console:

Uncaught TypeError: Object [object DOMWindow] has no method 'checkLogout'

How do i fix this?

Thanks!

Upvotes: 1

Views: 666

Answers (5)

John Fisher
John Fisher

Reputation: 22717

this is far different in js than in languages like C#. First, it is function-scoped. Secondly (and probably more importantly), you can control what this will be when calling a function. (Check out the "call" and "apply" functions, which are used quite frequently in javascript frameworks.)

Upvotes: 1

CarlosZ
CarlosZ

Reputation: 8679

You should add a context: this property to the hash that you send to $.ajax and then in the complete handler call this.checkLogout.

What happens is that JQuery's ajax method will call the handlers using the window as the this context, we can change that by adding a context property to the call.

Upvotes: 0

Mark Brown
Mark Brown

Reputation: 12544

You can try,

 checkLogout: function(){
        var self = this; //reference to the livePage object
        $.ajax({
            url: 'getLogin.php',
            dataType: "html",
            success: function(data){
                if($.trim(data) == 'LOGOUT'){
                    window.location = 'logout.php';
                }
            },
            complete: function(){
                setTimeout( function () {
                    self.checkLogout();},  //need to use self because 'this' no longer refers to livePage in this context
                livePage.delay)
            },
            timeout: 2000
        });
    }

Upvotes: 3

ThiefMaster
ThiefMaster

Reputation: 318748

Inside a function this is not bound to whatever it was bound to outside anymore. The easiest solution is assigning to another var using var self = this; or in your case passing it via the context: this option of $.ajax().

Upvotes: 5

jmccarthy
jmccarthy

Reputation: 480

Have a read up on this this keyword in Javascript. In your case this refers to window which like the error says has no method 'checkLogout'.

Upvotes: 0

Related Questions