Search code examples
c#.netv8clearscript

How do I catch an update event in ClearScript.V8?


Is there a way I can instantiate a Javascript variable (using ClearScript.V8) and catch the updates in C# so I can update the value in database?

It works when I use an object, like this:

public class SmartBoolean : ISmartVariable
{
    private Boolean _simulation;
    private Guid UserId;
    private long userKeyId;
    private long variableKeyId;
    private string Name;
    private Boolean _value;
    public Boolean value
    {
        get {
            return _value;
        }

        set {
            _value = value;

            if (!_simulation)
            {
                if (value)
                    new SmartCommon().SetTrue(userKeyId, variableKeyId);
                else
                    new SmartCommon().SetFalse(userKeyId, variableKeyId);
            }
        }
    }

    public SmartBoolean(Guid UserId, long userKeyId, long variableKeyId, string Name, Boolean value, Boolean simulation)
    {
        this.Name = Name;
        this._value = value;
        this.UserId = UserId;
        this.userKeyId = userKeyId;
        this.variableKeyId = variableKeyId;
        this._simulation = simulation;
    }

    public Boolean toggle()
    {
        this.value = !this._value;

        return this._value;
    }
}

but then the Javascript code needs to use an object like

variable.value

instead of simply

variable

.


Solution

  • You can define a JavaScript global property with accessors that call into your smart variable:

    dynamic addSmartProperty = engine.Evaluate(@"
        (function (obj, name, smartVariable) {
            Object.defineProperty(obj, name, {
                enumerable: true,
                get: function () { return smartVariable.value; },
                set: function (value) { smartVariable.value = value; }
            });
        })
    ");
    
    var smartVariable = new SmartBoolean(...);
    addSmartProperty(engine.Script, "variable", smartVariable);
    
    engine.Execute("variable = true");