CopperSpice API
1.9.2
|
CsScript extensions can make additional functionality available to JavaScript code by importing an extension into a QScriptEngine. There are three ways to implement an extension.
Extensions are imported by calling the method QScriptEngine::importExtension() which will load the script file to initialize the extension. The contents of the script file will be evaluated by the engine when the extension is imported.
The script file is called "__init__.js". The name of the extension is used to determine the path to the script file. The path is relative to the application's plugin path. For example, if the extension is "foo.bar.baz" then QScriptEngine will look for the script file in a folder named "foo/bar/baz". Before importing the extension QScriptEngine will ensure the extensions in "foo" and "foo/bar" are imported first.
The contents of the script file is evaluated in a new QScriptContext as if it were the body of a function. The engine's Global Object acts as the "this" object. The following local variables are initially available to the script.
The following is a simple example for loading an extension.
QScriptEngine will look for a QScriptExtensionPlugin which provides the requested extension by querying each plugin for its keys until a match is found. The plugin initialize() method will be called after the script file "__init__.js" (if any) has been evaluated.
Using the extension example of "foo.bar.baz", the following steps will be performed by QScriptEngine::importExtension().
foo/__init__.js
is evaluated. "foo"
in its list of keys is found, its initialize() function is called with "foo"
as key. foo/bar/__init__.js
is evaluated. "foo.bar"
in its list of keys is found, its initialize() function is called with "foo.bar"
as key. foo/bar/baz/__init__.js
is evaluated. "foo.bar.baz"
as key. When an extension is compiled and linked into your application as a static plugin, CsScript will look for the optional init.js
script in a resource, prefixed by :/qtscriptextension
. For example, if the extension key is "foo.bar", CsScript will evaluate the contents of the file :/qtscriptextension/foo/bar/__init__.js
, if it exists. If the resource is built into the plugin you may need to use the Q_INIT_RESOURCE() macro to initialize the resource before importing the extension.