如何在JXA中定义持久属性

时间:2015-05-26 16:52:08

标签: osascript javascript-automation jxa

在AppleScript中我会写

property foo: "value"

并且将在运行之间保存该值。如何在Javascript for Automation中执行此操作?

1 个答案:

答案 0 :(得分:1)

自动化JavaScript与AS的持久属性(和全局值)机制没有直接并行,但它确实有JSON.stringify()JSON.parse(),它们适用于简单的序列化并检索国家。

也许广泛地说:

(function () {
    'use strict';

    var a = Application.currentApplication(),
        sa = (a.includeStandardAdditions = true, a),
        strPath = sa.pathTo('desktop').toString() + '/persist.json';

    // INITIALISE WITH RECOVERED VALUE || DEFAULT
    var jsonPersist = $.NSString.stringWithContentsOfFile(strPath).js || null,
        persistent = jsonPersist && JSON.parse(jsonPersist) || {
            name: 'perfume',
            value: 'vanilla'
        };
    /*********************************************************/

    // ... MAIN CODE ...

    // recovered or default value
    sa.displayNotification(persistent.value);

    // mutated value
    persistent.value = "Five Spice"

    /*********************************************************/

    // WRAP UP - SERIALISE TO JSON FOR NEXT SESSION
    return $.NSString.alloc.initWithUTF8String(
        JSON.stringify(persistent)
    ).writeToFileAtomically(strPath, true);

})();

(这里有一个更全面的例子:https://github.com/dtinth/JXA-Cookbook/wiki/Examples#properties-which-persist-between-script-runs

或者,对于简单的键值对而不是任意数据结构,请参阅: https://stackoverflow.com/a/31902220/1800086关于JXA支持编写和阅读.plist