【问题标题】:Server side onchange event for custom class自定义类的服务器端 onchange 事件
【发布时间】:2020-10-02 15:17:42
【问题描述】:

如果我在 Google Apps 脚本中创建一个自定义类并将其分配给一个变量,我是否可以创建一个服务器端 onchange 事件以在值更改时做出反应?例如,类似:

    var Polygon = function(height, width) {
      this.height = height;
      this.width = width;
      this.save = function() { <code to draw the polygon here ...> };
    }
    Polygon.onchange = function() {
      currentPolygon = this.value;
      currentPolygon.draw();
    }
    var myPolygon = new Polygon(10, 12);
    myPolygon.height = 20; // triggers draw

或者,它必须包含在一个集合函数中吗?例如:

    var Polygon = function(height, width) {
      var myHeight = height;
      var myWidth = width;
      this.height = function() { return myHeight; }
      this.width = function() { return myWidth; }
      this.draw = function() { <code to draw the polygon here ...> };
      this.changeHeight = function(value) {
        myHeight = value;
        this.draw();
      }
      this.changeWidth = function(value) {
        myWidth = value;
        this.draw();
      }
    }
    var myPolygon = new Polygon(10, 12);
    myPolygon.changeHeight(20);

【问题讨论】:

    标签: javascript class google-apps-script events onchange


    【解决方案1】:

    没有这样的处理程序。但是您可以使用proxy 拦截所有set 调用:

    /*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
    
    const Polygon = function(height, width) {
      this.height = height;
      this.width = width;
      this.drawn = 0;
      this.draw = function() {
        this.drawn += 1;
      };
    };
    const PolygonOnchangeHandler = {
      set(target, prop, value) {
        Reflect.set(target, prop, value);//calls set
        Reflect.apply(target.draw, target, []);//calls draw
      },
    };
    const myPolygon = new Proxy(new Polygon(10, 12), PolygonOnchangeHandler);
    myPolygon.height = 20; // trigges draw
    console.log(myPolygon.drawn);//drawn once
    myPolygon.width = 5;
    console.log(myPolygon.drawn);//drawn twice
    &lt;!-- https://meta.stackoverflow.com/a/375985/ --&gt;    &lt;script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      • 2023-03-16
      • 1970-01-01
      相关资源
      最近更新 更多