Taritsyn / JavaScriptEngineSwitcher

JavaScript Engine Switcher determines unified interface for access to the basic features of popular JavaScript engines. This library allows you to quickly and easily switch to using of another JavaScript engine.
Apache License 2.0
440 stars 49 forks source link

Help needed on import function #33

Closed imsmart-tech closed 7 years ago

imsmart-tech commented 7 years ago

I'm developing a service where people will write their own Javascript code. With it I want them to write modules. Users would also have to explicitely load a given module to use it.

Check the test code below. It does not work because _engine is null when I call ImportModule. I don't know if it's possible to pass back the engine object to the function or how to walk around this issue.

    public class SmartScript
    {
        private IJsEngine _engine;

        public void Test()
        {
            try
            {
                RunJS();
            }
            catch (Exception ex)
            {

            }
        }

        public void RunJS()
        {
            _engine = JsEngineSwitcher.Instance.CreateDefaultEngine();

            try
            {
                _engine.Execute("this.ImSmart = {};");
                _engine.EmbedHostObject("ImSmart", new SmartScript(true));

                _engine.Execute("ImSmart.ImportModule('Nest');");
            }
            finally
            {
                _engine.Dispose();
            }
        }

        public void ImportModule(string name)
        {
            string Code = "(function() { " +
                " this.ImSmart.Nest = function Nest(room){ " +
                " this.room = room; " +
                " this.temperature = null; " +
                " this.ShowRoom = DisplayNest; " +
                " this.SetTemperature = SetTemperature; " +
                " } " +
                " function DisplayNest() " +
                " { " +
                " return 'room is ' + this.room + '. Temperature is ' + this.temperature; " +
                " } " +
                " function SetTemperature(temp) " +
                " { " +
                " this.temperature = temp; " +
                " } " +
                " }());";

            this._engine.Execute(Code);
        }
    }
Taritsyn commented 7 years ago

Create an instance of JS engine in class constructor. Please do not write in issue tracker about such errors.