Binding a set-property on the global object

Sep 18, 2011 at 12:16 AM

Ok, here's a crazy question. I need to be able to run managed code whenever the script tries to set a specific property on the global object. To explain better, please take a look at the code bellow, what I need is to be able to call the onconnect function whenever something happens in my managed code (specifically, a client connects, but that shouldn't really matter). How can I achieve this?

onconnect = function(e) {
  log('connect'); // log is a custom js-defined function.
};

Coordinator
Sep 18, 2011 at 11:17 PM

Have you seen this page?  http://jurassic.codeplex.com/wikipage?title=Calling%20a%20JavaScript%20function%20from%20.NET&referringTitle=Documentation

Here's some c# sample code:

// engine is of type Jurassic.ScriptEngine

// Check "onconnect" is set to a function.
if (engine.GetGlobalValue("onconnect") is Jurassic.Library.FunctionInstance == false)
    return;

// Call the "onconnect" function.
engine.CallGlobalFunction("onconnect");
Sep 19, 2011 at 9:42 PM

Is there any way that I can register for the event that the onconnect value is set?

Coordinator
Sep 20, 2011 at 2:35 AM

Ah, I see.  Not as such, but you can use ES5 getters and setters to do this easily enough.

C#:

engine.SetGlobalFunction("onconnectCallback", new Action(() => /* do something */));

Javascript:

Object.defineProperty(this, "onconnect", {
    get: function() { return this.onconnectValue; }
    set: function(value) { this.onconnectValue = value; onconnectCallback(); }
  })