Vincent Scheib
Vincent Scheib

Reputation: 18610

How do I polyfill an attribute in JavaScript?

Given an attribute on an event that will be browser prefixed, I'd like to create a polyfill that makes it appear unprefixed.

E.g. the interface FooEvent has an attribute webkitBar that I'd like to make appear as just bar so that handlers could be written as onFoo = function(e) { console.log(e.bar); }

My clumsy initial guess is to inject something into the prototype FooEvent.prototype.getBar = function() { return this.webkitBar; }. But, I'm not certain how.

Upvotes: 3

Views: 266

Answers (3)

pradeek
pradeek

Reputation: 22105

This is a good resource to get you started.

http://addyosmani.com/blog/writing-polyfills/

Upvotes: 0

Jordão
Jordão

Reputation: 56467

You could register a "first" handler to the event to do the transformation:

function adaptsBar(e) {
  e.bar = e.webkitBar;
}

Upvotes: 1

Raynos
Raynos

Reputation: 169383

ES5 only (and IE8)

Object.defineProperty(FooEvent.prototype, "bar", {
  get: function () {
    return this.webkitBar;
  },
  configurable: true
});

Be warned that extending host objects. (FooEvent is a host object) has unknown side effects and is a big bag of undefined behaviour.

I'd recommend static wrappers

var eventUtil = {
  getBar: function (ev) {
    return ev.webkitBar;
  }
}

function handler (e) {
  var bar = eventUtil.getBar(e);
}

Upvotes: 4

Related Questions