Mj1992
Mj1992

Reputation: 3504

Referencing javascript object within jquery event

I've this code.

var NotificationsBox={
    HideNotificationBox:function()
    {
          document.getElementById("NotificationBox").style.visibility="hidden"; 
    },
    toggleNotificationBox:function()
    {
        $('#NotificationBox').toggle();             
    },
    SetContainerClick_NotificationHide_Event:function()
    {
        $('#Container').click(this.HideNotificationBox);        
    },
    SetNotificationBoxClick_NotificationToggleEvent:function()
    {
        $('#ShowNotification').click(function(){
            $(this).html("0");
            $(this).css("background-color","#000");

            this.toggleNotificationBox();     ///  <-- PROBLEM
        });
    }

};

NotifyBox=Object.create(NotificationsBox);
NotifyBox.HideNotificationBox();
NotifyBox.SetContainerClick_NotificationHide_Event();
NotifyBox.SetNotificationBoxClick_NotificationToggleEvent();

Now you can see what the problem is. Here this will reference to the #ShowNotification and I want to reference NotificationBox here so that I can call the function.

Upvotes: 1

Views: 50

Answers (1)

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91349

Save a reference to this before binding click, and use this reference instead of this within the click event handler:

SetNotificationBoxClick_NotificationToggleEvent:function()
{
    var self = this;
    $('#ShowNotification').click(function(){
        $(this).html("0");
        $(this).css("background-color","#000");

        self.toggleNotificationBox(); //  <-- self will refer to NotificationsBox
    });
}

Or, as an alternative, use NotificationsBox.toggleNotificationBox(), though this will cease to work if you happen to change the name of the variable NotificationsBox:

SetNotificationBoxClick_NotificationToggleEvent:function()
{
    $('#ShowNotification').click(function(){
        $(this).html("0");
        $(this).css("background-color","#000");

        NotificationsBox.toggleNotificationBox();
    });
}

Upvotes: 2

Related Questions