In c# you can create a custom indexer like so
public object this[string name]
{
}
I'm working with a javascript widget library which has a widget that takes an aray of objects as a property called labels like so
new Thingy({
labels: [{value:1, text:"my label"},[{value:2, text:"my next label"}]
});
The problem is that you have to plan ahead to know exactly what all the values are that will need a label. For instance, in the example above, i know that the labels will be for values 1 and 2. But if I don't know what the values might be, i would like to be able to dynamicly create the text based on the value it tries to access
so when the library internally tries to access:
this.labels[n].text
I would like this.labels[n] to do something like
function(n){return {text: "label for " + n};}
Is this possible within the bounds of the javascript language?
You can get es6 proxies in latest Chrome and write a handler like in C#, but it won't be compatible with older browsers.
Meanwhile I suggest putting a getLabel()
method on a Thingy.prototype
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With