在前端页面调用合约写入数据时不会立即返回结果,这时需要再调用获取数据的函数,使用起来非常不便,这时event就可以很好解决这样的问题。
合约代码:
声明event事件:
event Deposit(address indexed _from, bytes32 indexed _id, uint _value);
触发event事件:
emit Deposit(msg.sender, _id, msg.value);
pragma solidity >=0.6.0 <0.9.0;
contract Demo {
uint256 demoIndex = 0;
event DemoIndexInc(uint256 indexed index);
function getDemoIndex() public view returns (uint256) {
return demoIndex;
}
function incDemoIndex() public {
demoIndex = demoIndex+1;
emit DemoIndexInc(demoIndex);
}
}
H5代码:
订阅event事件:
<script src="./dist/web3.min.js"></script>
<script type="text/javascript">
const addEventWatchTx = async () => {
var web3 = new Web3(ethereum)
var metaTxContract = new web3.eth.Contract(MetaTxABI, contractAddr)
metaTxContract.events.DemoIndexInc({
filter:{},
fromBlock: 'latest'
}, function(error, event){})
.on('data', function(event){
console.log(event); // same results as the optional callback above
})
.on('changed', function(event){
console.log('emove event from local database');
})
.on('error', console.error);
}
</script>
使用Solidity事件(Event)优化前端交互体验
本文介绍了如何利用Solidity的事件(Event)机制改进前端调用智能合约后的数据获取流程。当在前端页面调用合约写入数据后,由于不会立即返回结果,可以订阅合约的事件来实现实时更新。例如,通过监听`DemoIndexInc`事件,可以在数据变化时获取最新值,提高用户体验。示例合约展示了声明和触发事件的方法,而H5代码则演示了如何订阅并处理这些事件。
3266

被折叠的 条评论
为什么被折叠?



