Quote of the day

Friday, December 24, 2010

jQuery method in common javascript file for asp.net

Today, I faced an issue with "object required" error in javascript in my aspx pages. I'm working on the enhancement part of my project. As I'm curious of using jQuery, I implemented it in the page which I developed. Since there was only one javascript common file written for the whole project, I created events for buttons and other controls in that file.
I inherited common javascript file in my page and everything was working fine. But in other pages it was throwing "object required" error which is not suppose to happen. When I debugged the application, I got error in the jQuery events which I created.
The reason is, when other pages are loaded, jQuery script is trying to register the events which I've written for the new page I created. I, then used try.. catch.. inside the event, but still error persisted. Then my slow brain recognized that the event registration is causing the error. So I used try.. catch.. for registering events itself. Cool, my problem solved then.
Below did the trick:
try {
$("#btnSample").live("click", function() {
//do something
});
}
catch (err) {
}
Since try.. catch.. is used, even if it throws error, it would be catched and the error won't display!

Alternatively, you can use window.onerror method to return true whenever an error occurs is any of the method in javascript, which is actually not recommended.

No comments: