If you’re using the Microsoft Ajax Library (learn), you may not always want to start the automatic “attach” process that takes place when the page loads. It’s easy to disable, but not yet documented any place I could find easily.
<script src="Scripts/MicrosoftAjax/Start.debug.js" type="text/javascript"></script> <script type="text/javascript"> var ajaxPath = ""; Sys.activateDom = false;
All you must do is set Sys.activateDom to false as shown above (make sure this is set after the new Start.js JavaScript file loads, otherwise your code will crash when you try to set the Sys object before it has been properly constructed).
Then, to begin the attach process, just call Sys.activateElements:
Sys.activateElements(document.documentElement);
In the code line above, though I’ve specified that I want the entire HTML document activated, you could provide any element you want as a starting point (for example to optimize the use of the library and prevent unnecessary DOM searching for example).
I’m adding the delay in some JavaScript code because I wanted to set up a few variables in advance of the attach occurring. I tend to write my JavaScript code in an object oriented fashion these days (using the prototype pattern), including code that is interacting with the DOM. In this case, I’ll create a class that represents the logic of the page rather than following the typical purely functional model that is done on many JavaScript pages. But, when using the “eval” syntax of the Microsoft Ajax library “{{ code }}”, occasionally, I’ll need to delay the eval or the page will crash.
From my recent post on making a simple command extension to the Microsoft Ajax library, I wanted to make that more object oriented by referring to an instance of my class, rather than pointing directly to a function:
<body sys:attach="wpc" wpc:onbubbleevent="{{$view.onCommand}}" xmlns:sys="javascript:Sys" xmlns:wpc="javascript:WiredPrairie.Commanding">
$view represents the instance of my page’s behavior. However, if the attach were to occur too early, this variable is not yet set. I’m using the slick script loading functionality of the ajax library, specifying the various JavaScript libraries and their dependencies, including my page’s behavior. It’s not until that JavaScript code is loaded that the code can create an instance – and that could be AFTER the page has already done the attach logic. The attach happens before Sys.onReady for example. (Sys.onDomReady happens before onReady, but not all JavaScript files may have been downloaded).
Sys.onReady(function() { $view = new WiredPrairie.MainView(); Sys.activateElements(document.documentElement);
When using the sys:attach attribute, note that the attach and instantiation process happens before any code you’ve specified in onReady is executed (Microsoft currently uses the same method for determining when everything is ready by adding a function call to onReady – but their call is first in the queue).