本文介紹通訊類WVStandardEventCenter相關的JS API,供您建立H5端應用或者小程式時參考。通訊類WVStandardEventCenter的JS API提供H5端向Native端發送事件的能力。
WVStandardEventCenter.postNotificationToNative
H5端向Native端發送事件,具體的事件名稱可以是與Native業務方商議一致的任意名稱。
iOS事件監聽用法
使用標準的訊息中心監聽事件。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myEventListener) name:eventName object:nil]
- (void)myEventListener:(NSNotification *)notification {
// 事件參數可以從 notification.userInfo 中擷取。
}
Android事件監聽用法
@import android.taobao.windvane.service;
@import android.taobao.windvane.standardmodal
// 首先,需要自己實現監聽用的 Listener。
public class JsEventListener implements WVEventListener {
@Override
public WVEventResult onEvent(int id, WVEventContext ctx, Object... obj) {
// 所有事件均派發到這裡,WVEventId.H5TONATIVE_EVENT 表示 H5 發送過來的事件。
if (id == WVEventId.H5TONATIVE_EVENT) {
if (obj[0] instanceof String) {
String params = (String)obj[0];
// 這裡的 params 是包含 event 和 param 的 JSON String,需要自行還原序列化。
}
}
return null;
}
}
// 然後,註冊監聽器。
WVEventService.getInstance().addEventListener(new JsEventListener());
輸入參數
[
string]event:要發送的事件名稱。[
object]param:(可選)要發送的事件參數。
回調參數
無回調參數,如果成功蜂鳴,則進入success回調,否則進入failure回調。
var params = {
event: 'eventName',
param: {
// 事件要傳遞的資料。
}
};
window.WindVane.call('WVStandardEventCenter','postNotificationToNative', params, function(e) {
alert('success');
}, function(e) {
alert('failure: ' + JSON.stringify(e));
});