如何在 ClearScript.V8 中捕获更新事件?

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

有没有一种方法可以实例化 Javascript 变量(使用 ClearScript.V8)并在 C# 中捕获更新以便更新数据库中的值?

当我使用一个对象时它起作用了,像这样:

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;
    }
}

但是 Javascript 代码需要使用像

这样的对象

variable.value

而不是简单地

variable

.

您可以定义一个 JavaScript 全局 属性 以及调用您的智能变量的访问器:

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");