Are you building a huge, jQuery-ASP.NET web application, which is subjected to a lot of global code changes in your client script? If yes, you should probably consider the below design pattern, which would help you have a better control on code execution.
Imagine a web application having ~400 .js files. Each .js file would have code for AJAX calls/DOM manipulations for the respective .aspx page. But there would be some code which is redundant and can be moved to a common global function, which can be accessed by all .js files. With respect to ASP.NET paradigm, this can be compared to - your code behind partial class inheriting a base class. So whenever you have a global change, you can just change the base class and all .aspx files will have the changes.
Solution- Using wrapper which can provide pre/post events:
Let’s say for every page, we need to prevent post back on click of any button. i.e., writing “e.preventDefault()” on button click events. I call this as a “Pre Event”, since this is to be executed before any click events are written.
Similarly, let’s say, for every page, we need to disable/show/hide certain controls, based on few conditions. I call this as a “Post Event”, since this code has to be executed at the end (similar to pre render event of asp.net model). So here is how we can try to enforce this.
var value='Hello world';
return new PrivateSpace();
console.log('init this:', this);
console.log('make ajax calls here');
console.log('cache selectors here');
var obj=new oldClass();
To explain the execute method, let’s consider the below code:
console.log("page load operations here...");
The above code is what resides in your ‘.js’ file. It is written in revealing module pattern. Here, CommonSearch is a constructor function and to execute it, we should say:
var objCommonSearch=new CommonSearch();
This does not have “Pre” and “Post” events. So if we need some global changes, we are lost! We have to manually change all 400 “.js” files. To troubleshoot this problem, if we use our my$.execute method, we can say:
Note that in the above snippet, we are not creating instance of CommonSearch constructor function. Instead, we are passing it to my$.execute, which internally calls the private “PreInit()” method first, then executes “init()” of CommonSearch, and calls the private “preRender()” method. So, we are enforcing a particular sequence of code execution, which solves our problem.
How this is different from using a common global function in document.ready, which can do the same functionality as my$.execute? Simple…we have good name spacing and chainability in our my$ function, which prevents conflicts with other modules.