0

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
  • Note: In it's current state, it only handles one object at a time.. Commented Sep 15, 2010 at 19:04

1 Answer 1

1

You could throw in something like

if (obj instanceof Array) {
  for (var i = 0; i < obj.length; i++) {
     //...
  }
}
else {
  //...
}
Sign up to request clarification or add additional context in comments.

2 Comments

the only problem is that javascript thinks the collected links are instanceof Object instead of Array.. hmm
ah, I guess I just could do if (obj.length > 1) .. well thanks for the idea

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.