傳送門: 柏鏈項目學院html
當咱們在前端頁面調用合約時發現有些數據不會當即返回,這時還須要再調用更新數據的函數。那麼這樣的方法使用起來很是不便,監聽event就能夠很好的解決這樣的問題,下面咱們來看看如何監聽event。如下內容基於web3.js1.0版本,版本不一樣可能會代碼差別。前端
geth --datadir ./data --networkid 15 --port 30303 --rpc --rpcaddr 0.0.0.0 --rpcport 8545 --rpcvhosts "*" --rpcapi 'db,net,eth,web3,personal' --rpccorsdomain "*" --ws --wsaddr "localhost" --wsport "8546" --wsorigins "*" --nat "any" --nodiscover --dev --dev.period 1 console 2> 1.log
--ws --wsaddr "localhost" --wsport "8546" --wsorigins "*"
pragma solidity ^0.4.24; contract Map3 { mapping(string => string) map; event orderlog(string indexed action, string indexed key, string value); function getvalue(string key) public constant returns (string) { return map[key]; } function setvalue(string key, string value) public { emit orderlog("setvalue haha", key, value); map[key] = value; } }
var Web3 = require("web3") var web3; if (typeof web3 !== 'undefined') { web3 = new Web3(web3.currentProvider); } else { web3 = new Web3(new Web3.providers.WebsocketProvider("ws://127.0.0.1:8546")); } var contractAbi = [ { "constant": false, "inputs": [ { "name": "key", "type": "string" }, { "name": "value", "type": "string" } ], "name": "setvalue", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [ { "name": "key", "type": "string" } ], "name": "getvalue", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "action", "type": "string" }, { "indexed": true, "name": "key", "type": "string" }, { "indexed": false, "name": "value", "type": "string" } ], "name": "orderlog", "type": "event" } ]; var contractaAddress = "0x31bd7af45b90811f23fa748fbf1940dc8b3d9dcb"; MyContract = new web3.eth.Contract(contractAbi, contractaAddress); //console.log(MyContract.events.orderlog); var myEvent = MyContract.events.orderlog({ filter:{}, fromBlock: 0 }, function(error, event){}) .on('data', function(event){ console.log(event); // same results as the optional callback above }) .on('changed', function(event){ // remove event from local database }) .on('error', console.error); /* MyContract.getPastEvents('allEvents', { filter: {}, fromBlock: 0, toBlock: 'latest' }, function(error, events){ console.log(events); }) .then(function(events){ console.log(events) // same results as the optional callback above }); */
npm init -y npm install web3 --save node map_event.js
在remix中調用setvalue時的監聽效果
node
當合約被調用時,前端頁面須要當即更新數據,監聽event就能夠實現這樣的效果。git
Solidity Event是如何實現的:https://www.liangzl.com/get-article-detail-11825.htmlgithub