Creating jQuery plug-ins from MicrosoftAjax components
We had an interesting discussion recently on the ASP Insiders mailing list and ended up talking about what cool stuff we could build on top of jQuery. Many interesting things were mentioned and it was a very useful discussion but one suggestion in particular struck my curiosity as it was something I had investigated before and that could be improved on with very little code.
I had already written a little plugin to enable instantiation of Microsoft Ajax components on the results of a jQuery selector:
jQuery.fn.create = function(type, properties) { return this.each(function() { Sys.Component.create(type, properties, {}, {}, this); }); };
I have another version that is a little more elaborate and takes a bag of properties and events instead of just properties (get it from the attached sample) but you get the idea. This makes it fairly easy to instantiate components based on a selector:
$(":text.nomorethanfive")
.create(Bleroy.Sample.CharCount, { maxLength: 5 });
But if this were a native jQuery plugin instead of a Microsoft Ajax component, as Rick Strahl suggested, chances are you’d do something like this instead:
$(":text.nomorethanfive").charCount({ maxLength: 5 });
We can actually get that exact result fairly easily by writing a plugin that is specific to this component, but we can’t expect every Microsoft Ajax component author to also write a jQuery plugin, can we? We can do better than that. Here is a second small piece of code that is still generic but is in the business of creating jQuery plugins:
Sys.Component.exposeTojQuery = function(type, pluginName) { return jQuery.fn[pluginName] = function(properties) { return this.each(function() { Sys.Component.create(type, properties, {}, {}, this); }); } }
Like above, the version in the sample is better than that in that it supports events in addition to properties but again you get the idea. Thanks to this function, we can create a jQuery plugin for any existing Microsoft Ajax component with a single line of code:
Sys.Component.exposeTojQuery(Bleroy.Sample.CharCount, "charCount");
After this call, we can write exactly the code we wrote before, but without having had to write a specific plugin. We can then use charCount like a native jQuery plugin:
$(":text.nomorethanfive").charCount({ maxLength: 5 });
This is really easy to use, and I quite like it. We could for example add the following line of code to the new MicrosoftAjaxTemplates.js:
if (jQuery)
Sys.Component.exposeTojQuery(Sys.UI.DataView, "dataView");
This would enable us to instantiate DataView controls as simply as this:
<ul class="dv"> <li>{{ $dataItem }}</li> </ul> <script type="text/javascript"> $(".dv").dataView({ data: ["foo", "bar", "baz"] }); </script>
Get the code from here (you need to include jquery-1.3.2.js to the script folder):
http://weblogs.asp.net/blogs/bleroy/Samples/jQueryCreate.zip