【问题标题】:rule engine function inside Meteor bindEnvironment losing its this objectMeteor bindEnvironment 中的规则引擎函数丢失了它的 this 对象
【发布时间】:2017-08-11 08:10:00
【问题描述】:
var process_request_rule = [
  {
    "name": "rule-name",
    "condition": Meteor.bindEnvironment(function (R) {
      R.when(this.request.type == 'some-type');
    })
  }];

在上面的代码中,this.request 变得未定义,因为 this 指向 Meteor 对象而不是函数对象。研究后知道使用箭头函数可能会解决问题。尝试使用它,如下所示。

var process_request_rule = [
  {
    "name": "rule-name",
    "condition": Meteor.bindEnvironment((R) => {
      R.when(this.request.type == 'some-type');
     })
  }];

还是不行,请帮我绑定this对象

【问题讨论】:

  • 如果您使用的是Meteor.bindEnvironment,您希望在函数的this 中出现什么?
  • this 指的是当前正在执行的规则的事实。 PS:在 Meteor 应用程序中使用 npm node-rules 参考节点规则:npmjs.com/package/node-rules

标签: javascript meteor rule-engine


【解决方案1】:

您可以使用Meteor.bindEnvironment 删除,也可以只使用传递给condition 回调的第二个参数——它与假定的this 相同。 https://github.com/mithunsatheesh/node-rules/blob/master/lib/node-rules.js#L94

类似这样的:

var process_request_rule = [
  {
    "name": "rule-name",
    "condition": Meteor.bindEnvironment(function(R, session) {
      R.when(session.request.type == 'some-type');
     })
  }];

【讨论】:

  • 我不能放弃使用Meteor.bindEnvironment,因为我需要在 Meteor 中进行回调,否则我会错误地说 can't wait without a fiber。这里的会话是什么?
  • 将作为this 绑定到此条件函数的同一对象。您可以将其重命名为 self_this 以避免混淆:)
猜你喜欢
  • 2012-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-07
  • 2012-09-01
  • 1970-01-01
相关资源
最近更新 更多