Question

I'm in a way to make compat between XUI & Backbone but I met a problem in my design. I guess.

There it is. I want to extend XUI with a method call attr which would be able to deal with a hash of attributes/values. jQuery does, and Backbone exploits it. It's why I want to do this.

Unlucky, there already is an attr method in XUI. So, when I do:

xui.extend({
  attr:   function (attributes) {
    if (typeof attributes == "object") {
      for (var attr in attributes) {
        this.attr(attr, attributes[attr]);
      }
    };
  }
});

Of course, the proto of XUI have just one attr method. Mine. How can I have two?

Something doing following available:

xui(element).attr('attr', 'value');
xui(element).attr({'attr': 'value', 'foo': 'bar'});

Thanks for reading and helping :)

Was it helpful?

Solution

You need to save a reference to the original function, and then look at the arguments the function is called with to determine weather you should call your own version or the original.

Something like this (not tested code, so use only for inspiration):

var originalAttr = xui.attr;

xui.attr = function () {
  if(typeof arguments[0] === 'string') {
   originalAttr.apply(this, arguments);
  }
  else if(typeof arguments[0] === 'object') {
    for (var attr in attributes) {
      originalAttr.call(this, attr, attributes[attr]);
    }
  }
  else {
   /* unsupported arguments */
  }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top