Wrapping ScriptListener Code

Photoshop Script Snippets - Note: Full Scripts go in the Photoshop Scripts Forum

Moderators: Tom, Kukurykus

xbytor

Wrapping ScriptListener Code

Post by xbytor »

Most of us here are familiar with wrapping ScriptListener code in a function:

Code: Select allvar id32 = charIDToTypeID("Rvrt");
executeAction(id32, undefined, DialogModes.NO);
would become
Code: Select allfunction revertDocument() {
   executeAction(charIDToTypeID("Rvrt"), undefined, DialogModes.NO);
}

One feature of SL code is that it invariably will work only on the current/active document. This is normally not a problem, but there are times when you have multiple documents open that this is a bit of a pain.

What I've been doing for awhile now is wrapping SL code so that you can specify the document on which the code should operate without losing track of what the active document it.

Code: Select allfunction wrapSLCode(_doc, ftn) {
  var ad;
  if (_doc) {
    try { ad = app.activeDocument; } catch (e) {}
    app.activeDocument = _doc;
  }
  try {
    ftn();
  } finally {
    if (ad) try { app.activeDocument = ad; } catch (e) {}
  }
}

function revertDocument(doc) {
  function _ftn() {
    executeAction(charIDToTypeID("Rvrt"), undefined, DialogModes.NO);
  }
  wrapSLCode(doc, _ftn);
}

Document.prototype.revert = function() {
   revertDocument(this);
}


The code above will let you do invoke "docRef.revert()" on any document whether its an active document or not. This technique can also be extended to SL code that has parameters.