Back in January this yr jQuery introduced a brand new plugins registry, so now appeared like a good time to jot down a tutorial combining constructing a jQuery plugin with my ardour – realtime net applied sciences.
Realtime net applied sciences make it very easy so as to add reside content material to beforehand static internet pages. Live content material can carry a web page alive, retain customers and take away the necessity for them to refresh the web page periodically. Realtime updates are typically achieved by connecting to a supply of information, subscribing to the information you need to add to the web page after which updating the web page as the information arrives. But why can’t this be achieved by way of merely marking up a web page to establish what information needs to be proven and the place? Well, perhaps it may!
jQuery’s tagline is write much less, do extra. The tagline for the jQuery Realtime plugin that we’re going to construct on this tutorial shall be write much less, do realtime.
In this tutorial we’ll create a jQuery plugin that makes it very easy so as to add realtime content material to a web page by merely including some markup. First, we’ll cowl methods to use a service known as Pusher to subscribe to realtime knowledge. Then we’ll outline a means of marking up an HTML5 doc with ‘information-*’ attributes in a approach which might then be queried by our realtime jQuery plugin and transformed to realtime knowledge subscriptions. Finally, we’ll create the jQuery plugin which is able to use the attributes to subscribe to information and immediately show updates throughout the web page.
If you simply need to dive straight in you may view a demo in motion or you’ll be able to download thecode and begin hacking.
PUSHER BASICS
Pusher is a hosted service that makes it simple so as to add realtime content material and interactive experiences to net and cell apps. Here we’re going to easily join, subscribe to some knowledge after which replace a web page when the information is available in.
To reveal this create a file known as ‘instance.html’ and embrace the Pusher JavaScript library from the Pusher CDN. We know we’re going to make use of jQuery P.zero.zero so we also needs to embrace that now:<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-H">
<title>Creating a realtime jQuery plugin | Webdesigner Depot</title>
</head>
<physique>
<script src="http://js.pusher.com/P.zero/pusher.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/P.zero.zero/jquery.min.js"></script>
</physique>
</html>
Connect
Once the Pusher JavaScript library has been included we will hook up with Pusher by creating a brand new ‘Pusher’ occasion and passing in an software key. Create an extra ‘<script>’ tag beneath the jQuery embrace as follows:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-H">
<title>Creating a realtime jQuery plugin | Webdesigner Depot</title>
</head>
<physique>
<script src="http://js.pusher.com/P.zero/pusher.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/P.zero.zero/jquery.min.js"></script>
<script>
( perform( $ )
var pusher = new Pusher( '7b9f9ade2135118a915b' );
)( jQuery );
</script>
</physique>
</html>
Note: For the tutorial we’ll use an utility key that I’ve offered however in your personal purposes you’ll want to enroll to Pusher to get your personal.
You can examine that you simply’re related in three other ways. You can do it manually by checking the Pusher Debug Console, if you happen to load the web page with the Pusher Debug Console open you’ll see the connection logged. The Pusher JavaScript library offers a log propertywhich you can assign a operate to after which you may manually verify to ensure a connection has been established by inspecting the browser’s JavaScript console. Or you may verify the connection programmatically by monitoring the connection state of the Pusher occasion.

The Pusher Debug console
Whatever you select to do, you’ll now be linked.
Subscribe
Pusher makes use of the Publish & Subscribe pattern, so to obtain knowledge from Pusher you first must subscribe to it. Pusher makes use of the time period channels with regards to subscriptions, so let’s subscribe to a channel known as ‘check-channel’.
<script> ( operate( $ )
var pusher = new Pusher( '7b9f9ade2135118a915b' );
var channel = pusher.subscribe( 'take a look at-channel' );
)( jQuery );
</script>
As with connection state, you may verify the standing of a subscription in just a few methods; utilizing the Pusher Debug Console, by checking the output from ‘Pusher.log’ or by binding to the‘pusher:subscription_succeeded’ event.

Using Pusher.log to log pusher-js library info
Bind to occasions
Those of you who use jQuery will most likely be accustomed to the concept of binding to occasions. jQuery does present shortcuts for some occasions (e.g. ‘.onclick( <operate> )’) however you can too bind to occasions utilizing ‘.bind(<kind>, <perform>)’. Pusher follows this conference and you may bind to occasions to be told when one thing updates; when the connection state adjustments, when a subscription succeeds or when new utility knowledge is acquired. For this instance, and with the realtime plugin, we’re primarily within the latter.
Let’s bind to a ‘check-occasion’ on the channel:
<script>
( operate( $ )
var pusher = new Pusher( '7b9f9ade2135118a915b' );
var channel = pusher.subscribe( 'check-channel' );
channel.bind( 'check-occasion', handleEvent );
perform handleEvent( information )
console.log( 'in handleEvent:' );
console.log( information );
)( jQuery );
</script>
When binding to an occasion you merely determine the occasion by title and cross in a reference to a operate that might be referred to as when that occasion happens (is triggered) on the channel.
If you have got a Pusher account you’ll be able to take a look at that the ‘handleEvent’ perform is known as by utilizing thePusher Event Creator; enter ‘check-channel’ because the channel identify, ‘check-occasion’ because the occasion title and a few knowledge (‘ “some” : “knowledge” ’) into the occasion knowledge textual content space and click on the submit button. You’ll then see the debug info, together with the information you entered, logged to the JavaScript console.

Triggering an occasion from the Pusher Event Creator and logging it within the JavaScript console
Since the realtime jQuery plugin that we’re constructing doesn’t publish (set off) information (it simply consumes it) we gained’t cowl that right here. But if you happen to’re all in favour of discovering out extra checkout the Pusher server docs.
Displaying realtime updates
The subsequent factor to contemplate is displaying the realtime knowledge updates to the person.
For this we’ll want an concept for a easy utility; having labored in finance for just a few years I’m usually eager to keep away from any sort of monetary instance, however Bitcoin has made it fascinating and related. So, let’s create a quite simple show for exhibiting Bitcoin costs.
Note: We’re going to make use of some pretend knowledge. Let’s make certain this doesn’t end in extra Bitcoin panic promoting!
First, let’s create some HTML the place we’ll show the realtime costs. We can pre-populate the show with costs identified on the time the web page was loaded:
<h1>Bitcoin Fake Prices</h1>
<desk id="bitcoin_prices">
<thead>
<tr>
<th>
</th>
<th>Last</th>
<th>Low</th>
<th>High</th>
<th>Volume</th>
</tr>
</thead>
<tbody>
<tr>
<td>BTC/USD</td>
<td>sixty one.157 USD</td>
<td>fifty one USD</td>
<td>ninety five.713 USD</td>
<td>66271 BTC / 4734629 USD</td>
</tr>
</tbody>
</desk>
Let’s replace the JavaScript to subscribe to a extra appropriately named channel known as ‘btc-usd’ and bind to a ‘new-worth’ occasion:
<script>
( operate( $ )
var pusher = new Pusher( '7b9f9ade2135118a915b' );
var channel = pusher.subscribe( 'btc-usd' );
channel.bind( 'new-worth', handleEvent );
perform handleEvent( knowledge )
)( jQuery );
</script>
The ‘information’ despatched to the ‘handleEvent’ operate also needs to be in a extra applicable format – right here’s the JSON:
"final": "final worth",
"low": "low worth",
"excessive": "excessive worth",
"quantity": "quantity worth"
Now that we all know this we will change the ‘handleEvent’ perform to replace the suitable cell within the desk:
perform handleEvent( information )
var cells = $( '#bitcoin_prices tbody tr td' );
cells.eq( S ).textual content( information.final );
cells.eq( P ).textual content( information.low );
cells.eq( O ).textual content( knowledge.excessive );
cells.eq( F ).textual content( knowledge.quantity );
If you now set off a ‘new-value’ occasion on the ‘btc-usd’ channel, utilizing the JSON we outlined, the web page will replace to point out the brand new values.
There are methods of each making this code nicer and, because the web page grows to indicate extra knowledge, optimise issues. But, we’re going to make it in order that realtime knowledge might be added to the web page just by making use of markup.
Before we progress, let’s first add a little bit of styling to the instance. In the ‘<head>’ add the next CSS:
<fashion>
physique
font-household: "Helvetica Neue",Helvetica,Arial,sans-serif;
#bitcoin_prices
border-spacing: zero;
#bitcoin_prices thead
background-coloration: grey;
#bitcoin_prices tbody tr:nth-baby(odd)
background-shade: #fff;
#bitcoin_prices tbody tr:nth-baby(even)
background-shade: #ccc;
#bitcoin_prices tbody tr td:nth-little one(S)
background-colour: yellow;
#bitcoin_prices td
padding: 4px 10px;
</fashion>
As you may undoubtedly inform, I’m no designer. So please be happy to enhance on this.

The “styled” Bitcoin Fake Prices software
Finally, restructure issues so we’re arrange for constructing the plugin.
- Create an ‘examples’ listing and inside it a ‘bitcoin’ listing.
- Move the ‘instance.html’ file to ‘examples/bitcoin’, rename it ‘index.html’.
- Create a ‘src’ listing on the prime-degree of the mission.
The listing construction ought to now look as follows:
/
examples/
bitcoin/
index.html
src/
We’re now able to outline our realtime markup and construct the realtime jQuery plugin.
REALTIME MARKUP
The very first thing to focus on is that this isn’t a brand new thought — I labored for a corporation referred to as CaplinSystems and in 2001 they’d a expertise generally known as RTML that allow you to markup a web page in order that realtime updates might be utilized. The goal right here is to make use of jQuery to parse the web page after which interpret the markup, leading to subscriptions, occasion binding and in the end dwell content material being added to the web page.
For our plugin we’ll use HTML5’s data–* attributes. These attributes don’t straight have an effect on the format or presentation of the web page in order that they’re an important selection for our realtime markup.
The questions we now must reply concerning the markup are:
- Where can we put the Pusher software key?
- How will we determine what channels must be subscribed to?
- How can we determine the occasions that ought to be certain to on a channel?
- How do we all know what knowledge to show within the web page, and the place?
The first one is comparatively straightforward. Since we have to embrace our plugin JavaScript file we will add a ‘knowledge-rt-key’ attribute to the ‘<script>’ component for the plugin embrace and make the worth our software key.
Channel subscriptions could be recognized by a ‘information-rt-channel’ attribute. This will imply that the aspect that the attribute is on and all youngsters are associated to this subscription.
Event binding may be achieved utilizing a ‘information-rt-occasion’ attribute the place the ingredient with the attribute, and all youngsters are associated to this occasion.
The values to be extracted from the occasion information may be indicated by a ‘information-rt-worth’ attribute.
Putting this all collectively, replace the Fake Bitcoin Prices markup to look as follows:
<h1>Bitcoin Fake Prices</h1>
<desk id="bitcoin_prices">
<thead>
<tr>
<th></th>
<th>Last</th>
<th>Low</th>
<th>High</th>
<th>Volume</th>
</tr>
</thead>
<tbody>
<tr information-rt-channel="btc-usd"
information-rt-occasion="new-worth">
<td>BTC/USD</td>
<td information-rt-worth="final">sixty one.157 USD</td>
<td information-rt-worth="low">fifty one USD</td>
<td information-rt-worth="excessive">ninety five.713 USD</td>
<td knowledge-rt-worth="quantity">66271 BTC / 4734629 USD</td>
</tr>
</tbody>
</desk>
<script src="path/to/jquery.realtime.js"
knowledge-rt-key="7b9f9ade2135118a915b"></script>
So, from the script tag you may see we’re going to connect with Pusher utilizing the important thing recognized by ‘information-rt-key’. We’re going to subscribe to the ‘btc-usd’ channel and bind to the ‘new-value’ occasion. When an occasion is acquired we’re going to replace the suitable desk cell based mostly on the worth indicated by ‘information-rt-worth’; if the worth of the attribute is ‘final’ then the worth of the ‘final’ property is taken from the obtained ‘information’ object and displayed within the cell.
Hopefully what we are attempting to attain is now fairly clear. Let’s begin taking a look at the way to create a jQuery plugin.
jQuery plugin fundamentals
The jQuery plugin creation docs are fairly good so I gained’t go into the small print right here. We’ll merely consider constructing the performance that we’d like in our plugin.
Before we write any code we must always contemplate how we wish to use the plugin. The regular method a plugin capabilities is that you simply use jQuery to question the web page, and you then execute the plugin performance in opposition to the matched components.
$( 'a' ).toggle();
The above code would discover all ‘<a>’ components after which execute the ‘toggle()’ performance on them — in all probability hiding all anchors, so not probably the most helpful instance you’ll ever see.
So, let’s say we might wish to use the plugin as follows:
<script>
$( perform()
$( '#bitcoin_prices' ).realtime();
);
</script>
Let’s take a look at creating the anticipated performance.
A realtime plugin
First, create a ‘realtime.jquery.js’ file throughout the ‘src’ listing. This file will include the plugin performance. Then add the next to the file as the place to begin of our plugin:
( operate( $)
$.fn.realtime = perform()
console.log( 'realtime!' );
console.log( $( this ).html() );
;
( jQuery ) );
We may even check this out now. In ‘examples/bitcoin/index.html’ take away the instance plugin ‘<script>’ tag and discover the one beneath the jQuery embody and change it with a ‘<script>’ tag which incorporates the brand new ‘realtime.jquery.js’ file (don’t overlook the ‘knowledge-rt-key’ attribute) and a script block which executes the ‘realtime()’ plugin on the ‘bitcoin_prices’ desk:
<script src="//ajax.googleapis.com/ajax/libs/jquery/B.N.M/jquery.min.js"></script>
<script src="../../jquery.realtime.js"
information-rt-key="7b9f9ade2135118a915b"></script>
<script>
$( operate()
$( '#bitcoin_prices' ).realtime();
);
</script>
If you refresh the web page now you’ll see ‘realtime!’ logged to the JavaScript console together with the HTML from the ‘<desk>’ aspect. This is nice because it means the plugin is working; we’re efficiently executing our plugin performance on the desk recognized by the selector we handed in to jQuery.

jQuery plugins and third celebration libraries
Our realtime plugin depends on a third social gathering library — the Pusher JavaScript library. For the second we’ve got it included statically inside our HTML, however we don’t wish to make that a requirement to make use of the plugin. So, let’s dynamically load it. jQuery supplies a manner of simply doing this within the type of the ‘.getScript()’ operate.
So, let’s load model P.zero of the Pusher JavaScript library. We’ll load the HTTPS hosted model in order that browsers are pleased if our plugin is used on a web page served over HTTPS (Chrome already blocks makes an attempt to load HTTP hosted scripts in HTTPS pages and Firefox will do inFirefox 23). I’m going to wrap loading the library in a operate as follows:
var libraryLoaded = false;
operate loadPusher()
$.getScript( "https://d3dy5gmtp8yhk7.cloudfront.web/P.zero/pusher.min.js" )
.accomplished( pusherLoaded )
.fail( operate( jqxhr, settings, exception )
console.log( 'oh oh! ' + exception );
);
perform pusherLoaded( script, textStatus )
libraryLoaded = true;
console.log( 'pusher.min.js loaded: ' + textStatus );
loadPusher();
If you reload the web page the ‘pusher.min.js loaded: success’ message will probably be logged to the console.
As we’re growing it’s all the time good to have a method of logging data so at this level let’s create a easy ‘log’ operate that we will use which simply logs to the console. We’ll use this now and likewise use it for logging Pusher occasions. The full supply of the plugin is now:
( perform( $ )
operate log( msg )
console.log( msg );
var libraryLoaded = false;
perform loadPusher()
$.getScript( "https://d3dy5gmtp8yhk7.cloudfront.web/P.zero/pusher.min.js" )
.achieved( pusherLoaded )
.fail( operate( jqxhr, settings, exception )
log( 'oh oh! ' + exception );
);
perform pusherLoaded( script, textStatus )
libraryLoaded = true;
Pusher.log = log;
log( 'pusher.min.js loaded: ' + textStatus );
$.fn.realtime = perform()
log( 'realtime!' );
log( $( this ).html() );
;
loadPusher();
( jQuery ) );
You’ll additionally discover that we’ve assigned the ‘log’ perform to the ‘Pusher.log’ property. This means we will see the inner Pusher library logging in addition to our personal.
When ought to we join?
Due to the asynchronous nature of loading the library we will’t assure that it’s going to have loaded when our plugin is named into motion. Unfortunately this makes issues a bit extra advanced than is good however we’ll attempt to clear up it in as easy a approach as potential.
We have to examine to see if the library has loaded — therefore the ‘libraryLoaded’ flag — and act appropriately; if the library has loaded we are able to join, if it hasn’t we have to queue the execution till it does. Because of this it makes extra sense to solely create the Pusher occasion after we actually need it, which is after we truly need to subscribe to information.
Let’s take a look at how we are able to try this:
var pending = [];
operate pusherLoaded( script, textStatus )
libraryLoaded = true;
whereas( pending.size !== zero )
var els = pending.shift();
subscribe( els );
operate subscribe( els )
$.fn.realtime = operate()
var els = this;
if( libraryLoaded )
subscribe( els );
else
pending.push( els );
;
When the plugin is named we test the ‘libraryLoaded’ flag to see if the Pusher JavaScript library has been loaded. If it has we’re good to go and we will subscribe. If it’s nonetheless pending then we have to queue up the subscriptions. We do that by pushing the jQuery assortment (‘els’) onto a ‘pending’ array.
Now, join
Now that we all know that the Pusher JavaScript library has loaded and that the web page needs to subscribe to knowledge we will create our ‘Pusher’ occasion. Because we solely need one ‘Pusher’ occasion per web page we’re going to observe the Singleton pattern and have a ‘getPusher()’:
var pusher;
operate getPusher()
if( pusher === undefined )
var pluginScriptTag = $("script[src$='jquery.realtime.js']");
var appKey = pluginScriptTag.attr("knowledge-rt-key");
pusher = new Pusher( appKey );
return pusher;
This perform grabs the plugin script tag by on the lookout for a tag with a ‘src’ attribute that ends with ‘jquery.realtime.js’, after which will get the worth of the ‘information-rt-key’ attribute. It then creates a brand new ‘Pusher’ occasion, passing in the important thing. As mentioned earlier, creating a brand new ‘Pusher’ occasion leads to a connection to the supply of our information being established.
Subscribe
We can now use the ‘getPusher()’ operate anytime we need to entry the ‘Pusher’ occasion. In our case we wish to use it after we parse the weather to find out subscriptions.
Update the placeholder ‘subscribe’ perform and add the extra features proven beneath:
perform subscribe( els )
var channelEls = els.discover( "*[data-rt-channel]" );
log( 'discovered ' + channelEls.measurement() + ' channels' );
channelEls.every( subscribeChannel );
operate subscribeChannel( index, el )
el = $( el );
var pusher = getPusher();
var channelName = el.attr( 'knowledge-rt-channel' );
var channel = pusher.subscribe( channelName );
operate discover( els, selector )
var topLevelEls = els.filter( selector );
var childEls = els.discover( selector );
return topLevelEls.add( childEls );
The ‘discover’ perform is a utility operate to get any parts from an present assortment that match a given selector utilizing ‘.filter()’, together with any descendants of the weather utilizing ‘.find()’. We use this perform to search out any parts marked as much as signify channel subscriptions (‘knowledge-rt-channel’ attribute) and for every we then name ‘subscribeChannel’. This operate extracts the identify of the channel to be subscribed to and makes use of the worth in calling ‘pusher.subscribe( channelName )’ to really subscribe to the channel.
Bind
We then want to seek out any components marked as much as signify occasions (‘knowledge-rt-occasion’ attribute) to be certain to:
perform subscribeChannel( index, el )
el = $( el );
var pusher = getPusher();
var channelName = el.attr( 'knowledge-rt-channel' );
var channel = pusher.subscribe( channelName );
var eventEls = discover( el, '*[data-rt-event]' );
log( 'discovered ' + eventEls.measurement() + ' occasions' );
eventEls.every( perform( i, el)
bind( el, channel );
);
perform bind( el, channel )
el = $( el );
var eventName = el.attr( 'information-rt-occasion' );
channel.bind( eventName, perform( knowledge )
displayUpdate( el, information );
);
perform displayUpdate( el, information )
For every occasion component we discover name our personal ‘bind’ operate which binds to the occasion on the channel utilizing ‘channel.bind( eventName, eventHandler )’. The occasion handler perform is a small closure which permits us to cross the information replace, when acquired, and the occasion factor to a ‘displayUpdate’ operate.
If we run this now we are able to see from the logging that a connection is being established, we’re discovering one channel and subscribing to it, and discovering one occasion to bind to.

jQuery realtime markup discovering channel subscription and occasion binding
Display the replace
When the occasion handler is known as we have to discover the identify of every property on the ‘information’ object (e.g. final, low, excessive and quantity) despatched with the replace and discover any parts which might be marked with that identify.
perform bind( el, channel )
el = $( el );
var eventName = el.attr( 'knowledge-rt-occasion' );
channel.bind( eventName, perform( knowledge )
displayUpdate( el, knowledge );
);
operate displayUpdate( el, knowledge )
for( var propName in knowledge )
var worth = information[ propName ];
var updateEls = discover( el, '*[knowledge-rt-worth="' + propName + '"]' );
log( 'discovered ' + updateEls.measurement() + ' "' + propName + '" parts to replace' );
updateEls.textual content( worth );
We loop over the ‘knowledge’ object and get the identify of every property. Once we all know the property title (‘propName’) we will discover the related parts and replace their textual content worth with the brand new knowledge worth. For now we’re not going to assist objects with any form of hierarchy — we simply need one stage of key and worth pairs.
If you now refresh the web page and set off an occasion from the Pusher Event Creator the brand new information will likely be immediately displayed inside the web page.
Have you labored with a reside knowledge service? What classes did you study? Let us know within the feedback.
Featured picture/thumbnail, live data image by way of Shutterstock.
Leave a Comment