May 20, 2011
JQuery provides a superb way of easily finding and manipulating elements. But, if you don’t watch yourself, it can quickly become quite dangerous and easily be broken. For intance, imagine this file structure, with some example elements listed as its children.
– div class=”Target1″
– div class=”Target2″
and so on. If the page were to do something like:
You can imagine what would easily happen over time. Some other developer modifies the page and removes that DIV completely because they didn’t even know about it. As user controls get shared across pages, people may accidentally make a modifications to the user control in other pages, and as such, it breaks the page you were working in.
This is why I’m an advocate for utilizing JQuery plugins or widgets as much as possible. The UC could create its own widget that registers itself with the page. The page can then call the UC’s methods or do whatever it needs to do, instead of working with the internal elements directly. Otherwise, you may find yourself with broken code later on. If you don’t like the plugin/widget approach, just try at least to keep all of the JS code that’s related to this user control within the user control’s body, or in a script file where it won’t be easily lost.