jbeard4 / SCION

SCXML/Statecharts in JavaScript, moved to gitlab: https://gitlab.com/scion-scxml/scion
https://scion.scxml.io
Apache License 2.0
149 stars 29 forks source link

send/invoke #371

Closed aksonov closed 8 years ago

aksonov commented 8 years ago

I'm trying to integrate SCION with my project, looks like send or invoke is best variant, but i can't override send to call my code, how to do it? How to return values from my code to SCION?

https://github.com/jbeard4/SCION/wiki/Plugin-API-for-SCION-2.0-branch

Is this project alive?

jbeard4 commented 8 years ago

Still alive. Please elaborate on your use case and I will advise you. Thank you.

aksonov commented 8 years ago

I believe my use case is quite common - i need to integrate my app with scxml state flow - i.e. run my code specified within onentry, onexit, etc. and run transition depending from executing of that code. Now I've implement it by using something like

global.run = function(promise, args) {
  // my wrapper that executed given promise and call scion.gen("success", data) or gen("failure", data)
}

then within scxml:

<onentry><script>run(storage.load, args)</script></onentry>

But it pollutes global space (i have to add all my modules there) and looks like hack, maybe is it better way?

jbeard4 commented 8 years ago

There are a couple of ways to do this. The pattern that I prefer is to pass your APIs to the state machine instance on an explicit init event. Something like:

<scxml>
  <datamodel>
    <data id="api"/>
  </datamodel>
  <state id="initial_default">
    <transition target="idle" event="init">
      <assign location="api" expr="_event.data"/>
    </transition>
  </state>
  <state id="idle"/>
</scxml>

Then you can initialize the session by calling:

session.start()
session.gen('init', {run : function(){
  setTimeout( function(){ session.gen('success') }, 10 ); // do something asynchronous and generate success
}})

You can see examples of this technique here and here. The advantage to this approach is it makes it easy for the environment to mock these APIs for testing purposes.

Let me know if you have any other questions. If not, feel free to close the issue. Thank you.

aksonov commented 8 years ago

Thanks!