patcher.getnamed() does not return object right after patcher is loaded. Why?

Valery_Kondakoff's icon

Hello!

I was trying to access Max objects from JavaScript. While experimenting I have found, that patcher.getnamed() does not return object if it is called right after patcher load.

Here is my test script ('mySketch9' is a script name of jit.gl.sketch object):

var mySketch8;
var mySketch10 = this.patcher.getnamed('mySketch9');
function initSketch(x) {
mySketch8 = this.patcher.getnamed(x);
post("mySketch8 = " + mySketch8 + "\n");
}
initSketch('mySketch9');
post("mySketch10 = " + mySketch10 + "\n");

So, here are two attempts to initialise variables using patcher.getnamed(), but the variables mySketch8 and mySketch10 are not initialised when I load the main max patch. Here is what I see in Max Console:

js: mySketch8 = null
js: mySketch10 = null


It is interesting, that loadbanging the message 'initSketch mySketch9' to js object _does_ initialise the variable and Max Console reads:

js: mySketch8 = null
js: mySketch10 = null
js: mySketch8 = [object Maxobj]

Can anybody explain what is going on? Is this a bug or am I doing something wrong?
Thank you!

Here is a screenshot (Max 8.0.2, MacOSX 10.14.2):

Jan M's icon

You call this.patcher.getnamed('mySketch9'); in global code. This means it is executed as soon as the js object is instantiated, but not necessarily the entire patcher.

try moving it to the loadbang function in JS witch is executed after the entire patch is loaded:

var mySketch10 = null;
function loadbang() {
     mySketch10 = this.patcher.getnamed('mySketch9');
}

This should solve it.

Valery_Kondakoff's icon

Yes, that's it: function loadbang() is a solution. Thank you, Jan, for help and explanation!