Skip to content

Instantly share code, notes, and snippets.

@ifandelse
Created March 29, 2012 20:20
Show Gist options
  • Select an option

  • Save ifandelse/2243316 to your computer and use it in GitHub Desktop.

Select an option

Save ifandelse/2243316 to your computer and use it in GitHub Desktop.
Machina-based linear/fork-join FSM Task Idea
define([
'underscore',
'machina'
], function( _, machina ){
return function(config) {
var base = {
initialState: "notStarted",
checkIfReady: function() {
if(_.all(this.constraints[this.state].checkList, function(constraint) { return constraint; })) {
this.transition(this.constraints[this.state].nextState);
}
},
timeoutHandle: undefined,
data: [],
constraints: {
working: {
nextState: "completed",
checkList: {}
}
},
states: {
notStarted: {
"*" : function() {
this.deferUntilTransition();
}
},
working: {
_onEnter: function() {
var self = this;
if(config.onStart) {
config.onStart();
}
if(config.timeout) {
self.timeoutHandle = setTimeout(function(){
self.transition("error");
}, config.timeout);
}
}
},
completed: {
_onEnter: function() {
clearTimeout(this.timeoutHandle);
config.onComplete.apply(this, this.data);
}
},
error: {
_onEnter: function() {
config.onError.apply(this, this.data);
},
"*" : function() {
this.deferUntilTransition();
}
}
},
start: function() {
this.transition("working");
}
};
if(config.trigger) {
var handler = function() {
this.transition("working");
};
base.states.notStarted[config.trigger] = handler;
base.states.completed[config.trigger] = handler;
base.states.error[config.trigger] = handler;
}
_.each(config.topics, function(topic, idx) {
base.constraints.working.checkList[topic] = false;
base.states.working[topic] = function( data ) {
this.data[idx] = data;
this.constraints.working.checkList[topic] = true;
this.checkIfReady();
};
});
return new machina.Fsm(base);
}
});
var task = new DistributedTask({
timeout: 4000,
trigger: "resources.load",
topics: ["resource1.loaded","resource2.loaded","resource3.loaded","resource4.loaded"],
onStart: function() {
_.each([1,2,3,4], function(key) {
utils.publish("get.resource" + key);
});
},
onComplete: function(resource1,resource2,resource3,resource4) {
// do stuff with the resources
},
onError: function(resource1,resource2,resource3,resource4) {
this.start(); // retry
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment