14 March 2011

Max/MSP Javascript: Dollar Function - Returns a reference to a Max Object in a patch/subpatch

I started using Max this month and was simultaneously impressed with its power and simplicity and frustrated by it's cumbersome interface. I quickly checked out it's javascript capabilities and became much more comfortable. JS allows you do simple operations quite quickly that would take a tonne of parsing objects which use up space and lead to a messy patch.

That said, JS in Max is really a slightly ugly cousin of browser based javascript. Calls to objects are long winded and basically everything is a bit head wrecking!

So here we go: the first in my "Making Max JS less crap" series... The infamous dollar function! All you need to do to access a max object is give the object a scripting name in the inspector* and then use: $('scriptingname')

Please see right hand pane before copying my code>>

function $(stringref){
    stringref=stringref.replace(/parent/gi, "parentpatcher")
    var path=stringref.split('.')
    var obj=this.patcher
    for(i in path){
        if(path[i]=='parentpatcher'){ //up 1 level:
            if(i!=path.length-1){ //down 1 level:

$("myButton").message('set','new text!') //access 'myButton' object in current patcher
$("parent.myButton").message('set','new text!') //access 'myButton' object in parent patcher
$("myPatcher.myButton").message('set','new text!') //access 'myButton' object in child patcher
$("parent.myPatcher.myButton").message('set','new text!') //access 'myButton' object in sibling patcher

* If you're not bothered giving every patcher a unique scripting name in the inspector, try my lazy dollar function instead.

A good way to use this function is to use Luke Hall's include script. Save his script into your jsexternals folder, save my functions into your project folder as basefunctions.js (or something similar) and then you can simply use include(this,"basefunctions.js") at the top of every JS file you use. Thanks Luke - this is awesome!


Post a Comment

Cron Design Studio: Dublin based web design & software development