0

I have a page that does ASP.NET ajax postbacks using UpdatePanels. In some javascript, I set up some objects in the window.onload event, which works great. When I do a postback though, it seems like my objects are messed up.

One object which was receiving events from a table, is no longer receiving the events. I also had a case where objects which has local references to buttons wouldn't be able to update them. Here's the button javascript that was getting messed up:

function EditItemPage(clientId)
{
    this.saveButton = $get(clientId + ""_{2}"")
    this.publishButton = $get(clientId + ""_{3}"")
    this.exitButton = $get(clientId + ""_{4}"")

    EditItemPage.prototype.GoDirty = function()
    {
        //it works if i add these, but i'd rather not have to.
        this.saveButton = $get(clientId + ""_{2}"")
        this.publishButton = $get(clientId + ""_{3}"")
        this.exitButton = $get(clientId + ""_{4}"")

        this.saveButton.disabled = false;
        this.publishButton.value = 'Save and Publish';
        this.exitButton.value = 'Discard changes and Exit';
    }
}

So after I do a postback, the button references are messed up unless i reset them as I did in the GoDirty() function.

Any insight?

MStodd
  • 4,716
  • 3
  • 30
  • 50

1 Answers1

2

The this keyword (special variable) changes based on what function is calling it. Basically, it's an issue of scope. You need to either do a closure around the function which is being called on the ajax response, OR put what you need into the global scope, OR do what you are doing (which you don't like).

Writing the closure is the "right" way.

You may be familiar with the way the this variable changes scope based on events for form inputs. For a textbox, if you use the onblur event, the this refers to the textarea which just lost focus.

See this question for an example of how to do the closure.

This is also another good resource.

(I'm sure I could copy and paste the examples in here for you, but that seems redundant)

Community
  • 1
  • 1
cgp
  • 41,026
  • 12
  • 101
  • 131