如何从客户端调用谷歌应用程序脚本中的类方法?

问题描述 投票:0回答:3

如何从客户端调用谷歌应用程序脚本中的类方法? //客户端

function myClientSideFun() {
google.script.run.withSuccessHandler(onSuccess).myClass.myClassMethod()    
function onSucces(msg) { console.log(msg) } 
 }  

//server side
class MyClass {
myClassMethod() { return "myMsg" }
 }

let myClass = new MyClass()
class google-apps-script web-applications client-server
3个回答
1
投票

除非您在不同的顶级函数中导出类方法,否则不可能直接从客户端调用类方法。类只是现有对象的语法糖。关于 私有函数 的文档清楚地表明

obj.objectMethod()
不可从客户端调用。


0
投票

作为使用对象方法的简单示例。

HTML_测试

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <input id="testParam" type="text">
    <script>
      (function () {
        google.script.run.withSuccessHandler(
          function(param) {
            document.getElementById("testParam").value = param;
          }
        ).getTestParam();
      })();
    </script>
  </body>
</html>

代码.gs

class TestObject {
  constructor(param) {
    this.param = param;
  }
  get getParam() { return this.param; }
}

var obj = new TestObject("hello");

function getTestParam() {
  return obj.getParam;
}

选项2

在 @Bede 指出的基础上,有很多方法可以使用服务器端对象。

HTML_测试

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <input id="testParam" type="text">
    <script>
      (function () {
        google.script.run.withSuccessHandler(
          function(param) {
            document.getElementById("testParam").value = param;
          }
        ).getTestParam({name: "getParam2"});
      })();
    </script>
  </body>
</html>

代码.gs

class TestObject {
  constructor(param1,param2) {
    this.param1 = param1;
    this.param2 = param2;
  }
  getParam1() { return this.param1 }
  getParam2() { return this.param2 }
}

var obj = new TestObject("hello","goodbye");

var getTestParam = param => { return obj[param.name](); }

0
投票

非常感谢您的示例和答案,基于此,我似乎正在找出另一种方法,如何在服务器端封装函数 - 实际上使用对象文字:

const appFunctionLibrary = {
 appFunctions: {
  "fun1": function (arg1) {
    return arg1
  },
  "fun2": function (arg1, arg2) {
    return [arg1, arg2]
  },
  "fun3": function () {
    return "fun without param"
  }
 }
}

const main = requestedFunction =>
appFunctionLibrary.appFunctions[requestedFunction.name] 
(requestedFunction.arguments)

从客户端调用/1方式:也在客户端脚本中创建一个“对象”并调用../:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
  <button type="button" onclick="clientObject.clientFun.call(clientObject)">Test</button>
    <script>
      function ClientObj() {
       this.clientFun = function(){
        let arg1 = 'hello'
        let arg2 = 'from client'

        google.script.run.withSuccessHandler(function onSuccess(msg) {
          console.log(msg)
        }).main({name:'fun2', arguments: `${arg1}, ${arg2}`})  // .main({name:'fun3', arguments: ""}) .main({name:'fun1', arguments:  `${arg1}`})
       }
      }
      clientObject = new ClientObj()
    </script>
  </body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.