tags:

views:

22

answers:

1

How might I convert my bind method to allow for both a single object or an array of objects (in this case several links) to have functions bound to certain events? Would be cool to handle it within the bind() method I think.. Any assistance would be appreciated

var dQuery = function() {
  return {
  bind: function(obj, type, handler, delegate) {
      var delegate = delegate || false;
      this.log(obj);
      if (obj.addEventListener) {
        obj.addEventListener(type, handler, delegate); // false: bubble (^). true: capture (v).
      } else if (obj.attachEvent) {
        obj.attachEvent('on'+ type, handler);
      } else {
        obj['on'+ type] = handler;
      }
    }
  }
}();

(function($){
var $links = document.getElementsByTagName('a');

  $.bind($links, 'click', function() {
   // .. do stuff to each <a>
  });


})(dQuery);
+1  A: 

You could throw in something like

if (obj instanceof Array) {
  for (var i = 0; i < obj.length; i++) {
     //...
  }
}
else {
  //...
}
ipartola
the only problem is that javascript thinks the collected links are instanceof Object instead of Array.. hmm
tester
ah, I guess I just could do if (obj.length > 1) .. well thanks for the idea
tester