Skip to content

Instantly share code, notes, and snippets.

@delucis
Last active August 29, 2015 14:19
Show Gist options
  • Save delucis/ee01a5a0c8a49fb8cb6a to your computer and use it in GitHub Desktop.
Save delucis/ee01a5a0c8a49fb8cb6a to your computer and use it in GitHub Desktop.
Handling loadbang() and notifydeleted() conflicts in Javascript in Max/MSP
// G L O B A L V A R I A B L E S
// set ID for module
var modulename = 'my-module';
// or if the [js] object is given a first argument, use that
if (jsarguments.length > 1) {
modulename = jsarguments[1];
}
// set unique ID for each module instance with random number generator
var instanceID = Math.round(Math.random()*100000);
// or if the [js] object is given a second argument use that — should be #0 within your patch
if (jsarguments.length > 2) {
instanceID = jsarguments[2];
}
// initialise global dictionary to hold our instantiation flags
var instantiationFlags = new Dict("instantiation-flags");
// G L O B A L M E T H O D S
// notifydeleted -- called when module deleted
function notifydeleted() {
// make sure our deleted instance ID still matches the ID stored
// in the dictionary before running notifydeleted() functions
if(instantiationFlags.get(modulename)) {
testid = instantiationFlags.get(modulename);
if(testid == instanceID) {
// YOUR ON-DELETION FUNCTIONS GO HERE
post(modulename, "has been deleted.\n");
flagsOff();
}
}
}
// loadbang -- called when [bpatcher] is created or reinstantiated
function loadbang() {
// YOUR ON-(RE)INSTANTIATION FUNCTIONS GO HERE
post(modulename, "has been created or reinstantiated.\n");
flagsOn();
if(instantiationFlags.get(modulename)) {
// YOUR ON-REINSTANTIATION FUNCTIONS GO HERE
post(modulename, "has been reinstantiated.\n");
}
if(!instantiationFlags.get(modulename)) {
// YOUR ON-FIRST-INSTANTIATION FUNCTIONS GO HERE
post(modulename, "has been created.\n");
}
}
// I N S T A N T I A T I O N F L A G S
flagsOn.local = 1; // make sure we can’t trigger this with a message
function flagsOn() {
// store the current instance ID for our module in the instantiationFlags dictionary
instantiationFlags.replace(modulename, instanceID);
}
flagsOff.local = 1; // make sure we can’t trigger this with a message
function flagsOff() {
// remove the entry for our module from the instantiationFlags dictionary
instantiationFlags.remove(modulename);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment