Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my function run multiple times after UpdatePanel is loaded

So I want to run some javaScript function after my updatepanel is updated, so I have:

function pageLoad() { 

    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_pageLoaded(panelLoaded);
}


function panelLoaded(sender, args) {
        alert("foobar");
}

With the above code, if I update the panel one time, "foobar" will be alerted one time; If I update the panel the second time, "foobar" will pop up twice; the third time I trigger the panel to update, "foobar" popped up three times... 4th time pop 4 times so on and so forth....

What caused this??

Thanks~~~

like image 424
eastboundr Avatar asked Aug 03 '12 20:08

eastboundr


2 Answers

This is because pageLoad is executed during updatepanel postbacks as well. There is an easy solution:

function pageLoad(sender, eventArgs) {
    // If this is being executed by ajax
    if (eventArgs) {
        // And this is only a partial load
        if (eventArgs.get_isPartialLoad()) {
            // Don't perform any further processing
            return;
        }
    }
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_pageLoaded(panelLoaded);
}
like image 119
competent_tech Avatar answered Oct 11 '22 17:10

competent_tech


Thanks all, problem seem to be having too many prm instances as Sam mentioned. I added Sys.WebForms.PageRequestManager.getInstance().remove_pageLoaded(panelLoaded); after the alert() and everything is good.

like image 44
eastboundr Avatar answered Oct 11 '22 17:10

eastboundr