簡體   English   中英

自定義類的服務器端 onchange 事件

[英]Server side onchange event for custom class

如果我在 Google Apps Script 中創建一個自定義類並將其分配給一個變量,我可以創建一個服務器端 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);

沒有這樣的處理程序。 但是您可以使用代理來攔截所有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
 <!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM