1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="shortcut icon" href="favicon.ico" >
<meta property="fb:page_id" content="316663535020759" />
<meta name="title" content="Arbiter.js - A full-featured javascript pub/sub (Observer) implementation" />
<meta name="description" content="Arbiter.js is a light-weight, library-agnostic javascript implementation of the pub/sub pattern, written by Matt Kruse. It allows objects on your page to be de-coupled, and communicate with each other through messages. This leads to a cleaner, more easily understood design, and easier maintenance. " />
<link rel="image_src" type="image/gif" href="fb_share.gif" />
<meta property="og:image" content="http://arbiterjs.com/fb_share.gif"/>
<title>Arbiter.js - A full-featured javascript pub/sub (Observer) implementation by Matt Kruse</title>
<script src="jquery.js"></script>
<script src="Arbiter.js"></script>
<script>
$(function() {
$('#version').html( Arbiter.version );
$('#updated_on').html( Arbiter.updated_on );
});
</script>
<style>
* {
font-family:verdana,arial,sans-serif;
}
#wrapper {
width:850px;
text-align:left;
}
#license {
font-size:smaller;
font-style:italic;
}
.section {
margin-top:20px;
}
.section .title {
background-color:#669;
color:white;
padding:5px;
font-size:20px;
font-weight:bold;
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius:5px;
}
.download_wrapper {
float:right;
width:250px;
padding:20px 0 20px 20px;
background-color:white;
}
.download {
border:2px solid #343499;
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius:5px;
background-color:#CACAFC;
padding:5px;
}
.source {
margin-top:20px;
border:1px solid #ccc;
background-color:#eee;
padding:3px;
}
.code, .code * {
white-space:pre;
font-family:courier new;
font-size:12px;
overflow:auto;
}
.comment {
color:#999;
}
.doc-title {
font-weight:bold;
font-size:18px;
margin:20px 0;
}
.doc-definition {
margin-left:20px;
font-style:italic;
}
.doc-returns {
margin-left:20px;
font-size:smaller;
font-style:italic;
}
.doc-example {
border:1px solid #ccc;
background-color:#eee;
padding:3px;
margin:5px 0;
}
</style>
</head>
<body>
<center>
<div id="wrapper">
<div class="header">
<img src="logo.gif">
</div>
<div class="download_wrapper">
<div class="download">
Download source:
<a href="Arbiter.js">Arbiter.js</a><br>
Version: <span id="version"></span><br>
Updated: <span id="updated_on"></span><br>
<span id="license">This work is in the public domain and may be used in any way, for any purpose, without restriction.</span>
</div>
<br>
Support:<br>
<iframe src="//www.facebook.com/plugins/likebox.php?href=https%3A%2F%2Fwww.facebook.com%2Fpages%2FArbiterjs%2F316663535020759&width=210&height=62&colorscheme=light&show_faces=false&border_color&stream=false&header=false" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:210px; height:62px;" allowTransparency="true"></iframe> </div>
<div class="section">
<div class="body">
<p>
<a href="https://www.google.com/search?q=define%3Aarbiter" target="_blank">Arbiter</a>.js is a light-weight, library-agnostic javascript implementation of the <a href="http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern" target="_blank">pub/sub pattern</a>, written by <a href="http://MattKruse.com" target="_blank">Matt Kruse</a>. It allows objects on your page to be de-coupled, and communicate with each other through messages. This leads to a cleaner, more easily understood design, and easier maintenance.
</p>
<center><img src="example.gif"></center>
<p>
For example, if the user changes a value on one part of the page, it can publish a message saying which action was taken. Other parts of the page can subscribe to that action, and do something when it happens. But the first interaction doesn't have to know anything about the second. It just announces what happened, and anyone who cares can act on it.
</p>
</div>
</div>
<div class="section">
<div class="title">Example</div>
<div class="body">
<p>A simple code example might look like this:</p>
<div class="code">
// In the "notifications" widget, I want to do something when new mail arrives
Arbiter.subscribe("email/new", function(data) {
document.getElementById('notification').innerHTML = "New email from "+data.from;
});
// This code is called by the system that detects incoming email
Arbiter.publish("email/new", {from:"Bob"});
</div>
<div id="console" style="font-size:10px;max-height:125px;overflow-y:auto;background-color:#ffffcc;border:2px solid #666; padding:3px;margin:5px;min-height:100px;float:right;width:600px;">
<b>Console:</b><br>
Arbiter.subscribe('click/*', null, document.getElementById('console'), function(data,msg) {
this.innerHTML += msg+"<br>";
});
<hr>
</div>
<p>Here is a simple working example:</p>
<script type="text/javascript">
Arbiter.subscribe('click/*', null, document.getElementById('console'), function(data,msg) {
this.innerHTML += msg+"<br>";
});
</script>
<button onclick="Arbiter.publish('click/1')">Arbiter.publish('click/1')</button><br>
<button onclick="Arbiter.publish('click/2')">Arbiter.publish('click/2')</button><br>
<button onclick="Arbiter.publish('click/3')">Arbiter.publish('click/3')</button><br>
<br style="clear:both;">
</div>
</div>
<div class="section">
<div class="title">Method Summary</div>
<div class="body">
<div class="doc-title">Arbiter.publish</div>
<div class="code">Arbiter.publish( msg [, data [, options] ] )
Returns: true on success, false if any subscriber has thrown a js exception
</div>
<div class="doc-title">Arbiter.subscribe</div>
<div class="code">Arbiter.subscribe( msg, func )
Arbiter.subscribe( msg, options, func )
Arbiter.subscribe( msg, options, context, func )
Returns: subscription id
or [id1,id2] if subscribing to multiple messages
</div>
<div class="doc-title">Arbiter.unsubscribe</div>
<div class="code">Arbiter.unsubscribe( subscription_id )</div>
<div class="doc-title">Arbiter.resubscribe</div>
<div class="code">Arbiter.resubscribe( subscription_id )</div>
<div class="doc-title">Arbiter.create</div>
<div class="code">Arbiter.create()</div>
</div>
</div>
<div class="section">
<div class="title">How To</div>
<div class="body">
<div class="doc-section">
<div class="doc-title">Publish a simple message</div>
<div class="doc-example code">Arbiter.publish( 'component/msg' );</div>
<div class="doc-desc">A message may be in any format, but may not contain [ ,*]. A structure like a/b/c is recommended by convention, to allow messages to be categorized.
</div>
<div class="doc-section">
<div class="doc-title">Subscribe to a message</div>
<div class="doc-example code">Arbiter.subscribe( 'component/msg', function() { } );</div>
<div class="doc-desc">Subscriber functions will be passed the following arguments:
<ul>
<li>published_data: Any data that the publisher has passed along
<li>message: The message text that triggered the notification (useful if a subscriber function can handle multiple messages)
<li>subscriber_data: An object (initially empty) that will be passed between subscribers. This may be useful if you would like subscribers to send context or additional data to subsequent subscribers
</ul>
The value of "this" to be used within the function may be set in the subscribe() method itself.
</div>
</div>
<div class="doc-section">
<div class="doc-title">Pass data to subscribers</div>
<div class="doc-example code">Arbiter.publish( 'component/msg', {"data":"value"} );</div>
<div class="doc-desc">Publishers can pass data to subscribers that contains details about the message.</div>
</div>
<div class="doc-section">
<div class="doc-title">Force message bubbling</div>
<div class="doc-example code">Arbiter.publish( 'component/msg' , null, {cancelable:false} );</div>
<div class="doc-desc">By default, subscribers can return "false" to prevent subsequent subscribers from receiving the message. By passing cancelable:false in the options, the publisher can prevent canceling.</div>
</div>
<div class="doc-section">
<div class="doc-title">Allow late susbcribers to be notified of past messages</div>
<div class="doc-example code">Arbiter.publish( 'component/msg' , null, {persist:true} );</div>
<div class="doc-desc">By default, subscribers only receive notifications about messages sent after they subscribe. But for some events, like "system initalized" that may fire only once, it can be useful to allow subscribers to that message to get fired if the message has already been sent. If the publishers wants subscribers to be notified of this message even if they subscribe later, setting the persist flag will do that.</div>
</div>
<div class="doc-section">
<div class="doc-title">Fire subscribers asynchronously</div>
<div class="doc-example code">Arbiter.publish( 'component/msg', null, {async:true} );</div>
<div class="doc-desc">By default, subscribers are notified and their functions are run synchronously, so the publish() function doesn't return until all subscribers have finished. If you wish to notify the subscribers but return from the publish() call before the subscriber functions execute, use asynchronous mode. <b>Note:</b> Subscribers cannot cancel asynchonous messages, because the subscribers are executed independently using setTimeout()</div>
</div>
<div class="doc-section">
<div class="doc-title">Subscribe to multiple messages at once</div>
<div class="doc-example code">Arbiter.subscribe( 'component/msg, component/msg2', function() { } );
or
Arbiter.subscribe( ['component/msg','component/msg2'], function() { } );
</div>
<div class="doc-desc">The second argument to the subscriber function is the message, so you can distinguish which messages you are handling.</div>
</div>
<div class="doc-section">
<div class="doc-title">Subscribe to multiple messages using a wildcard</div>
<div class="doc-example code">Arbiter.subscribe( 'component/*', function() { } );</div>
<div class="doc-desc">This can be useful for handling all messages of a certain component or category. If you take care when naming your messages, using wildcards can help avoid subscribing to multiple individual messages and needing to update as new messages are added.</div>
</div>
<div class="doc-section">
<div class="doc-title">Subscribe to ALL messages</div>
<div class="doc-example code">Arbiter.subscribe( '*', function() { } );</div>
<div class="doc-desc">This can be useful for logging, for example. You can create a separate message logger that receives all messages and displays them in a debug window.</div>
</div>
<div class="doc-section">
<div class="doc-title">Set subscriber priority</div>
<div class="doc-example code">Arbiter.subscribe( 'msg', {priority:10}, func(){} );
Arbiter.subscribe( 'msg', {priority:20}, func(){} ); // Called first!
</div>
<div class="doc-desc">By default, all subscribers have a priority of 0. Higher values get higher priority and are executed first. Negative values are allowed.</div>
</div>
<div class="doc-section">
<div class="doc-title">Execute a subscriber asynchronously</div>
<div class="doc-example code">Arbiter.subscribe( 'msg', {async:true}, func(){} );</div>
<div class="doc-desc">A subscriber can be set to execute asynchronously, even if the message wasn't published as async. If a subscriber knows that it will do some heavy calculations, for example, it can force itself to be async so it won't interfere with the execution of other subscribers.</div>
</div>
<div class="doc-section">
<div class="doc-title">Ignore persisted messages</div>
<div class="doc-example code">Arbiter.subscribe( 'msg', {persist:false}, func(){} );</div>
<div class="doc-desc">If a message was persisted, a subscriber will be notified of it even if was sent in the past. If your subscriber is not interested in any past messages that may have been persisted, you can force them to be ignored.</div>
</div>
<div class="doc-section">
<div class="doc-title">Set the value of "this"</div>
<div class="doc-example code">Arbiter.subscribe( 'msg', null, document.getElementById('x'),
function() {
this.innerHTML = "Message handled!";
}
);
</div>
<div class="doc-desc">When executing the subscriber function, the value of "this" in the function can be specified at subscription time.</div>
</div>
<div class="doc-section">
<div class="doc-title">Unsubscribe from messages</div>
<div class="doc-example code">var subscription_id = Arbiter.subscribe( 'msg', function(){} );
Arbiter.unsubscribe( subscription_id );
</div>
<div class="doc-desc">Unsubscribing simply sets a flag which prevents the subscriber from executing, in case you want to re-subscribe later.</div>
</div>
<div class="doc-section">
<div class="doc-title">Re-subscribe to messages</div>
<div class="doc-example code">var subscription_id = Arbiter.subscribe( 'msg', function(){} );
Arbiter.unsubscribe( subscription_id );
Arbiter.resubscribe( subscription_id );
</div>
<div class="doc-desc">After unsubscribing, you can later re-subscribe to begin receiving messages again</div>
</div>
<div class="doc-section">
<div class="doc-title">Create a new message handler</div>
<div class="doc-example code">var MyController = Arbiter.create()</div>
<div class="doc-desc">This creates a separate Arbiter instance. If you want to have different message handlers entirely, for example, this will allow for that. Messages sent to the new object will not be shared with the default Arbiter object. You may create as many arbiters as you wish, and they will all operate independently.</div>
</div>
</div>
</div>
<div class="section">
<div class="title">Source</div>
<div class="body code source">
/*
Arbiter.js
by Matt Kruse
http://ArbiterJS.com - See site for documentation
This work is in the public domain and may be used in any way, for any purpose, without restriction.
*/
var Arbiter = (function () {
var create_arbiter = function () {
var subscriptions = {};
var wildcard_subscriptions = {};
var persistent_messages = {};
var id_lookup = {};
var new_id = 1;
return {
'version':'1.0'
,'updated_on':'2011-12-19'
,'create': function() { return create_arbiter(); }
,'subscribe': function() {
var msg, messages, subscription_list, persisted_subscription_list, subscription, func, options={}, context, wildcard=false, priority=0, id, return_ids=[];
if (arguments.length<2) { return null; }
messages = arguments[0];
func = arguments[arguments.length-1];<span class="comment"> // Function is always last argument</span>
if (arguments.length>2) { options = arguments[1] || {}; }
if (arguments.length>3) { context = arguments[2]; }
if (options.priority) {
priority = options.priority;
}
if (typeof messages=="string") {
messages = messages.split(/[,\s]+/);
}
for (var i=0; i<messages.length; i++) {
msg = messages[i];
<span class="comment"> // If the message ends in *, it's a wildcard subscription</span>
if (/\*$/.test(msg)) {
wildcard = true;
msg = msg.replace(/\*$/,'');
subscription_list = wildcard_subscriptions[msg];
if (!subscription_list) {
wildcard_subscriptions[msg] = subscription_list = [];
}
}
else {
subscription_list = subscriptions[msg];
if (!subscription_list) {
subscriptions[msg] = subscription_list = [];
}
}
id = new_id++;
subscription = {'id':id,'f':func,p:priority,self:context,'options':options};
id_lookup[id] = subscription;
subscription_list.push ( subscription );
<span class="comment"> // Sort the list by priority</span>
subscription_list = subscription_list.sort( function(a,b) {
return (a.p>b.p?-1:a.p==b.p?0:1);
} );
<span class="comment"> // Put it back in after sorting</span>
if (wildcard) {
wildcard_subscriptions[msg] = subscription_list;
}
else {
subscriptions[msg] = subscription_list;
}
return_ids.push(id);
<span class="comment"> // Check to see if there are any persistent messages that need</span>
<span class="comment"> // to be fired immediately</span>
if (!options.persist && persistent_messages[msg]) {
persisted_subscription_list = persistent_messages[msg];
for (var j=0; j<persisted_subscription_list.length; j++) {
subscription.f.call( subscription.self, persisted_subscription_list[j], {persist:true} );
}
}
}
<span class="comment"> // Return an array of id's, or just 1</span>
if (messages.length>0) {
return return_ids;
}
return return_ids[0];
}
,'publish': function(msg, data, options) {
var async_timeout=10,result,overall_result=true,cancelable=true,internal_data={},subscriber, wildcard_msg;
var subscription_list = subscriptions[msg] || [];
options = options || {};
<span class="comment"> // Look through wildcard subscriptions to find any that apply</span>
for (wildcard_msg in wildcard_subscriptions) {
if (msg.indexOf(wildcard_msg)==0) {
subscription_list = subscription_list.concat( wildcard_subscriptions[wildcard_msg] );
}
}
if (options.persist===true) {
if (!persistent_messages[msg]) {
persistent_messages[msg] = [];
}
persistent_messages[msg].push( data );
}
if (subscription_list.length==0) {
return overall_result;
}
if (typeof options.cancelable=="boolean") {
cancelable = options.cancelable;
}
for (var i=0; i<subscription_list.length; i++) {
subscriber = subscription_list[i];
if (subscriber.unsubscribed) {
continue;<span class="comment"> // Ignore unsubscribed listeners</span>
}
try {
<span class="comment"> // Publisher OR subscriber may request async</span>
if (options.async===true || (subscriber.options && subscriber.options.async)) {
setTimeout( (function(inner_subscriber) {
return function() {
inner_subscriber.f.call( inner_subscriber.self, data, msg, internal_data );
};
})(subscriber), async_timeout++ );
}
else {
result = subscriber.f.call( subscriber.self, data, msg, internal_data );
if (cancelable && result===false) {
break;
}
}
}
catch(e) {
overall_result = false;
}
}
return overall_result;
}
,'unsubscribe': function(id) {
if (id_lookup[id]) {
id_lookup[id].unsubscribed = true;
return true;
}
return false;
}
,'resubscribe': function(id) {
if (id_lookup[id]) {
id_lookup[id].unsubscribed = false;
return true;
}
return false;
}
};
};
return create_arbiter();
})();
</div>
</div>
</div>
</center>
</body>
</html>
|