I have several simple C++ classes, for example:
class Audio {
public:
Audio(const char *filename, bool async = true);
~Audio();
Audio *play(int fade = 0);
Audio *pause();
Audio *loop(int loops = -1);
Audio *volume(float volume);
I have replicated the structure in JavaScript as follows:
var Audio = function(filename, async) {};
Audio.prototype.Play = function(fade) {};
Audio.prototype.Pause = function() {};
Audio.prototype.Loop = function(loops) {};
Audio.prototype.Volume = function(volume) {};
And after reading both the documentation and the sources for v8, v8-juice, and a plethora of blogs… I can’t find a single reference on how to “override” a JS function with a C++ method.
Ideally, I’d like JS to be in control of class creation/destruction (is this possible?), and have those objects always point to my native functions (PrototypeTemplate?).
I’ve seriously spent my entire day today reading articles/blogs/code related to this and can’t find, what I should hope is, a simple answer.
For your sakes, a “simple” answer to me would be something along these lines (wrappers are fine with me; if I have to write wrappers for the creation/destruction that’s okay):
v8::Local<v8::Function> jsAudioFunction = v8::Local<v8::Function>::Cast(v8::Context::GetCurrent()->Global()->Get(v8::String::New("Audio")));
jsAudioFunction->Setup(/* setup constructor/destructor */);
jsAudioFunction->SetPrototype(/* map native methods to js functions */);
While this doesn’t answer the question of binding native code to JS objects, here are the fruits of my labor:
Inside of my init() function:
This does everything exactly the way I want it to; including proper instantiation and garbage collection.
The only regret I have with this approach is that I would like to be able to “only use what is defined.” That way these function are only available if the JS “class” has been included (making it possible to have all functions defined and documented in a JS IDE).