2015-05-26 59 views
2

定義持久化屬性在AppleScript的我會寫如何JXA

property foo: "value" 

和值將被保存運行之間。我如何在Javascript for 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); 

})(); 

(A更全面的例子在這裏:https://github.com/dtinth/JXA-Cookbook/wiki/Examples#properties-which-persist-between-script-runs

或者,簡單的鍵值對,而不是任意的數據結構,參見: https://stackoverflow.com/a/31902220/1800086上JXA支持書寫和閱讀.plist

相關問題