Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

[Twine2.1.1][Sugarcube 2.14] Is there a way to call a macro from JavaScript?

edited March 2017 in Help! with 2.0
Hey there,

I'm getting tired of duplicating my JS code to define a macro and then define a normal JS function to do exactly the same thing.
Is there a way for me to invoke a macro that I previously defined in JS inside a JS function?

Simple place holder code:
Macro.add('MySugarCubeMacro',
{
    handler: function()
    {
       console.log ("MySugarcubeMacro() invoked!");
    }
});

window.macro_invoker = function()
{
    // i have no clue how you do this...
    Macro.Invoke("MySugarCubeMacro");
}

Thank you for your answer!

Comments

  • edited March 2017
    There's very likely a better way, but you can use the wikifier to call Twine code from JS:
    new Wikifier(null, '<<MySugarCubeMacro>>');
    

    There are other ways too, but that's the one I've seen most often recommended, and the one I usually use.
  • oh, i remember using, this I didn't know it could actually invoke macros just like that.
  • I prefer writing the JavaScript function, and then adding a macro that calls that function.

    E.g.
    setup.myFunction(firstParam, secondParm) {
    //do stuff
    }
    
    Macro.add('MyFunction', {
        handler: function()
        {
           setup.myFunction(this.args[0], this.args[1]);
        }
    });
    
  • Rokiyo wrote: »
    I prefer writing the JavaScript function, and then adding a macro that calls that function.
    I believe this is the better way to have a macro and Javascript function execute the same core code.

    Because macro definition is basically just a thin abstraction layer around Javascript code evocation and using <jQuery>.wiki (or a Wikifier) in this case to evoke the same code from two locations is an expensive operation.
  • edited March 2017
    @Rokiyo: so, what is the difference in adding the function to the "window" rather than to the "setup" object?
  • edited March 2017
    Disane wrote: »
    @Rokiyo: so, what is the difference in adding the function to the "window" or "setup" objects?
    Simple put, the developers of your web-browser (or of third-party Javascript libraries for that matter) may add properties to the window object in their next release and if your custom property has the same name as theirs then yours could overwrite theirs which could lead to interesting behaviour. This is one reason why it is generally a good idea to create your own unique Namespace when extending the window object.

    On the other hand it is very unlikely that anyone but yourself is going to add new properties to the setup object, which SugarCube supplies for the Author's use.
  • @greyelf: Thanks man, I'll start refactoring then. It's amazing how much one can learn on this forum.
Sign In or Register to comment.