Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript custom index accessor

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?

like image 623
Michael Avatar asked Jun 05 '12 22:06

Michael


1 Answers

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.

like image 126
spacevillain Avatar answered Oct 01 '22 16:10

spacevillain