With a bit of prompting from others, I've been thinking about how to make the DOM accessible to Python programs in skulpt. The DOM has always seemed like a big black hole of endless functions and properties, and I've always thought about modules in skulpt as being implementations of existing Python modules. But for the DOM in a web page it now seems more sensible to me to just have the module mirror the Javascript interface. But again that seemed like a lot of work. Until yesterday when I figured out how I would approach the problem. I prototyped it by writing a wrapper for Javascripts Math object.
Now, you can look in the source and see how I've painstakingly wrapped each Math function in the current library. But most of that can be replaced with the following code:
var $builtinmodule = function(name)
{
var mod = {};
var props = Object.getOwnPropertyNames(Math)
for (i in props) {
if (typeof Math[props[i]] === "number" ) {
mod[props[i]] = Math[props[i]];
}
if (typeof Math[props[i]] == "function") {
mod[props[i]] = new Sk.builtin.func(Math[props[i]],undefined,undefined,undefined);
}
}
return mod;
}
The following little test program works perfectly using this approach.
import math
print math.sin(2.4)
print math.PI
print math.abs(-45.90)
print math.max(1,2,3,-1)
I've got something similar started for the document object but there are a few more hurdles to clear before I can call it a success.
1. parameters: Numbers work great untouched, but Strings and other Objects in Python need to be converted to their native forms before you pass them to the native Javscript functions.
2. return values, again numbers just work. But Strings and other objects must be converted from native javascript to skulpt/Python objects before they can be returned to the Python program.
Both 1 and 2 can be handled pretty nicely by adding some code to Sk.builtin.func and to
Sk.builtin.prototype.tp$call
3. objects: DOM functions of course do not return numbers and strings most of the time. The document object itself is an instance of HTMLDocument, and many other things are HTMLBodyElements. I don't see any reason why this can't be handled pretty much automatically either.
Anybody been down this same road? What have I missed? If you have the time and inclination to help with this little project please let me know!
Brad
--
Brad Miller
Associate Professor, Computer Science
Luther College