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

发布了130 篇原创文章 · 获赞 103 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/xiaolinlife/article/details/90446779