How do use JUCE javascript array brackets subscript for c++ object?


#1

in Javascript:

obj = Midi.tag();

Console.log(obj[0]); // this prints "undefined"

So I get undefined when I try to do this which leads me to believe there may be a way to add something in the C++ code that tells it how to handle brackets ‘[]’? How do I do it? Thanks! (Note the class within a class below) I guess the question is specifically: What do I add to SaltTestObject definition?

in C++:

class SaltMidiObject
    :
    public DynamicObject
{
public:
    SaltMidiObject(JcfScriptRuntime & owner_)
        :
        owner(owner_)
    {
        setMethod("tag", tag);
    }

    class SaltTestObject : public DynamicObject 
    {
    public:
        SaltTestObject() {}
    };

    static var tag(const var::NativeFunctionArgs & args)
    {
        auto obj = getObjectWithArgumentCount<SaltMidiObject>(args);
        return new SaltTestObject;
    }

    JcfScriptRuntime & owner;
};

#2

The [] - operator is hardcoded to access an Array<var> object. From Javascript.cpp, line 414:

var getResult (const Scope& s) const override
        {
            if (const Array<var>* array = object->getResult (s).getArray())
                return (*array) [static_cast<int> (index->getResult (s))];

            return var::undefined();
        }

I suppose this would be the point where you could add your custom class handling, something like

else if (const SaltMidiObject *obj = dynamic_cast<SaltMidiObject*>(object->getResult(s)))
{
    return obj->getWithYourCustomMethod(index->getResult (s));
}

This code is just an ugly sketch and not tested, but you see where I am going. And you need to decide whether having a [] operator for your class justifies hacking around in the Javascript Engine (you would have to remerge it each time the Javascript engine is updated)…


#3

thank you!