ryanve
ryanve

Reputation: 52501

How to use JavaScript get and set for polyfill

I'm trying to figure out how to make a polyfill for dataset and I think I need to use get and set to define the function. How would the syntax of get/set be when trying to add them to Element.prototype? The examples on MDN shows a local variable, but how do you use them to add to Element.prototype?

Object.defineProperty {Element.prototype, "dataset", 
   get: function() { /* return value */ }
 , set: function(newVal) { /* set somehow w/ setAttribute or jQuery */ }
}

I'd like to either route the getter/setter methods to $.attr() the example above I just related them to .data() or (better) the native setAttribute and getAttribute. There is one polyfill for dataset here but it only supports standards-compliant browsers (not IE8 or less). I want to do one the avoids the use of __defineGetter__ (I think that's the issue in IE8). I think defineProperty may be the appropriate method, and I can use the ES5 Shim to polyfill that. How would I use defineProperty to do this?

Upvotes: 1

Views: 3553

Answers (1)

Brett Zamir
Brett Zamir

Reputation: 14345

Yes, Object.defineProperty works where available. I've made such a polyfill based on Eli Grey's original, enhancing a little bit by avoiding globals/non-standard prototype overriding and to work properly with CamelCasing (and utilizing his Xccessors polyfill where defineProperty support is lacking).

Update: Although it doesn't matter for you in this case, I might mention that the defineProperty polyfill will only work in IE8 on DOM objects. And it will not work before IE8 because one cannot override the DOM prototypes before then--unless you really want to get your hands dirty and build your own, but doing it thoroughly would be a vast task. Also, the dataset polyfills (mine and the original) currently only work in a polyfill, standard-friendly manner to read in properties from Element.prototype.getAttribute() and work from there. Element.prototype.getAttribute would also need polyfilling in order to ensure it was getting the latest dataset-updated version, etc.

Upvotes: 2

Related Questions