Tuesday, July 18, 2017

Using cordova channel to handle javascript event

Cordova uses channel&subscribe to fire and handle event. This logic can also be used in application logic. The APIs are quite easy to understand, so using the APIs does not need to know the details of the implementation. Actually, the cordova channel&subscribe model can be used in a regular js file not be part of a cordova plugin.

The below is a sample to using cordova channel to create an event, subscribe to the event and fire the event.

In index.html
<button onclick="createevent()">create event</button>
<button onclick="subscribeevent()">subscribe event</button>
<button onclick="fireevent()">fire event</button>
<button onclick="unsubscribeevent()">unsubscribe event</button>



In js file
function createevent(sticky){
   var channel = cordova.require('cordova/channel');
   channel.createSticky('myevent');
}

function subscribeevent(event){
    var channel = cordova.require('cordova/channel');
    channel.myevent.subscribe(handler);
}

function handler(e){
    alert("event fired: " + e);
}

function fireevent(event){
    var channel = cordova.require('cordova/channel');
      channel.myevent.fire("my event obj");
}

1 comment:

  1. I have written a custom cordova plugin to listen sd card action. Its working only if I use

    channel.createSticky('onCordovaReady');
    channel.waitForInitialization('onCordovaReady');

    but all other plugins are thrwing error
    channel not ready

    ReplyDelete