简体   繁体   English

当以太坊智能合约触发事件时如何获得通知

[英]How to get notified when an event triggers on ethereum smart contract

When someone makes a transfer from my account, an event gets trigger name 当有人从我的帐户转帐时,事件将获得触发名称

event Transfer(address indexed from, address indexed to, uint to)

Now I want to get notified when this event occurs on smart contract. 现在,我想在智能合约上发生此事件时得到通知。 I tried with difference things like filter, watch, subscription and etc. But nothing works as per need. 我尝试了一些不同的东西,例如过滤器,监视,订阅等。

I also have an another query What does filter, subscribe, and watch exactly do. 我还有另一个查询,“过滤”,“订阅”和“观看”到底是做什么的。 I am always getting confuse between these terms. 我总是对这些术语感到困惑。 Can someone give a clear idea. 有人可以给一个清晰的想法。

Note: I am using WEB3JS 1.0.0.26 version. 注意:我正在使用WEB3JS 1.0.0.26版本。

Here's a simple example for web3js 1.0.0.beta* : 这是web3js 1.0.0.beta*的简单示例:

function handler (event) {
   console.log(event.returnValues);
}

function errorCallback (err) {
   console.error(err);
}

let subscription = contractObj.events.TestEvent().subscription;
subscription.on('data', handler).on('error', errorCallback);

To unsubscribe: 退订:

subscription.unsubscribe(function (result) {
   console.log(result)
});

Example of usage in class: 在类中的用法示例:

class Listener {
  constructor(event, handler) {
    this.subscription = event;
    this.subscription.on('data', handler).on('error', this.errorCallback);
  }

  errorCallback(err) {
    console.log(err);
  }
}


class Test {
  constructor(contractObj) {
    this.contractObj = contractObj;
    this.createListener();
  }

  createListener() {
    let self = this;
    this.listener = new Listener(this.contractObj.events.TestEvent(), function (event) {
      self.returnValues = event.returnValues;
    });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM