Search code examples
cocoascriptsketchapp

How to correctly combine "dot notation" and "braces notation" in cocoascript (sketch)?


In sketch documentation it's stated that dot and braces notations can be mixed with each other. It's even an example available:

[[context.document currentPage] deselectAllLayers];

Unfortunately, this code doesn't work in sketch and produce error if executed by "run custom script" command:

SyntaxError: Unexpected identifier 'currentPage'. Expected either a closing ']' or a ',' following an array element..
Plugin “untitled script”, line 2.
»   [context.document currentPage]; «Error in command untitled script Script at path (null) does not contain a handler function named: onRun
Script executed in 0.023666s

This can be avoided by adding additional ( and ):

[[(context.document) currentPage] deselectAllLayers];

Why this happens? Is it any documentation available how exactly braces and dot notation can be mixed? Is it some error or expected behaviour?


Solution

  • It seems to me it's an error, but in Sketch documentation. Besides this case you showed, I couldn't find any other example where dot and braces notations are used together in the same statement, without parentheses.

    The documentation page about Selections, for instance, tells that you'd use the following code to unselect everything:

    var doc = context.document
    [[doc currentPage] deselectAllLayers]
    

    Follow this link and look under Clearing the selection header: http://bohemiancoding.com/sketch/support/developer/02-common-tasks/01.html

    Even their example plugins don't mix both notations, as you can see here: https://github.com/BohemianCoding/ExampleSketchPlugins/blob/master/Hello%20World/Hello%20World.sketchplugin/Contents/Sketch/script.cocoascript.

    In that example, context.document is also assigned to a new variable before being used within braces.