【问题标题】:How to tell if fluent method is the last to be called如何判断流利的方法是否是最后一个被调用的方法
【发布时间】:2015-10-15 17:44:55
【问题描述】:

我正在尝试为 JavaScript 项目创建类似 fluent 的 API。

目前我有这样的事情:

function Foo(a, b) {
   this.a = a;
   this.b = b;
   this.Set = function(attr, val) {
      this[attr] = val;
      return this;
   },
   this.refresh = function() {
      //do something
   }
};

这使我可以编写以下内容:

var foo = new Foo("Hello", "World");
// foo = { a : "Hello", b : "World" }
foo.Set("c", "!");
// foo = { a : "Hello", b : "World", c : "!" }
foo.Set(...);
//...

编写流畅的 API 的好处是菊花链方法调用,因此我可以更轻松、更易读地编写 foo.Set(...).Set(...).Set(...)

编写基本 API 没问题,但我想知道如何检测菊花链中的最后一个 Set 调用,因为在这个调用中我想调用 refresh

我想这样做是为了避免用户需要手动附加.refresh()

有没有人处理过这样的事情?

谢谢, erip

编辑

所需的伪代码效果:

function Foo(a, b) {
   this.a = a;
   this.b = b;
   this.Set = function(attr, val) {
      this[attr] = val;
      //if this Set is the last
         // return this.refresh();
      return this;
   },
   this.refresh = function() {
      //do something
   }
};

【问题讨论】:

  • 所以在foo.Set().Set().Set() 中,您希望前两个Set 调用返回this,但最后一个返回不同的东西?
  • @Oriol 如果可能的话,我希望最后一个Setvoid,基本上。
  • 你不能。如果你能找到一些技巧来完成这项工作,那可能是个坏主意!
  • @Evert 好的,我不确定是否有好的方法可以做到这一点。我必须添加文档,告诉用户忘记.refresh(),风险自负。
  • 我能想到的唯一方法是使用超时,您可以在每次调用 Set 方法时清除并重新启动。但是,循环不会等待超时完成。

标签: javascript fluent


【解决方案1】:

在对另一个答案的评论中,您说您希望保留相同的签名,但您可以通过允许可选的第三个参数来做到这一点,该参数进一步表达了刷新的意图,而不仅仅是一个简单的布尔值 @ 987654321@。用户仍然需要指示刷新(并且可能不小心在最后一个Set 以外的地方调用它),但它维护方法链。

function Foo(a, b) {
   this.a = a;
   this.b = b;
   this.Set = function(attr, val) {
      this[attr] = val;

      var cfg = arguments[2] || {};
      if (cfg.refresh) {
         this.refresh();
      }

      return this;
   },
   this.refresh = function() {
      console.log('inside this.refresh');
   }
};

var foo = new Foo();
foo.Set("what","ever")
   .Set("Hello","World")
   .Set("United","States", {refresh: true});

【讨论】:

    【解决方案2】:

    可能是这样的:

    function Foo(a, b) {
       this.a = a;
       this.b = b;
       this.Set = function(attr, val, isLast) {
          this[attr] = val;
          if(isLast) {
            this.refresh();
          }
       },
       this.refresh = function() {
          //do something
       }
    };
    
    foo.Set({})
    foo.Set({})
    foo.Set({}, true)
    

    【讨论】:

    • 如果可能,我想维护函数签名。
    • @erip 我认为这不可能,您的程序无法自动知道您是否调用了 Set 方法。你必须为它创建某种标识符......参数,函数调用等......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    相关资源
    最近更新 更多