<p>This is an example used by a post on my blog. <a href='http://oli.me.uk/2013/06/05/implementing-a-message-bus-in-javascript/'>Implementing a message bus in JavaScript.</a></p>
<hr />
<input type='text' id='value' placeholder='Type here, then hit enter...' />
<button id='update'>Update</button>
<p><span id='count'>0</span> value(s) in the message bus. Click update to render them.</p>
<ul id='list'></ul>
JavaScript
var messages = [];
var input = document.getElementById('value');
var list = document.getElementById('list');
var updateButton = document.getElementById('update');
var count = document.getElementById('count');
input.addEventListener('keydown', function (e) {
if (e.keyCode === 13) {
messages.push({
type: 'input',
value: e.target.value
});
e.target.value = '';
updateCount();
}
});
updateButton.addEventListener('click', function () {
clearMessageBus();
updateCount();
});
function clearMessageBus() {
var message;
while (message = messages.pop()) {
if (message.type === 'input') {
appendValueToList(message.value);
}
}
}
function appendValueToList(value) {
var el = document.createElement('li');
el.textContent = value;
list.appendChild(el);
}
function updateCount() {
count.textContent = messages.length;
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.