How to generate global, named javascript functions

2019-01-26 08:35发布

I'd like to write Javascript scripts for Google Apps Script using CoffeeScript, and I'm having trouble generating functions in the expected form.

Google Apps Script expects a script to contain top-level, named functions. (I may be using the wrong terminology, so I'll illustrate what I mean with examples...)

For example, this function is happily recognised by Google Apps Script:

function triggerableFunction() {
   // ...
}

... while this function is not (it will parse, but won't you won't be able to trigger it):

var nonTriggerableFunction;

nonTriggerableFunction = function() {
  // ...
};

I've found that with CoffeeScript, the closest I'm able to get is the nonTriggerableFunction form above. What's the best approach to generating a named function like triggerableFunction above?

I'm already using the 'bare' option (the -b switch), to compile without the top-level function safety wrapper.

The one project I've found on the web which combines CoffeeScript and Google App Script is Gmail GTD Bot, which appears to do this using a combination of back-ticks, and by asking the user to manually remove some lines from the resulting code. (See the end of the script, and the 'Installation' section of the README). I'm hoping for a simpler and cleaner solution.

4条回答
一纸荒年 Trace。
2楼-- · 2019-01-26 08:58

CoffeeScript does not allow you to create anything in the global namespace implicitly; but, you can do this by directly specifying the global namespace.

window.someFunc = (someParam) -> 
    alert(someParam)
查看更多
神经病院院长
3楼-- · 2019-01-26 08:58

This should give you a global named function (yes, it's a little hacky, but far less that using backticks):

# wrap in a self invoking function to capture global context
do ->
  # use a class to create named function
  class @triggerableFunction
    # the constructor is invoked at instantiation, this should be the function body
    constructor: (arg1, arg2) ->
      # whatever
查看更多
我想做一个坏孩纸
4楼-- · 2019-01-26 09:00

juste use @ in script, exemple of my code :

@isArray = (o)->
  Array.isArray(o)

it will be compiled in :

(function() {

  this.isArray = function(o) {
    return Array.isArray(o);
  };

}).call(this);

this = window in this case, so it's global function

查看更多
够拽才男人
5楼-- · 2019-01-26 09:11

Turns out this can be done using a single line of embedded Javascript for each function.

E.g. this CoffeeScript:

myNonTriggerableFunction = ->
  Logger.log("Hello World!")

`function myTriggerableFunction() { myNonTriggerableFunction(); }`

... will produce this JavaScript, when invoking the coffee compiler with the 'bare' option (the -b switch):

var myNonTriggerableFunction;

myNonTriggerableFunction = function() {
  return Logger.log("Hello World!");
};

function myTriggerableFunction() { myNonTriggerableFunction(); };

With the example above, Google Apps Script is able to trigger myTriggerableFunction directly.

查看更多
登录 后发表回答