A sane object model for programmers, using Distributed Objects.

Adding AppleScript support to your Cocoa application is a PITA, to put it bluntly. Sure, it's easy to do simple tasks, but once you move away from sample code territory, you are on your own and in many cases, in a world of hurt.

Why not do something more modern? Why not add scripting support the Cocoa way? Here's how to make your app scriptable via JSTalk:

Come up with an object model for your application, using standard Cocoa classes. In many cases this is already done, by virtue of writing a maintainable application.

Expose a "root" object to JSTalk, via Distributed Objects. In most cases, this will just be NSApplication. If you choose to use the JSTalk framework, it's just one line of code: [JSTalk listen];

Document what methods, properties, and objects you support. There's no magic xml files to fill out!

Exposing your model this way lets your app be scripted from Cocoa, Python, Ruby, and JavaScript- any language that can reach over to Cocoa. And no magic. Did I mention that part yet?

How does JSTalk (the language) work?

JSTalk is built on top of Apple's JavaScriptCore, the same JavaScript engine that powers Safari. So when you write in JSTalk, you are really writing JavaScript.

JSTalk also includes a bridge which lets you access Apple's Cocoa frameworks from JavaScript. This means you have a ton wonderful classes and functions you can use in addition to the standard JavaScript library.

JSTalk also adds a preprocessor to make using the Cocoa frameworks friendlier. Since Cocoa is written in Objective-C, you get a different syntax than what you'd normally encounter in JavaScript for calling methods. For example, here's some typical Cocoa code for writing a string to a file:

This is a valid script in JSTalk, but it doesn't look very nice. For instance, there are lots of underscores in the method names, and you don't get the nested message passing like you do in Objective-C. To fix this quandary, JSTalk adds a light preprocessor which will allow you to use Objective-C message syntax like so:

JSTalk Plugins

JSTalk comes with some standard helper categories (which you can currently find in JSTalkExtras.m), but it will also look in your ~/Library/Application Support/JSTalk/Plug-ins/ folder, and load any .jstplugin bundles it sees. You can turn this off in your application if you don't like that idea, via [JSTalk setShouldLoadJSTPlugins:NO];

There are two examples with JSTalk, one that just adds a category cocoa's string class: - [NSString reversedString]. The other example is "FMDB.jstplugin", which loads the FMDB SQLite classes, for use in JSTalk. This allows you to use sqlite to create, insert, update, etc, sql tables from JSTalk.