【问题标题】:How to define a persistent property in JXA如何在 JXA 中定义持久属性
【发布时间】:2015-12-23 20:42:44
【问题描述】:

我会在 AppleScript 中编写

property foo: "value"

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

【问题讨论】:

    标签: osascript javascript-automation


    【解决方案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 的支持

    【讨论】:

      猜你喜欢
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 2013-07-23
      • 2012-02-18
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多