OK, so I’m taking the cheesy backgroundColorizer plugin to a different place because of this guy’s super clever trick. Couple things had to happen. First, I made my <body> tag look like this:
<body xmlns:sys="javascript:Sys"sys:activate="*">
Then I added this 1-time-only registration line below (this essentially tells the sweet little $.declare function to burn my “backgroundColorizer” plugin as a registered behavior for each element this its attached to , activated by that global sys:activate=”*” piece we added to the <body> tag) (did that make any sense?):
$(function () { $.declare("backgroundColorizer"); });
Now, some html elements can simply look like this with no additional javascript needed:
<ul sys:attach="backgroundcolorizer">
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
<tablesys:attach="backgroundcolorizer"backgroundcolorizer:oddColor=’lightGreen’ backgroundcolorizer:evenColor=’Green’>
<tr><td>Jane </td><td>Smith</td></tr>
<tr><td>Joe </td><td>Smith</td></tr>
<tr><td>John </td><td>Doe</td></tr>
<tr><td>Jane Q. </td><td>Public</td></tr>
</table>
OK, here’s the worst and hackish part, where i took my plugin and put in embarrassingly cheesy code to get around the various “children” semantics. I’m sure this would break down immediately, but for this trivial sample it works ok:
// The "backgroundColorizer" pluggin allows you to essentially color alternative odd/even rows' background // (thrilling, eh?) (function ($) { $.fn.extend( { backgroundColorizer: function (options) { var defaults = { oddColor: 'red', evenColor: 'blue' }; var options = $.extend(defaults, options); var selector = this; if (this[0].tagName == "TABLE") { selector = $('tr'); } else { selector = this.children(); } return $(selector).each(function (index) { var obj = $(this); if (index % 2 > 0) { obj.css("background-color", options.oddColor); } else { obj.css("background-color", options.evenColor); } }); } }); })(jQuery);
OK. So, there you have it. We’re using the declarative behavior approach of Microsoft’s ajax library to wrap around our JQuery plugin. Check out that link at the beginning of this post and after your brain stops curdling (as mine did) from that dude’s solution, then soak it up and savor.