Skip to content

Latest commit

 

History

History
347 lines (295 loc) · 10.2 KB

examples.md

File metadata and controls

347 lines (295 loc) · 10.2 KB
layout title order
default
Examples
3

The following examples demonstrate Javascript peer API usage and (protocol) messages. They actually run in your browser. You can edit them on codepen if desired. Most of them use the Jet Daemon hosted at nodejitsu with the Daemon URL: ws://jet.nodejitsu.com (Port 80). The nodejitsu Jet Daemon is public and you may notice activity of other peers "playing" with it.

Connect

This example creates a peer and reports back the connection status.

The most relevant code snippet is:

var peer = new jet.Peer({
      url: 'ws://jet.nodejitsu.com:80',
      onOpen: function() {}
    });
var connect = function(url) {
   try {
    $('#status').text('disconnected');
    // create a Jet Peer, providing the Jet (Daemon) Websocket URL
    var peer = new jet.Peer({
      url: url,
      onOpen: function() {
        $('#status').text('connected');
      },
    });
  } catch(err) {
    $('#status').text('error ' + err);
  }
};

// try to (re-)connect when button is clicked $('button').click(function(e) { connect($('input').val()); e.preventDefault(); });

// try to (re-)connect when input field changed $('input').change(function(e) { connect($('input').val()); });

See the Pen Jet Connect by Gerhard Preuss (@lipp) on CodePen.

<script async src="//codepen.io/assets/embed/ei.js"></script>

Add States

This example creates a Peer and adds two States with random. One, ignoring the Daemon response, the other one logging the Daemon response to console. The message traffic between the Daemon and the Peer is visible in the result window bottom.

The most relevant code snippet is:

// create read-only state (no set callback provided)
// ignore the Daemon response by leaving out the callback object.
// the request is a notification.
peer.state({
  path: 'foo',
  value: 123
});

// create writable state,
// provide callback object with error and success handlers.
// the Daemon will send a response, as the request is not a
// notification.
var bar = 'hello';
peer.state({
  path: 'bar',
  value: bar,
  set: function(newVal) {
      bar = newVal;
  }
  }, {
  success: function() {},
  error: function(err) {}
});
var connect = function(url) {
   try {
    $('#status').text('disconnected');
    // create a Jet Peer, providing the Jet (Daemon) Websocket URL
    var peer = new jet.Peer({
      url: url,
      onOpen: function() {
        $('#status').text('connected');
      },
      onSend: function(message) {
        addLogEntry('Out',message);
      },
      onReceive: function(message) {
        addLogEntry('In',message);
      }
    });
     var random = 'random' + new Date().getTime();
     // add as notification
     peer.state({
       path: random,
       value: 123
     });
 random = &#x27;random_2_&#x27; + new Date().getTime();
 // add as request
 peer.state({
   path: random,
   value: 123
 },{
   success: function() {
     console.log(&#x27;ok&#x27;);
   },
   error: function(err) {
     console.log(err);
   }
 });

} catch(err) { $('#status').text('error ' + err); } };

// try to (re-)connect when button is clicked $('button').click(function(e) { connect($('input').val()); e.preventDefault(); });

// try to (re-)connect when input field changed $('input').change(function(e) { connect($('input').val()); });

var off; var addLogEntry = function(direction, message) { var now = new Date().getTime(); if (!off) { off = now; } var tr = $('<tr></tr>'); tr.append('<td>' + (now-off) + '</td>'); tr.append('<td>' + direction + '</td>'); tr.append('<td>' + message + '</td>'); $('#log tbody').append(tr); };

See the Pen Jet Add State by Gerhard Preuss (@lipp) on CodePen.

<script async src="//codepen.io/assets/embed/ei.js"></script>

Fetch Simple

This examples creates a Peer, adds two States with random name ("random...") and fetches everything with a path starting with "random". The message traffic between the Daemon and the Peer is visible in the result window bottom. Compare the (fetch) id of the fetch message with the incoming messages' method field. The incoming messages can be considered Passive as they are Requests targeted at the Peer, embedding a Peer defined method field value.

This is the most relevant snippet:

// fetch and provide: 1) fetch rule, 2) callback for fetching
peer.fetch({path: {startsWith: 'random'}}, function(path, event, value){});
var connect = function(url) {
   try {
    $('#status').text('disconnected');
    // create a Jet Peer, providing the Jet (Daemon) Websocket URL
    var peer = new jet.Peer({
      url: url,
      onOpen: function() {
        $('#status').text('connected');
      },
      onSend: function(message) {
        addLogEntry('Out',message);
      },
      onReceive: function(message) {
        addLogEntry('In',message);
      }
    });
     var random = 'random' + new Date().getTime();
     // add as notification
     peer.state({
       path: random,
       value: 123
     });
 random = &#x27;random_2_&#x27; + new Date().getTime();
 // add as request
 peer.state({
   path: random,
   value: 123
 });

 peer.fetch({
   path: {
     startsWith: &#x27;random&#x27;
   }
 },function(path, event, value) {
   console.log(&#x27;fetch&#x27;, path, event, value);
 });

} catch(err) { $('#status').text('error ' + err); } };

// try to (re-)connect when button is clicked $('button').click(function(e) { connect($('input').val()); e.preventDefault(); });

// try to (re-)connect when input field changed $('input').change(function(e) { connect($('input').val()); });

var off; var addLogEntry = function(direction, message) { var now = new Date().getTime(); if (!off) { off = now; } var tr = $('<tr></tr>'); tr.append('<td>' + (now-off) + '</td>'); tr.append('<td>' + direction + '</td>'); tr.append('<td>' + message + '</td>'); $('#log tbody').append(tr); };

See the Pen Jet Fetch State by Gerhard Preuss (@lipp) on CodePen.

<script async src="//codepen.io/assets/embed/ei.js"></script>

Change State

This examples creates a Peer, adds a "ticker" States with random name (so that at least these State are available for fetching) and fetches everything with a path starting with "ticker". Every second the ticker value is incremented by one. The message traffic between the Daemon and the Peer is visible in the result window bottom.

This is the most relevant snippet:

var ticker = peer.state({
  path: 'ticker',
  value: 1
});

setInterval(function() {
  var old = ticker.value();
  ticker.value(++old); // post state change
}, 1000);
var tickTimer;
var connect = function(url) {
  try {
    $('#status').text('disconnected');
    // create a Jet Peer, providing the Jet (Daemon) Websocket URL
    var peer = new jet.Peer({
      url: url,
      onOpen: function() {
        $('#status').text('connected');
      },
      onSend: function(message) {
        addLogEntry('Out',message);
      },
      onReceive: function(message) {
        addLogEntry('In',message);
      }
    });
    var path = 'ticker_#' + new Date().getTime();
    // add as notification
    var ticker = peer.state({
      path: path,
      value: 1
    });
if (tickTimer) {
  clearInterval(tickTimer);
}
tickTimer = setInterval(function() {
  var old = ticker.value();
  ticker.value(++old);
}, 1000);

peer.fetch({
  path: {
    startsWith: &#x27;ticker_&#x27;
  }
},function(path, event, value) {
  // console.log(&#x27;fetch&#x27;, path, event, value);
});

} catch(err) { $('#status').text('error ' + err); } };

// try to (re-)connect when button is clicked $('button').click(function(e) { connect($('input').val()); e.preventDefault(); });

// try to (re-)connect when input field changed $('input').change(function(e) { connect($('input').val()); });

var off; var addLogEntry = function(direction, message) { var now = new Date().getTime(); if (!off) { off = now; } var tr = $('<tr></tr>'); tr.append('<td>' + (now-off) + '</td>'); tr.append('<td>' + direction + '</td>'); tr.append('<td>' + message + '</td>'); $('#log tbody').append(tr); };

See the Pen Jet Change State by Gerhard Preuss (@lipp) on CodePen.

<script async src="//codepen.io/assets/embed/ei.js"></script>