ionic3之Events的学习

最近在做项目的时候,看到同事在用Events,之前没怎么用过,对这块也不了解,查阅之后发现Events还是挺有用的,简单总结一下。订阅-发布。
先看一下Events的定义:
官网是这样说的

Events is a publish-subscribe style event system for sending and responding to application-level events across your app.
Events是一个发布 - 订阅式事件系统,用于在应用程序中发送和响应应用程序级别的事件。可以理解为:发布一个事件之后,可以将这个事件广播到整个工程的任何一个地方,只需要订阅就可以获取到传过来的值。
ionic Events 官网链接地址
具体应用如下:

1.发布事件
在第一个页面中发布一个事件。
需要导入 Events 依赖包

import { Events } from 'ionic-angular';

// first page (publish an event when a user is created)
constructor(public events: Events) {}
createUser(user) {
  console.log('User created!')
  this.events.publish('user:created', user, Date.now());
}

方法说明:
publish(topic, eventData)
Publish an event to the given topic. 发布一个事件到给定的主题。
参数名----------类型----------详细的解释
Param----------Type----------Details
topic------------string---------the topic to publish to
eventData-----any-----------the data to send as the event

2.订阅事件
第二个页面中订阅事件,并且获取到 第一个节目上面的数据值

// second page (listen for the user created event after function is called)
constructor(public events: Events) {
  events.subscribe('user:created', (user, time) => {
    // user and time are the same arguments passed in `events.publish(user, time)`
    console.log('Welcome', user, 'at', time);
  });
}

方法说明:
subscribe(topic, handler)
Subscribe to an event topic. Events that get posted to that topic will trigger the provided handler.
订阅事件的主题,事件将触发它提供的方法。
参数名----------类型----------详细的解释
Param----------Type----------Details
topic------------string---------the topic to publish to
handler-----function-----------the event handler

3.取消订阅
unsubscribe(topic, handler)
Unsubscribe from the given topic. Your handler will no longer receive events published to this topic.
取消订阅的主题,不再接收publish到主题事件。
unsubscribe()返回值为 true,就表示移除成功。
参数名----------类型----------详细的解释
Param----------Type----------Details
topic------------string---------the topic to unsubscribe from
handler-----function-----------the event handler

Returns:
true if a handler was removed

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值