$: Now with more magic!

Ajax Add comments

Dustin Diaz is on a roll :) He has posted about Roll out your own JavaScript Interfaces in which he discusses the desire to use style from libraries such as prototype, jquery and friends, yet in a small bit of code where you don't want to use the library:

There are times when using a JavaScript library is called for. Building large web applications that use a wide array of utility functions that help aid in developing multi-tiered class systems, advanced UI components, complex event models, and heavy use of DOM scripting helpers. Yep. Those are all great.
However, there are other times when you don’t need all that. And often what we end up doing is just importing a few of our favorite functions as globals, and work off those. But what ends up happening in this case is that we lose the particular style that these libraries offer. For instance, I’d still like to be able to do something like this without a library.

Dustin would like to write something like this:

PLAIN TEXT
JAVASCRIPT:
  1. $('foo', 'bar').on('click', function(e) {
  2. $(this).css({
  3. color: 'green',
  4. fontSize: '2em'
  5. }).addClass('active');
  6. });

And to implement the magic he takes Prototypes $() and makes it a special object that can do much more:

PLAIN TEXT
JAVASCRIPT:
  1. (function() {
  2. // private constructor
  3. function _$(els) {
  4. this.elements = [];
  5. for (var i=0; ilength; i++) {
  6. var element = els[i];
  7. if (typeof element == 'string') {
  8. element = document.getElementById(element);
  9. }
  10. this.elements.push(element);
  11. }
  12. return this;
  13. }
  14. _$.prototype = {
  15. each: function(fn) {
  16. for ( var i = 0, len = this.elements.length; i) {
  17. fn.call(this, this.elements[i]);
  18. }
  19. return this;
  20. },
  21. setStyle: function(prop, val) {
  22. this.each(function(el) {
  23. el.style[prop] = val;
  24. });
  25. return this;
  26. },
  27. addClass: function(className) {
  28. this.each(function(el) {
  29. el.className += ‘ ‘+className;
  30. });
  31. return this;
  32. },
  33. on: function(type, fn) {
  34. var listen = function(el) {
  35. if (window.addEventListener) {
  36. el.addEventListener(type, fn, false);
  37. } else if (window.attachEvent) {
  38. el.attachEvent(’on’+type, function() {
  39. fn.call(el, window.event);
  40. });
  41. }
  42. };
  43. this.each(function(el) {
  44. listen(el);
  45. });
  46. return this;
  47. },
  48. css: function(o) {
  49. var that = this;
  50. this.each(function(el) {
  51. for (var prop in o) {
  52. console.log(prop);
  53. that.setStyle(prop, o[prop]);
  54. }
  55. });
  56. return this;
  57. }
  58. };
  59. window.$ = function() {
  60. return new _$(arguments);
  61. }
  62. })();

You can see a demonstration at work.

[via Ajaxian]

Leave a Reply

Entries RSS Comments RSS Login