javascriptgoogle-apps-scriptweb-applicationsjavascript-namespaces

Calling google.script.run with Namespace Functions


I've been migrating an old javascript project to GAS and am hitting a blocker on trying to run namespace functions from the client-side web app. Quick code example:

var foo = function() {
  function doBar() {
    //do stuff
  }

  function doBang() {
    //do stuff
  }

  return {
  bar:doBar,
  bang:doBang
  }
}();

While this would be easy to call on the server side through foo.bar(), I have hit a wall in trying to speak to these functions from my web app. I was hoping to do something like this:

<script>
  google.script.run.withSuccessHandler(callback).foo.bar();
  function callback() {
    //do stuff
  }
</script>

But alas this does not seem to work. Is there something I am missing, or another way to get this working without having some form of handler function, not contained in a namespace, which passes through to my namespaces?

As this is a project migration, I have a very well structured but huge, set of namespaces; This would require a very long and robust hander function, so I would like to avoid doing so if possible.


Solution

  • You would need that handler function. Apps Script doesn't understand you are calling a server-side function if you add the dot, and so you get this error:

    TypeError: Cannot read properties of undefined (reading 'bar')

    Feature request:

    I'd suggest you to request this feature using this Issue Tracker template, if you'd like to see this implemented.