【问题标题】:Running code before and after each Method call in Meteor在 Meteor 中的每个方法调用之前和之后运行代码
【发布时间】:2019-01-10 04:07:10
【问题描述】:

我正在运行几个方法调用,它们需要向最终用户显示加载模式并在方法返回结果时将其隐藏。我正在寻找一种方法来为每个方法运行此调用前代码和调用后代码,而无需重复代码。

swal({
  title: "Saving...",
  onBeforeOpen: () => swal.showLoading()
});
Meteor.call("method", {/*params*/}, (err, res) => {
 //Do something
 swal.hide();
});

我希望能够运行这 2 个 swal 代码,而无需在每次调用中编写该代码。 有什么方法可以配置 Meteor.call 在调用方法之前和之后做一些事情吗?

【问题讨论】:

    标签: javascript meteor client-side meteor-methods


    【解决方案1】:

    您可以将代码抽象为一个包装函数,接受您的方法名称、参数和回调函数作为参数:

    const call = ({ title, name, params, callback }) => {
     swal({
      title: title,
      onBeforeOpen: () => swal.showLoading()
     });
     Meteor.call(name, params, (err, res) => {
       callback(err, res);
       swal.hide();
     });
    }
    

    请注意,callback 不是“真实”回调,而只是放在语句中并从“真实”回调本身接收参数作为参数。

    使用方法例如这样:

    call({ 
      title: 'Saving...', 
      name: 'method', 
      params: {/*params*/}, 
      callback: (err, res) => {
        console.log('I am executed before hide');
      }
    });
    

    如果你非常需要这个功能,你可以把它放在一个自己的文件中,并使用export 使其可用于其他文件/模块。

    【讨论】:

      猜你喜欢
      • 2014-05-02
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多