cryptozombies合约7

我们的合约几乎就要完成了!让我们加上一个事件.

事件 是合约和区块链通讯的一种机制。你的前端应用"监听"某些事件,并做出反应。

例子:

// 这里建立事件

dart 复制代码
event IntegersAdded(uint x, uint y, uint result);

function add(uint _x, uint _y) public {
  uint result = _x + _y;
  //触发事件,通知app
  IntegersAdded(_x, _y, result);
  return result;
}

你的 app 前端可以监听这个事件。JavaScript 实现如下:

c 复制代码
YourContract.IntegersAdded(function(error, result) {
  // 干些事
})

实战演习

我们想每当一个僵尸创造出来时,我们的前端都能监听到这个事件,并将它显示出来。

1。 定义一个 事件 叫做 NewZombie。 它有3个参数: zombieId (uint), name (string), 和 dna (uint)。

2。 修改 _createZombie 函数使得当新僵尸造出来并加入 zombies数组后,生成事件NewZombie。

3。 需要定义僵尸id。 array.push() 返回数组的长度类型是uint - 因为数组的第一个元素的索引是 0, array.push() - 1 将是我们加入的僵尸的索引。 zombies.push() - 1 就是 id,数据类型是 uint。在下一行中你可以把它用到 NewZombie 事件中。

dart 复制代码
pragma solidity ^0.4.19;

contract ZombieFactory {

    // 这里建立事件
    event NewZombie(uint zombieId, string name, uint dna);

    uint dnaDigits = 16;
    uint dnaModulus = 10 ** dnaDigits;

    struct Zombie {
        string name;
        uint dna;
    }

    Zombie[] public zombies;

    function _createZombie(string _name, uint _dna) private {
        uint id = zombies.push(Zombie(_name, _dna)) - 1;
        // 这里触发事件
        NewZombie(id, _name, _dna);
    }

    function _generateRandomDna(string _str) private view returns (uint) {
        uint rand = uint(keccak256(_str));
        return rand % dnaModulus;
    }

    function createRandomZombie(string _name) public {
        uint randDna = _generateRandomDna(_name);
        _createZombie(_name, randDna);
    }

}
相关推荐
链上Sniper19 小时前
Python 区块链开发实战:从零到一构建智能合约
开发语言·网络·python·架构·区块链·php·智能合约
姜家志21 小时前
AI+去中心化=下一波生产力革命(2)
web3·区块链
链上Sniper1 天前
区块链+AI融合实战:智能合约如何结合机器学习优化DeFi风控?
架构·区块链
全干engineer1 天前
web3-Remix部署智能合约到“荷兰式”拍卖及以太坊gas费机制细讲
web3·区块链·智能合约
链上Sniper1 天前
智能合约安全漏洞解析:从 Reentrancy 到 Integer Overflow
开发语言·网络·架构·区块链·php·智能合约
FakeOccupational1 天前
【p2p、分布式,区块链笔记 MESH】 论文阅读 Thread/OpenThread Low-Power Wireless Multihop Net
分布式·区块链·p2p
全干engineer1 天前
web3-以太坊智能合约基础(理解智能合约Solidity)
web3·区块链·智能合约
穗余1 天前
WEB3——开发者怎么查看自己的合约日志记录
web3·区块链
链上Sniper1 天前
高并发区块链系统实战:从架构设计到性能优化
开发语言·网络·python·性能优化·架构·区块链·php
链上Sniper1 天前
NFT 市场开发:基于 Ethereum 和 IPFS 构建去中心化平台
开发语言·网络·架构·去中心化·区块链·php