【问题标题】:google.script.run.withSuccessHandler(onSuccess). onSuccess doesn't works inside constructorgoogle.script.run.withSuccessHandler(onSuccess)。 onSuccess 在构造函数中不起作用
【发布时间】:2016-03-09 22:32:10
【问题描述】:

我在 Google Apps Script Web App 中使用客户端-服务器通信时遇到了一点问题。

我的 code.gs 包含:

function loadPetName() {
  Logger.log('Client ask a Pet Name');

  // use Google apps UserProperties as default storage
  var storage = PropertiesService.getUserProperties();

  return JSON.parse(storage.getProperty('name');
}

Pet.html 是:

<script>
// CLASS Pet
function Pet() {

  // CONSTRUCTOR
  console.log('Creating new Pet');
  var petName;

  // Get pet name from outer storage
  console.log('Loading pet name from storage...');
  google.script.run.withSuccessHandler(onSuccessLoad).loadPetName();
  var onSuccessLoad = function(name) {
    console.log('run onSuccessLoad');
    this.petName = name;
    alert('Pet Name is ' + name)
  };

  // METHODS ...
}
</script>

init.html 是:

<script>
function init() {
  console.log('Initialization');
  var cat = new Pet();
}
</script>

index.html 包含:

<body onload=init()>
  ...

在浏览器中打开 index.html 后,我在控制台中看到:

Initialization
Creating new Pet
Loading Pet Name from storage...

但是没有“run onSuccessLoad”。

在 Google Script 控制台中,我们可以看到:“客户询问宠物名称”。一切正常,但 onSuccessLoad 函数没有运行。

如果在 Pet.html 中我们替换

google.script.run.withSuccessHandler(onSuccessLoad).loadPetName();

google.script.run.withSuccessHandler(console.log('SuccessHandler fired')).loadPetName();

我们将在控制台中看到:“SuccessHandler 已触发”。

我的问题在哪里?

谢谢!

【问题讨论】:

    标签: javascript html google-app-engine web-applications


    【解决方案1】:

    我发现了一个错误……天哪!

    此代码不起作用:

    google.script.run.withSuccessHandler(onSuccessLoad).loadPetName();
    
    var onSuccessLoad = function(name) {
      console.log('run onSuccessLoad');
      this.petName = name;
    };
    

    但是这段代码可以正常工作:

    var onSuccessLoad = function(name) {
      console.log('run onSuccessLoad');
      this.petName = name;
    };
    
    google.script.run.withSuccessHandler(onSuccessLoad).loadPetName();
    

    但是为什么呢?! (抱歉这个愚蠢的问题)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 2012-06-05
      • 2011-11-09
      • 2019-03-17
      • 2013-08-01
      • 1970-01-01
      相关资源
      最近更新 更多