mirror of
https://github.com/Hopiu/postal.js.git
synced 2026-05-05 13:54:41 +00:00
Added AMD format build for postal, and included examples that match the jsfiddle usage example, one for standard, one for amd style
This commit is contained in:
parent
3de1a8335e
commit
14864b5135
33 changed files with 11665 additions and 5 deletions
13
build-all.sh
13
build-all.sh
|
|
@ -1,6 +1,13 @@
|
|||
#!/bin/sh
|
||||
|
||||
anvil -b build-browser.json
|
||||
anvil -b build-browser-diags.json
|
||||
anvil -b build-browser-standard.json
|
||||
anvil -b build-browser-standard-diags.json
|
||||
anvil -b build-browser-amd.json
|
||||
anvil -b build-browser-amd-diags.json
|
||||
anvil -b build-node.json
|
||||
anvil -b build-node-diags.json
|
||||
anvil -b build-node-diags.json
|
||||
|
||||
cp ./lib/browser/amd/postal.js ./example/amd/js/libs/postal/
|
||||
cp ./lib/browser/amd/postal.diagnostics.js ./example/amd/js/libs/postal/
|
||||
cp ./lib/browser/standard/postal.js ./example/standard/js/
|
||||
cp ./lib/browser/standard/postal.diagnostics.js ./example/standard/js/
|
||||
12
build-browser-amd-diags.json
Normal file
12
build-browser-amd-diags.json
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"source": "src/diags",
|
||||
"output": "lib/browser/amd",
|
||||
"lint": {},
|
||||
"uglify": {},
|
||||
"gzip": {},
|
||||
"extensions": { "uglify": "min", "gzip": "gz" },
|
||||
"wrap": {
|
||||
"prefix": "define(['postal', 'underscore'], function(postal, _) {",
|
||||
"suffix": "});"
|
||||
}
|
||||
}
|
||||
12
build-browser-amd.json
Normal file
12
build-browser-amd.json
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"source": "src/main",
|
||||
"output": "lib/browser/amd",
|
||||
"lint": {},
|
||||
"uglify": {},
|
||||
"gzip": {},
|
||||
"extensions": { "uglify": "min", "gzip": "gz" },
|
||||
"wrap": {
|
||||
"prefix": "define(['underscore'], function(_) {",
|
||||
"suffix": "return postal; });"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"source": "src/diags",
|
||||
"output": "lib/browser",
|
||||
"output": "lib/browser/standard",
|
||||
"lint": {},
|
||||
"uglify": {},
|
||||
"gzip": {},
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"source": "src/main",
|
||||
"output": "lib/browser",
|
||||
"output": "lib/browser/standard",
|
||||
"lint": {},
|
||||
"uglify": {},
|
||||
"gzip": {},
|
||||
55
example/amd/index.html
Normal file
55
example/amd/index.html
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
|
||||
"http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<title>Postal Examples (AMD/require.js Lib Format)</title>
|
||||
<link rel="stylesheet" type="text/css" href="style.css">
|
||||
<script data-main="js/main" src="js/libs/require/require.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
Example 1 - The World's Simplest Subscription
|
||||
<div class="results" id="example1"></div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 2 - Subscribing with the "#" wildcard character
|
||||
<ul class="results" id="example2"></ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 3 - Subscribing with the "*" wildcard character
|
||||
<ul class="results" id="example3"></ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 4 - using ignoreDuplicates()
|
||||
<ul class="results" id="example4"></ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 5 - using disposeAfter(X)
|
||||
<ul class="results" id="example5"></ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 6 - using whenHandledThenExecute(X)
|
||||
<ul class="results" id="example6"></ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 7 - using withConstraint() to apply a predicate to subscription callback
|
||||
<ul class="results" id="example7"></ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 8 - using withContext to set the "this" context
|
||||
<ul class="results" id="example8"></ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 9 - using withDelay to delay evaluation of subscription
|
||||
<ul class="results" id="example9"></ul>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
131
example/amd/js/examples.js
Normal file
131
example/amd/js/examples.js
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
define(['postal', 'postaldiags'], function(postal, diags){
|
||||
// The world's simplest subscription
|
||||
var channel = postal.channel("Name.Changed");
|
||||
// subscribe
|
||||
var subscription = channel.subscribe(function(data) { $("#example1").html("Name: " + data.name); });
|
||||
// And someone publishes a first name change:
|
||||
channel.publish({ name: "Dr. Who" });
|
||||
subscription.unsubscribe();
|
||||
|
||||
|
||||
// Subscribing to a wildcard topic using #
|
||||
// The # symbol represents "one word" in a topic (i.e - the text between two periods of a topic).
|
||||
// By subscribing to "#.Changed", the binding will match
|
||||
// Name.Changed & Location.Changed but *not* for Changed.Companion
|
||||
var hashChannel = postal.channel("#.Changed"),
|
||||
chgSubscription = hashChannel.subscribe(function(data) {
|
||||
$('<li>' + data.type + " Changed: " + data.value + '</li>').appendTo("#example2");
|
||||
});
|
||||
postal.channel("Name.Changed")
|
||||
.publish({ type: "Name", value:"John Smith" });
|
||||
postal.channel("Location.Changed")
|
||||
.publish({ type: "Location", value: "Early 20th Century England" });
|
||||
chgSubscription.unsubscribe();
|
||||
|
||||
|
||||
// Subscribing to a wildcard topic using *
|
||||
// The * symbol represents any number of characters/words in a topic string.
|
||||
// By subscribing to "DrWho.*.Changed", the binding will match
|
||||
// DrWho.NinthDoctor.Companion.Changed & DrWho.Location.Changed but *not* Changed
|
||||
var starChannel = postal.channel("DrWho.*.Changed"),
|
||||
starSubscription = starChannel.subscribe(function(data) {
|
||||
$('<li>' + data.type + " Changed: " + data.value + '</li>').appendTo("#example3");
|
||||
});
|
||||
postal.channel("DrWho.NinthDoctor.Companion.Changed")
|
||||
.publish({ type: "Companion Name", value:"Rose" });
|
||||
postal.channel("DrWho.TenthDoctor.Companion.Changed")
|
||||
.publish({ type: "Companion Name", value:"Martha" });
|
||||
postal.channel("DrWho.Eleventh.Companion.Changed")
|
||||
.publish({ type: "Companion Name", value:"Amy" });
|
||||
postal.channel("DrWho.Location.Changed")
|
||||
.publish({ type: "Location", value: "The Library" });
|
||||
postal.channel("TheMaster.DrumBeat.Changed")
|
||||
.publish({ type: "DrumBeat", value: "This won't trigger any subscriptions" });
|
||||
postal.channel("Changed")
|
||||
.publish({ type: "Useless", value: "This won't trigger any subscriptions either" });
|
||||
starSubscription.unsubscribe();
|
||||
|
||||
// Applying ignoreDuplicates to a subscription
|
||||
var dupChannel = postal.channel("WeepingAngel.*"),
|
||||
dupSubscription = dupChannel.subscribe(function(data) {
|
||||
$('<li>' + data.value + '</li>').appendTo("#example4");
|
||||
}).ignoreDuplicates();
|
||||
postal.channel("WeepingAngel.DontBlink")
|
||||
.publish({ value:"Don't Blink" });
|
||||
postal.channel("WeepingAngel.DontBlink")
|
||||
.publish({ value:"Don't Blink" });
|
||||
postal.channel("WeepingAngel.DontEvenBlink")
|
||||
.publish({ value:"Don't Even Blink" });
|
||||
postal.channel("WeepingAngel.DontBlink")
|
||||
.publish({ value:"Don't Close Your Eyes" });
|
||||
dupSubscription.unsubscribe();
|
||||
|
||||
// Using disposeAfter(X) to remove subscription automagically after X number of receives
|
||||
var daChannel = postal.channel("Donna.Noble.*"),
|
||||
daSubscription = daChannel.subscribe(function(data) {
|
||||
$('<li>' + data.value + '</li>').appendTo("#example5");
|
||||
}).disposeAfter(2);
|
||||
postal.channel("Donna.Noble.ScreamingAgain")
|
||||
.publish({ value:"Donna Noble has left the library." });
|
||||
postal.channel("Donna.Noble.ScreamingAgain")
|
||||
.publish({ value:"Donna Noble has left the library." });
|
||||
postal.channel("Donna.Noble.ScreamingAgain")
|
||||
.publish({ value:"Donna Noble has left the library." });
|
||||
postal.channel("Donna.Noble.ScreamingAgain")
|
||||
.publish({ value:"Donna Noble has left the library." });
|
||||
postal.channel("Donna.Noble.ScreamingAgain")
|
||||
.publish({ value:"Donna Noble has left the library." });
|
||||
daSubscription.unsubscribe();
|
||||
|
||||
// Using whenHandledThenExecute() to invoke a function after handling a message
|
||||
var whteChannel = postal.channel("Donna.Noble.*"),
|
||||
whteSubscription = whteChannel.subscribe(function(data) {
|
||||
$('<li>' + data.value + '</li>').appendTo("#example6");
|
||||
}).whenHandledThenExecute(function() {
|
||||
$('<li>[Kind of a frivolous example...but this line resulted from the whenHandledThenExecute() callback]</li>').appendTo("#example6");
|
||||
});
|
||||
postal.channel("Donna.Noble.*")
|
||||
.publish({ value:"Donna Noble has left the library." });
|
||||
whteSubscription.unsubscribe();
|
||||
|
||||
// Using withConstraint to apply a predicate to the subscription
|
||||
var drIsInTheTardis = false,
|
||||
wcChannel = postal.channel("Tardis.Depart"),
|
||||
wcSubscription = wcChannel.subscribe(function(data) {
|
||||
$('<li>' + data.value + '</li>').appendTo("#example7");
|
||||
}).withConstraint(function() { return drIsInTheTardis; } );
|
||||
postal.channel("Tardis.Depart")
|
||||
.publish({ value:"Time for time travel....fantastic!" });
|
||||
postal.channel("Tardis.Depart")
|
||||
.publish({ value:"Time for time travel....fantastic!" });
|
||||
drIsInTheTardis = true;
|
||||
postal.channel("Tardis.Depart")
|
||||
.publish({ value:"Time for time travel....fantastic!" });
|
||||
wcSubscription.unsubscribe();
|
||||
|
||||
// Using withContext to set the "this" context
|
||||
var ctxChannel = postal.channel("Dalek.Meet.CyberMen"),
|
||||
ctxSubscription = ctxChannel.subscribe(function(data) {
|
||||
$('<li>' + data.value + '</li>').appendTo(this);
|
||||
}).withContext($("#example8"));
|
||||
postal.channel("Dalek.Meet.CyberMen")
|
||||
.publish({ value:"Exterminate!" });
|
||||
postal.channel("Dalek.Meet.CyberMen")
|
||||
.publish({ value:"Delete!" });
|
||||
ctxSubscription.unsubscribe();
|
||||
|
||||
// Using withDelay() to delay the subscription evaluation
|
||||
var wdChannel = postal.channel("He.Will.Knock.Four.Times"),
|
||||
wdSubscription = wdChannel.subscribe(function(data) {
|
||||
$('<li>' + data.value + '</li>').appendTo($("#example9"));
|
||||
}).withDelay(5000);
|
||||
postal.channel("He.Will.Knock.Four.Times")
|
||||
.publish({ value:"Knock!" });
|
||||
postal.channel("He.Will.Knock.Four.Times")
|
||||
.publish({ value:"Knock!" });
|
||||
postal.channel("He.Will.Knock.Four.Times")
|
||||
.publish({ value:"Knock!" });
|
||||
postal.channel("He.Will.Knock.Four.Times")
|
||||
.publish({ value:"Knock!" });
|
||||
wdSubscription.unsubscribe();
|
||||
});
|
||||
4
example/amd/js/libs/jquery/jquery-min.js
vendored
Normal file
4
example/amd/js/libs/jquery/jquery-min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
20
example/amd/js/libs/postal/postal.diagnostics.js
Normal file
20
example/amd/js/libs/postal/postal.diagnostics.js
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
define(['postal', 'underscore'], function(postal, _) {
|
||||
postal.addWireTap(function(data, envelope) {
|
||||
var all = _.extend(envelope, { data: data });
|
||||
if(!JSON) {
|
||||
throw "This browser or environment does not provide JSON support";
|
||||
}
|
||||
try {
|
||||
console.log(JSON.stringify(all));
|
||||
}
|
||||
catch(exception) {
|
||||
try {
|
||||
all.data = "ERROR: " + exception.message;
|
||||
console.log(JSON.stringify(all));
|
||||
}
|
||||
catch(ex) {
|
||||
console.log("Unable to parse data to JSON: " + exception);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
329
example/amd/js/libs/postal/postal.js
Normal file
329
example/amd/js/libs/postal/postal.js
Normal file
|
|
@ -0,0 +1,329 @@
|
|||
define(['underscore'], function(_) {
|
||||
/*
|
||||
postal.js
|
||||
Author: Jim Cowart
|
||||
License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license)
|
||||
Version 0.4.0
|
||||
*/
|
||||
|
||||
var DEFAULT_EXCHANGE = "/",
|
||||
DEFAULT_PRIORITY = 50,
|
||||
DEFAULT_DISPOSEAFTER = 0,
|
||||
NO_OP = function() { },
|
||||
parsePublishArgs = function(args) {
|
||||
var parsed = { envelope: { } }, env;
|
||||
switch(args.length) {
|
||||
case 3:
|
||||
if(typeof args[1] === "Object" && typeof args[2] === "Object") {
|
||||
parsed.envelope.exchange = DEFAULT_EXCHANGE;
|
||||
parsed.envelope.topic = args[0];
|
||||
parsed.payload = args[1];
|
||||
env = parsed.envelope;
|
||||
parsed.envelope = _.extend(env, args[2]);
|
||||
}
|
||||
else {
|
||||
parsed.envelope.exchange = args[0];
|
||||
parsed.envelope.topic = args[1];
|
||||
parsed.payload = args[2];
|
||||
}
|
||||
break;
|
||||
case 4:
|
||||
parsed.envelope.exchange = args[0];
|
||||
parsed.envelope.topic = args[1];
|
||||
parsed.payload = args[2];
|
||||
env = parsed.envelope;
|
||||
parsed.envelope = _.extend(env, args[3]);
|
||||
break;
|
||||
default:
|
||||
parsed.envelope.exchange = DEFAULT_EXCHANGE;
|
||||
parsed.envelope.topic = args[0];
|
||||
parsed.payload = args[1];
|
||||
break;
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
|
||||
var DistinctPredicate = function() {
|
||||
var previous;
|
||||
return function(data) {
|
||||
var eq = false;
|
||||
if(_.isString(data)) {
|
||||
eq = data === previous;
|
||||
previous = data;
|
||||
}
|
||||
else {
|
||||
eq = _.isEqual(data, previous);
|
||||
previous = _.clone(data);
|
||||
}
|
||||
return !eq;
|
||||
};
|
||||
};
|
||||
|
||||
var ChannelDefinition = function(exchange, topic) {
|
||||
this.exchange = exchange;
|
||||
this.topic = topic;
|
||||
};
|
||||
|
||||
ChannelDefinition.prototype = {
|
||||
subscribe: function(callback) {
|
||||
var subscription = new SubscriptionDefinition(this.exchange, this.topic, callback);
|
||||
postal.configuration.bus.subscribe(subscription);
|
||||
return subscription;
|
||||
},
|
||||
|
||||
publish: function(data, envelope) {
|
||||
var env = _.extend({
|
||||
exchange: this.exchange,
|
||||
timeStamp: new Date(),
|
||||
topic: this.topic
|
||||
}, envelope);
|
||||
postal.configuration.bus.publish(data, env);
|
||||
}
|
||||
};
|
||||
|
||||
var SubscriptionDefinition = function(exchange, topic, callback) {
|
||||
this.exchange = exchange;
|
||||
this.topic = topic;
|
||||
this.callback = callback;
|
||||
this.priority = DEFAULT_PRIORITY;
|
||||
this.constraints = [];
|
||||
this.maxCalls = DEFAULT_DISPOSEAFTER;
|
||||
this.onHandled = NO_OP;
|
||||
this.context = null;
|
||||
};
|
||||
|
||||
SubscriptionDefinition.prototype = {
|
||||
unsubscribe: function() {
|
||||
postal.configuration.bus.unsubscribe(this);
|
||||
},
|
||||
|
||||
defer: function() {
|
||||
var fn = this.callback;
|
||||
this.callback = function(data) {
|
||||
setTimeout(fn,0,data);
|
||||
};
|
||||
return this;
|
||||
},
|
||||
|
||||
disposeAfter: function(maxCalls) {
|
||||
if(_.isNaN(maxCalls) || maxCalls <= 0) {
|
||||
throw "The value provided to disposeAfter (maxCalls) must be a number greater than zero.";
|
||||
}
|
||||
|
||||
var fn = this.onHandled;
|
||||
var dispose = _.after(maxCalls, _.bind(function() {
|
||||
this.unsubscribe(this);
|
||||
}, this));
|
||||
|
||||
this.onHandled = function() {
|
||||
fn.apply(this.context, arguments);
|
||||
dispose();
|
||||
};
|
||||
return this;
|
||||
},
|
||||
|
||||
ignoreDuplicates: function() {
|
||||
this.withConstraint(new DistinctPredicate());
|
||||
return this;
|
||||
},
|
||||
|
||||
whenHandledThenExecute: function(callback) {
|
||||
if(! _.isFunction(callback)) {
|
||||
throw "Value provided to 'whenHandledThenExecute' must be a function";
|
||||
}
|
||||
this.onHandled = callback;
|
||||
return this;
|
||||
},
|
||||
|
||||
withConstraint: function(predicate) {
|
||||
if(! _.isFunction(predicate)) {
|
||||
throw "Predicate constraint must be a function";
|
||||
}
|
||||
this.constraints.push(predicate);
|
||||
return this;
|
||||
},
|
||||
|
||||
withConstraints: function(predicates) {
|
||||
var self = this;
|
||||
if(_.isArray(predicates)) {
|
||||
_.each(predicates, function(predicate) { self.withConstraint(predicate); } );
|
||||
}
|
||||
return self;
|
||||
},
|
||||
|
||||
withContext: function(context) {
|
||||
this.context = context;
|
||||
return this;
|
||||
},
|
||||
|
||||
withDebounce: function(milliseconds) {
|
||||
if(_.isNaN(milliseconds)) {
|
||||
throw "Milliseconds must be a number";
|
||||
}
|
||||
var fn = this.callback;
|
||||
this.callback = _.debounce(fn, milliseconds);
|
||||
return this;
|
||||
},
|
||||
|
||||
withDelay: function(milliseconds) {
|
||||
if(_.isNaN(milliseconds)) {
|
||||
throw "Milliseconds must be a number";
|
||||
}
|
||||
var fn = this.callback;
|
||||
this.callback = function(data) {
|
||||
setTimeout(fn, milliseconds, data);
|
||||
};
|
||||
return this;
|
||||
},
|
||||
|
||||
withPriority: function(priority) {
|
||||
if(_.isNaN(priority)) {
|
||||
throw "Priority must be a number";
|
||||
}
|
||||
this.priority = priority;
|
||||
return this;
|
||||
},
|
||||
|
||||
withThrottle: function(milliseconds) {
|
||||
if(_.isNaN(milliseconds)) {
|
||||
throw "Milliseconds must be a number";
|
||||
}
|
||||
var fn = this.callback;
|
||||
this.callback = _.throttle(fn, milliseconds);
|
||||
return this;
|
||||
}
|
||||
};
|
||||
|
||||
var bindingsResolver = {
|
||||
cache: { },
|
||||
|
||||
compare: function(binding, topic) {
|
||||
if(this.cache[topic] && this.cache[topic][binding]) {
|
||||
return true;
|
||||
}
|
||||
var rgx = new RegExp("^" + this.regexify(binding) + "$"), // match from start to end of string
|
||||
result = rgx.test(topic);
|
||||
if(result) {
|
||||
if(!this.cache[topic]) {
|
||||
this.cache[topic] = {};
|
||||
}
|
||||
this.cache[topic][binding] = true;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
regexify: function(binding) {
|
||||
return binding.replace(/\./g,"\\.") // escape actual periods
|
||||
.replace(/\*/g, ".*") // asterisks match any value
|
||||
.replace(/#/g, "[A-Z,a-z,0-9]*"); // hash matches any alpha-numeric 'word'
|
||||
}
|
||||
};
|
||||
|
||||
var localBus = {
|
||||
|
||||
subscriptions: {},
|
||||
|
||||
wireTaps: [],
|
||||
|
||||
publish: function(data, envelope) {
|
||||
_.each(this.wireTaps,function(tap) {
|
||||
tap(data, envelope);
|
||||
});
|
||||
|
||||
_.each(this.subscriptions[envelope.exchange], function(topic) {
|
||||
_.each(topic, function(binding){
|
||||
if(postal.configuration.resolver.compare(binding.topic, envelope.topic)) {
|
||||
if(_.all(binding.constraints, function(constraint) { return constraint(data); })) {
|
||||
if(typeof binding.callback === 'function') {
|
||||
binding.callback.apply(binding.context, [data, envelope]);
|
||||
binding.onHandled();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
subscribe: function(subDef) {
|
||||
var idx, found, fn;
|
||||
|
||||
if(!this.subscriptions[subDef.exchange]) {
|
||||
this.subscriptions[subDef.exchange] = {};
|
||||
}
|
||||
if(!this.subscriptions[subDef.exchange][subDef.topic]) {
|
||||
this.subscriptions[subDef.exchange][subDef.topic] = [];
|
||||
}
|
||||
|
||||
idx = this.subscriptions[subDef.exchange][subDef.topic].length - 1;
|
||||
if(!_.any(this.subscriptions[subDef.exchange][subDef.topic], function(cfg) { return cfg === subDef; })) {
|
||||
for(; idx >= 0; idx--) {
|
||||
if(this.subscriptions[subDef.exchange][subDef.topic][idx].priority <= subDef.priority) {
|
||||
this.subscriptions[subDef.exchange][subDef.topic].splice(idx + 1, 0, subDef);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(!found) {
|
||||
this.subscriptions[subDef.exchange][subDef.topic].unshift(subDef);
|
||||
}
|
||||
}
|
||||
|
||||
return _.bind(function() { this.unsubscribe(subDef); }, this);
|
||||
},
|
||||
|
||||
unsubscribe: function(config) {
|
||||
if(this.subscriptions[config.exchange][config.topic]) {
|
||||
var len = this.subscriptions[config.exchange][config.topic].length,
|
||||
idx = 0;
|
||||
for ( ; idx < len; idx++ ) {
|
||||
if (this.subscriptions[config.exchange][config.topic][idx] === config) {
|
||||
this.subscriptions[config.exchange][config.topic].splice( idx, 1 );
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
addWireTap: function(callback) {
|
||||
this.wireTaps.push(callback);
|
||||
return function() {
|
||||
var idx = this.wireTaps.indexOf(callback);
|
||||
if(idx !== -1) {
|
||||
this.wireTaps.splice(idx,1);
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
var postal = {
|
||||
configuration: {
|
||||
bus: localBus,
|
||||
resolver: bindingsResolver
|
||||
},
|
||||
|
||||
channel: function(exchange, topic) {
|
||||
var exch = arguments.length === 2 ? exchange : DEFAULT_EXCHANGE,
|
||||
tpc = arguments.length === 2 ? topic : exchange;
|
||||
return new ChannelDefinition(exch, tpc);
|
||||
},
|
||||
|
||||
subscribe: function(exchange, topic, callback) {
|
||||
var exch = arguments.length === 3 ? exchange : DEFAULT_EXCHANGE,
|
||||
tpc = arguments.length === 3 ? topic : exchange,
|
||||
callbk = arguments.length === 3 ? callback : topic;
|
||||
var channel = this.channel(exch, tpc);
|
||||
return channel.subscribe(callbk);
|
||||
},
|
||||
|
||||
publish: function(exchange, topic, payload, envelopeOptions) {
|
||||
var parsedArgs = parsePublishArgs([].slice.call(arguments,0));
|
||||
var channel = this.channel(parsedArgs.envelope.exchange, parsedArgs.envelope.topic);
|
||||
channel.publish(parsedArgs.payload, parsedArgs.envelope);
|
||||
},
|
||||
|
||||
addWireTap: function(callback) {
|
||||
this.configuration.bus.addWireTap(callback);
|
||||
}
|
||||
};
|
||||
|
||||
return postal; });
|
||||
31
example/amd/js/libs/require/require.js
Normal file
31
example/amd/js/libs/require/require.js
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
/*
|
||||
RequireJS 1.0.2 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
|
||||
Available via the MIT or new BSD license.
|
||||
see: http://github.com/jrburke/requirejs for details
|
||||
*/
|
||||
var requirejs,require,define;
|
||||
(function(){function J(a){return M.call(a)==="[object Function]"}function E(a){return M.call(a)==="[object Array]"}function Z(a,c,h){for(var k in c)if(!(k in K)&&(!(k in a)||h))a[k]=c[k];return d}function N(a,c,d){a=Error(c+"\nhttp://requirejs.org/docs/errors.html#"+a);if(d)a.originalError=d;return a}function $(a,c,d){var k,j,q;for(k=0;q=c[k];k++){q=typeof q==="string"?{name:q}:q;j=q.location;if(d&&(!j||j.indexOf("/")!==0&&j.indexOf(":")===-1))j=d+"/"+(j||q.name);a[q.name]={name:q.name,location:j||
|
||||
q.name,main:(q.main||"main").replace(ea,"").replace(aa,"")}}}function V(a,c){a.holdReady?a.holdReady(c):c?a.readyWait+=1:a.ready(!0)}function fa(a){function c(b,l){var f,a;if(b&&b.charAt(0)===".")if(l){p.pkgs[l]?l=[l]:(l=l.split("/"),l=l.slice(0,l.length-1));f=b=l.concat(b.split("/"));var c;for(a=0;c=f[a];a++)if(c===".")f.splice(a,1),a-=1;else if(c==="..")if(a===1&&(f[2]===".."||f[0]===".."))break;else a>0&&(f.splice(a-1,2),a-=2);a=p.pkgs[f=b[0]];b=b.join("/");a&&b===f+"/"+a.main&&(b=f)}else b.indexOf("./")===
|
||||
0&&(b=b.substring(2));return b}function h(b,l){var f=b?b.indexOf("!"):-1,a=null,d=l?l.name:null,i=b,e,h;f!==-1&&(a=b.substring(0,f),b=b.substring(f+1,b.length));a&&(a=c(a,d));b&&(a?e=(f=m[a])&&f.normalize?f.normalize(b,function(b){return c(b,d)}):c(b,d):(e=c(b,d),h=E[e],h||(h=g.nameToUrl(e,null,l),E[e]=h)));return{prefix:a,name:e,parentMap:l,url:h,originalName:i,fullName:a?a+"!"+(e||""):e}}function k(){var b=!0,l=p.priorityWait,f,a;if(l){for(a=0;f=l[a];a++)if(!s[f]){b=!1;break}b&&delete p.priorityWait}return b}
|
||||
function j(b,l,f){return function(){var a=ga.call(arguments,0),c;if(f&&J(c=a[a.length-1]))c.__requireJsBuild=!0;a.push(l);return b.apply(null,a)}}function q(b,l){var a=j(g.require,b,l);Z(a,{nameToUrl:j(g.nameToUrl,b),toUrl:j(g.toUrl,b),defined:j(g.requireDefined,b),specified:j(g.requireSpecified,b),isBrowser:d.isBrowser});return a}function o(b){var l,a,c,C=b.callback,i=b.map,e=i.fullName,ba=b.deps;c=b.listeners;if(C&&J(C)){if(p.catchError.define)try{a=d.execCb(e,b.callback,ba,m[e])}catch(k){l=k}else a=
|
||||
d.execCb(e,b.callback,ba,m[e]);if(e)(C=b.cjsModule)&&C.exports!==void 0&&C.exports!==m[e]?a=m[e]=b.cjsModule.exports:a===void 0&&b.usingExports?a=m[e]:(m[e]=a,F[e]&&(Q[e]=!0))}else e&&(a=m[e]=C,F[e]&&(Q[e]=!0));if(D[b.id])delete D[b.id],b.isDone=!0,g.waitCount-=1,g.waitCount===0&&(I=[]);delete R[e];if(d.onResourceLoad&&!b.placeholder)d.onResourceLoad(g,i,b.depArray);if(l)return a=(e?h(e).url:"")||l.fileName||l.sourceURL,c=l.moduleTree,l=N("defineerror",'Error evaluating module "'+e+'" at location "'+
|
||||
a+'":\n'+l+"\nfileName:"+a+"\nlineNumber: "+(l.lineNumber||l.line),l),l.moduleName=e,l.moduleTree=c,d.onError(l);for(l=0;C=c[l];l++)C(a)}function r(b,a){return function(f){b.depDone[a]||(b.depDone[a]=!0,b.deps[a]=f,b.depCount-=1,b.depCount||o(b))}}function u(b,a){var f=a.map,c=f.fullName,h=f.name,i=L[b]||(L[b]=m[b]),e;if(!a.loading)a.loading=!0,e=function(b){a.callback=function(){return b};o(a);s[a.id]=!0;w()},e.fromText=function(b,a){var l=O;s[b]=!1;g.scriptCount+=1;g.fake[b]=!0;l&&(O=!1);d.exec(a);
|
||||
l&&(O=!0);g.completeLoad(b)},c in m?e(m[c]):i.load(h,q(f.parentMap,!0),e,p)}function v(b){D[b.id]||(D[b.id]=b,I.push(b),g.waitCount+=1)}function B(b){this.listeners.push(b)}function t(b,a){var f=b.fullName,c=b.prefix,d=c?L[c]||(L[c]=m[c]):null,i,e;f&&(i=R[f]);if(!i&&(e=!0,i={id:(c&&!d?M++ +"__p@:":"")+(f||"__r@"+M++),map:b,depCount:0,depDone:[],depCallbacks:[],deps:[],listeners:[],add:B},y[i.id]=!0,f&&(!c||L[c])))R[f]=i;c&&!d?(f=t(h(c),!0),f.add(function(){var a=h(b.originalName,b.parentMap),a=t(a,
|
||||
!0);i.placeholder=!0;a.add(function(b){i.callback=function(){return b};o(i)})})):e&&a&&(s[i.id]=!1,g.paused.push(i),v(i));return i}function x(b,a,f,c){var b=h(b,c),d=b.name,i=b.fullName,e=t(b),k=e.id,j=e.deps,n;if(i){if(i in m||s[k]===!0||i==="jquery"&&p.jQuery&&p.jQuery!==f().fn.jquery)return;y[k]=!0;s[k]=!0;i==="jquery"&&f&&S(f())}e.depArray=a;e.callback=f;for(f=0;f<a.length;f++)if(k=a[f])k=h(k,d?b:c),n=k.fullName,a[f]=n,n==="require"?j[f]=q(b):n==="exports"?(j[f]=m[i]={},e.usingExports=!0):n===
|
||||
"module"?e.cjsModule=j[f]={id:d,uri:d?g.nameToUrl(d,null,c):void 0,exports:m[i]}:n in m&&!(n in D)&&(!(i in F)||i in F&&Q[n])?j[f]=m[n]:(i in F&&(F[n]=!0,delete m[n],T[k.url]=!1),e.depCount+=1,e.depCallbacks[f]=r(e,f),t(k,!0).add(e.depCallbacks[f]));e.depCount?v(e):o(e)}function n(b){x.apply(null,b)}function z(b,a){if(!b.isDone){var c=b.map.fullName,d=b.depArray,g,i,e,k;if(c){if(a[c])return m[c];a[c]=!0}if(d)for(g=0;g<d.length;g++)if(i=d[g])if((e=h(i).prefix)&&(k=D[e])&&z(k,a),(e=D[i])&&!e.isDone&&
|
||||
s[i])i=z(e,a),b.depCallbacks[g](i);return c?m[c]:void 0}}function A(){var b=p.waitSeconds*1E3,a=b&&g.startTime+b<(new Date).getTime(),b="",c=!1,h=!1,j;if(!(g.pausedCount>0)){if(p.priorityWait)if(k())w();else return;for(j in s)if(!(j in K)&&(c=!0,!s[j]))if(a)b+=j+" ";else{h=!0;break}if(c||g.waitCount){if(a&&b)return j=N("timeout","Load timeout for modules: "+b),j.requireType="timeout",j.requireModules=b,d.onError(j);if(h||g.scriptCount){if((G||ca)&&!W)W=setTimeout(function(){W=0;A()},50)}else{if(g.waitCount){for(H=
|
||||
0;b=I[H];H++)z(b,{});g.paused.length&&w();X<5&&(X+=1,A())}X=0;d.checkReadyState()}}}}var g,w,p={waitSeconds:7,baseUrl:"./",paths:{},pkgs:{},catchError:{}},P=[],y={require:!0,exports:!0,module:!0},E={},m={},s={},D={},I=[],T={},M=0,R={},L={},F={},Q={},Y=0;S=function(b){if(!g.jQuery&&(b=b||(typeof jQuery!=="undefined"?jQuery:null))&&!(p.jQuery&&b.fn.jquery!==p.jQuery)&&("holdReady"in b||"readyWait"in b))if(g.jQuery=b,n(["jquery",[],function(){return jQuery}]),g.scriptCount)V(b,!0),g.jQueryIncremented=
|
||||
!0};w=function(){var b,a,c,h,j,i;Y+=1;if(g.scriptCount<=0)g.scriptCount=0;for(;P.length;)if(b=P.shift(),b[0]===null)return d.onError(N("mismatch","Mismatched anonymous define() module: "+b[b.length-1]));else n(b);if(!p.priorityWait||k())for(;g.paused.length;){j=g.paused;g.pausedCount+=j.length;g.paused=[];for(h=0;b=j[h];h++)a=b.map,c=a.url,i=a.fullName,a.prefix?u(a.prefix,b):!T[c]&&!s[i]&&(d.load(g,i,c),c.indexOf("empty:")!==0&&(T[c]=!0));g.startTime=(new Date).getTime();g.pausedCount-=j.length}Y===
|
||||
1&&A();Y-=1};g={contextName:a,config:p,defQueue:P,waiting:D,waitCount:0,specified:y,loaded:s,urlMap:E,urlFetched:T,scriptCount:0,defined:m,paused:[],pausedCount:0,plugins:L,needFullExec:F,fake:{},fullExec:Q,managerCallbacks:R,makeModuleMap:h,normalize:c,configure:function(b){var a,c,d;b.baseUrl&&b.baseUrl.charAt(b.baseUrl.length-1)!=="/"&&(b.baseUrl+="/");a=p.paths;d=p.pkgs;Z(p,b,!0);if(b.paths){for(c in b.paths)c in K||(a[c]=b.paths[c]);p.paths=a}if((a=b.packagePaths)||b.packages){if(a)for(c in a)c in
|
||||
K||$(d,a[c],c);b.packages&&$(d,b.packages);p.pkgs=d}if(b.priority)c=g.requireWait,g.requireWait=!1,g.takeGlobalQueue(),w(),g.require(b.priority),w(),g.requireWait=c,p.priorityWait=b.priority;if(b.deps||b.callback)g.require(b.deps||[],b.callback)},requireDefined:function(b,a){return h(b,a).fullName in m},requireSpecified:function(b,a){return h(b,a).fullName in y},require:function(b,c,f){if(typeof b==="string"){if(J(c))return d.onError(N("requireargs","Invalid require call"));if(d.get)return d.get(g,
|
||||
b,c);c=h(b,c);b=c.fullName;return!(b in m)?d.onError(N("notloaded","Module name '"+c.fullName+"' has not been loaded yet for context: "+a)):m[b]}(b&&b.length||c)&&x(null,b,c,f);if(!g.requireWait)for(;!g.scriptCount&&g.paused.length;)g.takeGlobalQueue(),w();return g.require},takeGlobalQueue:function(){U.length&&(ha.apply(g.defQueue,[g.defQueue.length-1,0].concat(U)),U=[])},completeLoad:function(b){var a;for(g.takeGlobalQueue();P.length;)if(a=P.shift(),a[0]===null){a[0]=b;break}else if(a[0]===b)break;
|
||||
else n(a),a=null;a?n(a):n([b,[],b==="jquery"&&typeof jQuery!=="undefined"?function(){return jQuery}:null]);S();d.isAsync&&(g.scriptCount-=1);w();d.isAsync||(g.scriptCount-=1)},toUrl:function(a,c){var d=a.lastIndexOf("."),h=null;d!==-1&&(h=a.substring(d,a.length),a=a.substring(0,d));return g.nameToUrl(a,h,c)},nameToUrl:function(a,h,f){var j,k,i,e,m=g.config,a=c(a,f&&f.fullName);if(d.jsExtRegExp.test(a))h=a+(h?h:"");else{j=m.paths;k=m.pkgs;f=a.split("/");for(e=f.length;e>0;e--)if(i=f.slice(0,e).join("/"),
|
||||
j[i]){f.splice(0,e,j[i]);break}else if(i=k[i]){a=a===i.name?i.location+"/"+i.main:i.location;f.splice(0,e,a);break}h=f.join("/")+(h||".js");h=(h.charAt(0)==="/"||h.match(/^\w+:/)?"":m.baseUrl)+h}return m.urlArgs?h+((h.indexOf("?")===-1?"?":"&")+m.urlArgs):h}};g.jQueryCheck=S;g.resume=w;return g}function ia(){var a,c,d;if(n&&n.readyState==="interactive")return n;a=document.getElementsByTagName("script");for(c=a.length-1;c>-1&&(d=a[c]);c--)if(d.readyState==="interactive")return n=d;return null}var ja=
|
||||
/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,ka=/require\(\s*["']([^'"\s]+)["']\s*\)/g,ea=/^\.\//,aa=/\.js$/,M=Object.prototype.toString,r=Array.prototype,ga=r.slice,ha=r.splice,G=!!(typeof window!=="undefined"&&navigator&&document),ca=!G&&typeof importScripts!=="undefined",la=G&&navigator.platform==="PLAYSTATION 3"?/^complete$/:/^(complete|loaded)$/,da=typeof opera!=="undefined"&&opera.toString()==="[object Opera]",K={},t={},U=[],n=null,X=0,O=!1,d,r={},I,v,x,y,u,z,A,H,B,S,W;if(typeof define==="undefined"){if(typeof requirejs!==
|
||||
"undefined")if(J(requirejs))return;else r=requirejs,requirejs=void 0;typeof require!=="undefined"&&!J(require)&&(r=require,require=void 0);d=requirejs=function(a,c,d){var k="_",j;!E(a)&&typeof a!=="string"&&(j=a,E(c)?(a=c,c=d):a=[]);if(j&&j.context)k=j.context;d=t[k]||(t[k]=fa(k));j&&d.configure(j);return d.require(a,c)};d.config=function(a){return d(a)};require||(require=d);d.toUrl=function(a){return t._.toUrl(a)};d.version="1.0.2";d.jsExtRegExp=/^\/|:|\?|\.js$/;v=d.s={contexts:t,skipAsync:{}};if(d.isAsync=
|
||||
d.isBrowser=G)if(x=v.head=document.getElementsByTagName("head")[0],y=document.getElementsByTagName("base")[0])x=v.head=y.parentNode;d.onError=function(a){throw a;};d.load=function(a,c,h){d.resourcesReady(!1);a.scriptCount+=1;d.attach(h,a,c);if(a.jQuery&&!a.jQueryIncremented)V(a.jQuery,!0),a.jQueryIncremented=!0};define=function(a,c,d){var k,j;typeof a!=="string"&&(d=c,c=a,a=null);E(c)||(d=c,c=[]);!c.length&&J(d)&&d.length&&(d.toString().replace(ja,"").replace(ka,function(a,d){c.push(d)}),c=(d.length===
|
||||
1?["require"]:["require","exports","module"]).concat(c));if(O&&(k=I||ia()))a||(a=k.getAttribute("data-requiremodule")),j=t[k.getAttribute("data-requirecontext")];(j?j.defQueue:U).push([a,c,d])};define.amd={multiversion:!0,plugins:!0,jQuery:!0};d.exec=function(a){return eval(a)};d.execCb=function(a,c,d,k){return c.apply(k,d)};d.addScriptToDom=function(a){I=a;y?x.insertBefore(a,y):x.appendChild(a);I=null};d.onScriptLoad=function(a){var c=a.currentTarget||a.srcElement,h;if(a.type==="load"||c&&la.test(c.readyState))n=
|
||||
null,a=c.getAttribute("data-requirecontext"),h=c.getAttribute("data-requiremodule"),t[a].completeLoad(h),c.detachEvent&&!da?c.detachEvent("onreadystatechange",d.onScriptLoad):c.removeEventListener("load",d.onScriptLoad,!1)};d.attach=function(a,c,h,k,j,n){var o;if(G)return k=k||d.onScriptLoad,o=c&&c.config&&c.config.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script"),o.type=j||"text/javascript",o.charset="utf-8",o.async=!v.skipAsync[a],c&&o.setAttribute("data-requirecontext",
|
||||
c.contextName),o.setAttribute("data-requiremodule",h),o.attachEvent&&!da?(O=!0,n?o.onreadystatechange=function(){if(o.readyState==="loaded")o.onreadystatechange=null,o.attachEvent("onreadystatechange",k),n(o)}:o.attachEvent("onreadystatechange",k)):o.addEventListener("load",k,!1),o.src=a,n||d.addScriptToDom(o),o;else ca&&(importScripts(a),c.completeLoad(h));return null};if(G){u=document.getElementsByTagName("script");for(H=u.length-1;H>-1&&(z=u[H]);H--){if(!x)x=z.parentNode;if(A=z.getAttribute("data-main")){if(!r.baseUrl)u=
|
||||
A.split("/"),z=u.pop(),u=u.length?u.join("/")+"/":"./",r.baseUrl=u,A=z.replace(aa,"");r.deps=r.deps?r.deps.concat(A):[A];break}}}d.checkReadyState=function(){var a=v.contexts,c;for(c in a)if(!(c in K)&&a[c].waitCount)return;d.resourcesReady(!0)};d.resourcesReady=function(a){var c,h;d.resourcesDone=a;if(d.resourcesDone)for(h in a=v.contexts,a)if(!(h in K)&&(c=a[h],c.jQueryIncremented))V(c.jQuery,!1),c.jQueryIncremented=!1};d.pageLoaded=function(){if(document.readyState!=="complete")document.readyState=
|
||||
"complete"};if(G&&document.addEventListener&&!document.readyState)document.readyState="loading",window.addEventListener("load",d.pageLoaded,!1);d(r);if(d.isAsync&&typeof setTimeout!=="undefined")B=v.contexts[r.context||"_"],B.requireWait=!0,setTimeout(function(){B.requireWait=!1;B.takeGlobalQueue();B.jQueryCheck();B.scriptCount||B.resume();d.checkReadyState()},0)}})();
|
||||
30
example/amd/js/libs/underscore/underscore-min.js
vendored
Normal file
30
example/amd/js/libs/underscore/underscore-min.js
vendored
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
// Underscore.js 1.2.2
|
||||
// (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
|
||||
// Underscore is freely distributable under the MIT license.
|
||||
// Portions of Underscore are inspired or borrowed from Prototype,
|
||||
// Oliver Steele's Functional, and John Resig's Micro-Templating.
|
||||
// For all details and documentation:
|
||||
// http://documentcloud.github.com/underscore
|
||||
(function(){function r(a,c,d){if(a===c)return a!==0||1/a==1/c;if(a==null||c==null)return a===c;if(a._chain)a=a._wrapped;if(c._chain)c=c._wrapped;if(b.isFunction(a.isEqual))return a.isEqual(c);if(b.isFunction(c.isEqual))return c.isEqual(a);var e=l.call(a);if(e!=l.call(c))return false;switch(e){case "[object String]":return String(a)==String(c);case "[object Number]":return a=+a,c=+c,a!=a?c!=c:a==0?1/a==1/c:a==c;case "[object Date]":case "[object Boolean]":return+a==+c;case "[object RegExp]":return a.source==
|
||||
c.source&&a.global==c.global&&a.multiline==c.multiline&&a.ignoreCase==c.ignoreCase}if(typeof a!="object"||typeof c!="object")return false;for(var f=d.length;f--;)if(d[f]==a)return true;d.push(a);var f=0,g=true;if(e=="[object Array]"){if(f=a.length,g=f==c.length)for(;f--;)if(!(g=f in a==f in c&&r(a[f],c[f],d)))break}else{if("constructor"in a!="constructor"in c||a.constructor!=c.constructor)return false;for(var h in a)if(m.call(a,h)&&(f++,!(g=m.call(c,h)&&r(a[h],c[h],d))))break;if(g){for(h in c)if(m.call(c,
|
||||
h)&&!f--)break;g=!f}}d.pop();return g}var s=this,F=s._,o={},k=Array.prototype,p=Object.prototype,i=k.slice,G=k.unshift,l=p.toString,m=p.hasOwnProperty,v=k.forEach,w=k.map,x=k.reduce,y=k.reduceRight,z=k.filter,A=k.every,B=k.some,q=k.indexOf,C=k.lastIndexOf,p=Array.isArray,H=Object.keys,t=Function.prototype.bind,b=function(a){return new n(a)};if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)exports=module.exports=b;exports._=b}else typeof define==="function"&&define.amd?
|
||||
define("underscore",function(){return b}):s._=b;b.VERSION="1.2.2";var j=b.each=b.forEach=function(a,c,b){if(a!=null)if(v&&a.forEach===v)a.forEach(c,b);else if(a.length===+a.length)for(var e=0,f=a.length;e<f;e++){if(e in a&&c.call(b,a[e],e,a)===o)break}else for(e in a)if(m.call(a,e)&&c.call(b,a[e],e,a)===o)break};b.map=function(a,c,b){var e=[];if(a==null)return e;if(w&&a.map===w)return a.map(c,b);j(a,function(a,g,h){e[e.length]=c.call(b,a,g,h)});return e};b.reduce=b.foldl=b.inject=function(a,c,d,e){var f=
|
||||
d!==void 0;a==null&&(a=[]);if(x&&a.reduce===x)return e&&(c=b.bind(c,e)),f?a.reduce(c,d):a.reduce(c);j(a,function(a,b,i){f?d=c.call(e,d,a,b,i):(d=a,f=true)});if(!f)throw new TypeError("Reduce of empty array with no initial value");return d};b.reduceRight=b.foldr=function(a,c,d,e){a==null&&(a=[]);if(y&&a.reduceRight===y)return e&&(c=b.bind(c,e)),d!==void 0?a.reduceRight(c,d):a.reduceRight(c);a=(b.isArray(a)?a.slice():b.toArray(a)).reverse();return b.reduce(a,c,d,e)};b.find=b.detect=function(a,c,b){var e;
|
||||
D(a,function(a,g,h){if(c.call(b,a,g,h))return e=a,true});return e};b.filter=b.select=function(a,c,b){var e=[];if(a==null)return e;if(z&&a.filter===z)return a.filter(c,b);j(a,function(a,g,h){c.call(b,a,g,h)&&(e[e.length]=a)});return e};b.reject=function(a,c,b){var e=[];if(a==null)return e;j(a,function(a,g,h){c.call(b,a,g,h)||(e[e.length]=a)});return e};b.every=b.all=function(a,c,b){var e=true;if(a==null)return e;if(A&&a.every===A)return a.every(c,b);j(a,function(a,g,h){if(!(e=e&&c.call(b,a,g,h)))return o});
|
||||
return e};var D=b.some=b.any=function(a,c,d){var c=c||b.identity,e=false;if(a==null)return e;if(B&&a.some===B)return a.some(c,d);j(a,function(a,b,h){if(e||(e=c.call(d,a,b,h)))return o});return!!e};b.include=b.contains=function(a,c){var b=false;if(a==null)return b;return q&&a.indexOf===q?a.indexOf(c)!=-1:b=D(a,function(a){return a===c})};b.invoke=function(a,c){var d=i.call(arguments,2);return b.map(a,function(a){return(c.call?c||a:a[c]).apply(a,d)})};b.pluck=function(a,c){return b.map(a,function(a){return a[c]})};
|
||||
b.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,a);if(!c&&b.isEmpty(a))return-Infinity;var e={computed:-Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b>=e.computed&&(e={value:a,computed:b})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);if(!c&&b.isEmpty(a))return Infinity;var e={computed:Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b<e.computed&&(e={value:a,computed:b})});return e.value};b.shuffle=function(a){var c=[],b;
|
||||
j(a,function(a,f){f==0?c[0]=a:(b=Math.floor(Math.random()*(f+1)),c[f]=c[b],c[b]=a)});return c};b.sortBy=function(a,c,d){return b.pluck(b.map(a,function(a,b,g){return{value:a,criteria:c.call(d,a,b,g)}}).sort(function(a,c){var b=a.criteria,d=c.criteria;return b<d?-1:b>d?1:0}),"value")};b.groupBy=function(a,c){var d={},e=b.isFunction(c)?c:function(a){return a[c]};j(a,function(a,c){var b=e(a,c);(d[b]||(d[b]=[])).push(a)});return d};b.sortedIndex=function(a,c,d){d||(d=b.identity);for(var e=0,f=a.length;e<
|
||||
f;){var g=e+f>>1;d(a[g])<d(c)?e=g+1:f=g}return e};b.toArray=function(a){return!a?[]:a.toArray?a.toArray():b.isArray(a)?i.call(a):b.isArguments(a)?i.call(a):b.values(a)};b.size=function(a){return b.toArray(a).length};b.first=b.head=function(a,b,d){return b!=null&&!d?i.call(a,0,b):a[0]};b.initial=function(a,b,d){return i.call(a,0,a.length-(b==null||d?1:b))};b.last=function(a,b,d){return b!=null&&!d?i.call(a,Math.max(a.length-b,0)):a[a.length-1]};b.rest=b.tail=function(a,b,d){return i.call(a,b==null||
|
||||
d?1:b)};b.compact=function(a){return b.filter(a,function(a){return!!a})};b.flatten=function(a,c){return b.reduce(a,function(a,e){if(b.isArray(e))return a.concat(c?e:b.flatten(e));a[a.length]=e;return a},[])};b.without=function(a){return b.difference(a,i.call(arguments,1))};b.uniq=b.unique=function(a,c,d){var d=d?b.map(a,d):a,e=[];b.reduce(d,function(d,g,h){if(0==h||(c===true?b.last(d)!=g:!b.include(d,g)))d[d.length]=g,e[e.length]=a[h];return d},[]);return e};b.union=function(){return b.uniq(b.flatten(arguments,
|
||||
true))};b.intersection=b.intersect=function(a){var c=i.call(arguments,1);return b.filter(b.uniq(a),function(a){return b.every(c,function(c){return b.indexOf(c,a)>=0})})};b.difference=function(a,c){return b.filter(a,function(a){return!b.include(c,a)})};b.zip=function(){for(var a=i.call(arguments),c=b.max(b.pluck(a,"length")),d=Array(c),e=0;e<c;e++)d[e]=b.pluck(a,""+e);return d};b.indexOf=function(a,c,d){if(a==null)return-1;var e;if(d)return d=b.sortedIndex(a,c),a[d]===c?d:-1;if(q&&a.indexOf===q)return a.indexOf(c);
|
||||
for(d=0,e=a.length;d<e;d++)if(a[d]===c)return d;return-1};b.lastIndexOf=function(a,b){if(a==null)return-1;if(C&&a.lastIndexOf===C)return a.lastIndexOf(b);for(var d=a.length;d--;)if(a[d]===b)return d;return-1};b.range=function(a,b,d){arguments.length<=1&&(b=a||0,a=0);for(var d=arguments[2]||1,e=Math.max(Math.ceil((b-a)/d),0),f=0,g=Array(e);f<e;)g[f++]=a,a+=d;return g};var E=function(){};b.bind=function(a,c){var d,e;if(a.bind===t&&t)return t.apply(a,i.call(arguments,1));if(!b.isFunction(a))throw new TypeError;
|
||||
e=i.call(arguments,2);return d=function(){if(!(this instanceof d))return a.apply(c,e.concat(i.call(arguments)));E.prototype=a.prototype;var b=new E,g=a.apply(b,e.concat(i.call(arguments)));return Object(g)===g?g:b}};b.bindAll=function(a){var c=i.call(arguments,1);c.length==0&&(c=b.functions(a));j(c,function(c){a[c]=b.bind(a[c],a)});return a};b.memoize=function(a,c){var d={};c||(c=b.identity);return function(){var b=c.apply(this,arguments);return m.call(d,b)?d[b]:d[b]=a.apply(this,arguments)}};b.delay=
|
||||
function(a,b){var d=i.call(arguments,2);return setTimeout(function(){return a.apply(a,d)},b)};b.defer=function(a){return b.delay.apply(b,[a,1].concat(i.call(arguments,1)))};b.throttle=function(a,c){var d,e,f,g,h,i=b.debounce(function(){h=g=false},c);return function(){d=this;e=arguments;var b;f||(f=setTimeout(function(){f=null;h&&a.apply(d,e);i()},c));g?h=true:a.apply(d,e);i();g=true}};b.debounce=function(a,b){var d;return function(){var e=this,f=arguments;clearTimeout(d);d=setTimeout(function(){d=
|
||||
null;a.apply(e,f)},b)}};b.once=function(a){var b=false,d;return function(){if(b)return d;b=true;return d=a.apply(this,arguments)}};b.wrap=function(a,b){return function(){var d=[a].concat(i.call(arguments));return b.apply(this,d)}};b.compose=function(){var a=i.call(arguments);return function(){for(var b=i.call(arguments),d=a.length-1;d>=0;d--)b=[a[d].apply(this,b)];return b[0]}};b.after=function(a,b){return a<=0?b():function(){if(--a<1)return b.apply(this,arguments)}};b.keys=H||function(a){if(a!==
|
||||
Object(a))throw new TypeError("Invalid object");var b=[],d;for(d in a)m.call(a,d)&&(b[b.length]=d);return b};b.values=function(a){return b.map(a,b.identity)};b.functions=b.methods=function(a){var c=[],d;for(d in a)b.isFunction(a[d])&&c.push(d);return c.sort()};b.extend=function(a){j(i.call(arguments,1),function(b){for(var d in b)b[d]!==void 0&&(a[d]=b[d])});return a};b.defaults=function(a){j(i.call(arguments,1),function(b){for(var d in b)a[d]==null&&(a[d]=b[d])});return a};b.clone=function(a){return!b.isObject(a)?
|
||||
a:b.isArray(a)?a.slice():b.extend({},a)};b.tap=function(a,b){b(a);return a};b.isEqual=function(a,b){return r(a,b,[])};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(m.call(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=p||function(a){return l.call(a)=="[object Array]"};b.isObject=function(a){return a===Object(a)};b.isArguments=l.call(arguments)=="[object Arguments]"?function(a){return l.call(a)=="[object Arguments]"}:
|
||||
function(a){return!(!a||!m.call(a,"callee"))};b.isFunction=function(a){return l.call(a)=="[object Function]"};b.isString=function(a){return l.call(a)=="[object String]"};b.isNumber=function(a){return l.call(a)=="[object Number]"};b.isNaN=function(a){return a!==a};b.isBoolean=function(a){return a===true||a===false||l.call(a)=="[object Boolean]"};b.isDate=function(a){return l.call(a)=="[object Date]"};b.isRegExp=function(a){return l.call(a)=="[object RegExp]"};b.isNull=function(a){return a===null};
|
||||
b.isUndefined=function(a){return a===void 0};b.noConflict=function(){s._=F;return this};b.identity=function(a){return a};b.times=function(a,b,d){for(var e=0;e<a;e++)b.call(d,e)};b.escape=function(a){return(""+a).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")};b.mixin=function(a){j(b.functions(a),function(c){I(c,b[c]=a[c])})};var J=0;b.uniqueId=function(a){var b=J++;return a?a+b:b};b.templateSettings={evaluate:/<%([\s\S]+?)%>/g,
|
||||
interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};b.template=function(a,c){var d=b.templateSettings,d="var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('"+a.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(d.escape,function(a,b){return"',_.escape("+b.replace(/\\'/g,"'")+"),'"}).replace(d.interpolate,function(a,b){return"',"+b.replace(/\\'/g,"'")+",'"}).replace(d.evaluate||null,function(a,b){return"');"+b.replace(/\\'/g,"'").replace(/[\r\n\t]/g," ")+";__p.push('"}).replace(/\r/g,
|
||||
"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t")+"');}return __p.join('');",e=new Function("obj","_",d);return c?e(c,b):function(a){return e(a,b)}};var n=function(a){this._wrapped=a};b.prototype=n.prototype;var u=function(a,c){return c?b(a).chain():a},I=function(a,c){n.prototype[a]=function(){var a=i.call(arguments);G.call(a,this._wrapped);return u(c.apply(b,a),this._chain)}};b.mixin(b);j("pop,push,reverse,shift,sort,splice,unshift".split(","),function(a){var b=k[a];n.prototype[a]=function(){b.apply(this._wrapped,
|
||||
arguments);return u(this._wrapped,this._chain)}});j(["concat","join","slice"],function(a){var b=k[a];n.prototype[a]=function(){return u(b.apply(this._wrapped,arguments),this._chain)}});n.prototype.chain=function(){this._chain=true;return this};n.prototype.value=function(){return this._wrapped}}).call(this);
|
||||
14
example/amd/js/main.js
Normal file
14
example/amd/js/main.js
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
require.config({
|
||||
paths: {
|
||||
underscore: 'libs/underscore/underscore-min',
|
||||
postal: 'libs/postal/postal',
|
||||
postaldiags:'libs/postal/postal.diagnostics',
|
||||
jquery: 'libs/jquery/jquery-min'
|
||||
}
|
||||
});
|
||||
|
||||
require(['jquery'], function($){
|
||||
$(function(){
|
||||
require(['examples']);
|
||||
});
|
||||
});
|
||||
11
example/amd/style.css
Normal file
11
example/amd/style.css
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
div {
|
||||
font-family: Tahoma, Arial;
|
||||
font-size: 10pt;
|
||||
}
|
||||
|
||||
.results {
|
||||
margin-bottom:20px;
|
||||
padding: 10px;
|
||||
border-top: 1pt solid lightsteelblue;
|
||||
border-bottom: 1pt solid lightsteelblue;
|
||||
}
|
||||
59
example/standard/index.html
Normal file
59
example/standard/index.html
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
|
||||
"http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<title>Postal Examples (Standard Lib Format)</title>
|
||||
<link rel="stylesheet" type="text/css" href="style.css">
|
||||
<script type="text/javascript" src="js/underscore.js"></script>
|
||||
<script type="text/javascript" src="js/jquery-1.7.1.js"></script>
|
||||
<script type="text/javascript" src="js/postal.js"></script>
|
||||
<script type="text/javascript" src="js/postal.diagnostics.js"></script>
|
||||
<script type="text/javascript" src="js/main.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
Example 1 - The World's Simplest Subscription
|
||||
<div class="results" id="example1"></div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 2 - Subscribing with the "#" wildcard character
|
||||
<ul class="results" id="example2"></ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 3 - Subscribing with the "*" wildcard character
|
||||
<ul class="results" id="example3"></ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 4 - using ignoreDuplicates()
|
||||
<ul class="results" id="example4"></ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 5 - using disposeAfter(X)
|
||||
<ul class="results" id="example5"></ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 6 - using whenHandledThenExecute(X)
|
||||
<ul class="results" id="example6"></ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 7 - using withConstraint() to apply a predicate to subscription callback
|
||||
<ul class="results" id="example7"></ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 8 - using withContext to set the "this" context
|
||||
<ul class="results" id="example8"></ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
Example 9 - using withDelay to delay evaluation of subscription
|
||||
<ul class="results" id="example9"></ul>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
9266
example/standard/js/jquery-1.7.1.js
vendored
Normal file
9266
example/standard/js/jquery-1.7.1.js
vendored
Normal file
File diff suppressed because it is too large
Load diff
131
example/standard/js/main.js
Normal file
131
example/standard/js/main.js
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
$(function(){
|
||||
// The world's simplest subscription
|
||||
var channel = postal.channel("Name.Changed");
|
||||
// subscribe
|
||||
var subscription = channel.subscribe(function(data) { $("#example1").html("Name: " + data.name); });
|
||||
// And someone publishes a first name change:
|
||||
channel.publish({ name: "Dr. Who" });
|
||||
subscription.unsubscribe();
|
||||
|
||||
|
||||
// Subscribing to a wildcard topic using #
|
||||
// The # symbol represents "one word" in a topic (i.e - the text between two periods of a topic).
|
||||
// By subscribing to "#.Changed", the binding will match
|
||||
// Name.Changed & Location.Changed but *not* for Changed.Companion
|
||||
var hashChannel = postal.channel("#.Changed"),
|
||||
chgSubscription = hashChannel.subscribe(function(data) {
|
||||
$('<li>' + data.type + " Changed: " + data.value + '</li>').appendTo("#example2");
|
||||
});
|
||||
postal.channel("Name.Changed")
|
||||
.publish({ type: "Name", value:"John Smith" });
|
||||
postal.channel("Location.Changed")
|
||||
.publish({ type: "Location", value: "Early 20th Century England" });
|
||||
chgSubscription.unsubscribe();
|
||||
|
||||
|
||||
// Subscribing to a wildcard topic using *
|
||||
// The * symbol represents any number of characters/words in a topic string.
|
||||
// By subscribing to "DrWho.*.Changed", the binding will match
|
||||
// DrWho.NinthDoctor.Companion.Changed & DrWho.Location.Changed but *not* Changed
|
||||
var starChannel = postal.channel("DrWho.*.Changed"),
|
||||
starSubscription = starChannel.subscribe(function(data) {
|
||||
$('<li>' + data.type + " Changed: " + data.value + '</li>').appendTo("#example3");
|
||||
});
|
||||
postal.channel("DrWho.NinthDoctor.Companion.Changed")
|
||||
.publish({ type: "Companion Name", value:"Rose" });
|
||||
postal.channel("DrWho.TenthDoctor.Companion.Changed")
|
||||
.publish({ type: "Companion Name", value:"Martha" });
|
||||
postal.channel("DrWho.Eleventh.Companion.Changed")
|
||||
.publish({ type: "Companion Name", value:"Amy" });
|
||||
postal.channel("DrWho.Location.Changed")
|
||||
.publish({ type: "Location", value: "The Library" });
|
||||
postal.channel("TheMaster.DrumBeat.Changed")
|
||||
.publish({ type: "DrumBeat", value: "This won't trigger any subscriptions" });
|
||||
postal.channel("Changed")
|
||||
.publish({ type: "Useless", value: "This won't trigger any subscriptions either" });
|
||||
starSubscription.unsubscribe();
|
||||
|
||||
// Applying ignoreDuplicates to a subscription
|
||||
var dupChannel = postal.channel("WeepingAngel.*"),
|
||||
dupSubscription = dupChannel.subscribe(function(data) {
|
||||
$('<li>' + data.value + '</li>').appendTo("#example4");
|
||||
}).ignoreDuplicates();
|
||||
postal.channel("WeepingAngel.DontBlink")
|
||||
.publish({ value:"Don't Blink" });
|
||||
postal.channel("WeepingAngel.DontBlink")
|
||||
.publish({ value:"Don't Blink" });
|
||||
postal.channel("WeepingAngel.DontEvenBlink")
|
||||
.publish({ value:"Don't Even Blink" });
|
||||
postal.channel("WeepingAngel.DontBlink")
|
||||
.publish({ value:"Don't Close Your Eyes" });
|
||||
dupSubscription.unsubscribe();
|
||||
|
||||
// Using disposeAfter(X) to remove subscription automagically after X number of receives
|
||||
var daChannel = postal.channel("Donna.Noble.*"),
|
||||
daSubscription = daChannel.subscribe(function(data) {
|
||||
$('<li>' + data.value + '</li>').appendTo("#example5");
|
||||
}).disposeAfter(2);
|
||||
postal.channel("Donna.Noble.ScreamingAgain")
|
||||
.publish({ value:"Donna Noble has left the library." });
|
||||
postal.channel("Donna.Noble.ScreamingAgain")
|
||||
.publish({ value:"Donna Noble has left the library." });
|
||||
postal.channel("Donna.Noble.ScreamingAgain")
|
||||
.publish({ value:"Donna Noble has left the library." });
|
||||
postal.channel("Donna.Noble.ScreamingAgain")
|
||||
.publish({ value:"Donna Noble has left the library." });
|
||||
postal.channel("Donna.Noble.ScreamingAgain")
|
||||
.publish({ value:"Donna Noble has left the library." });
|
||||
daSubscription.unsubscribe();
|
||||
|
||||
// Using whenHandledThenExecute() to invoke a function after handling a message
|
||||
var whteChannel = postal.channel("Donna.Noble.*"),
|
||||
whteSubscription = whteChannel.subscribe(function(data) {
|
||||
$('<li>' + data.value + '</li>').appendTo("#example6");
|
||||
}).whenHandledThenExecute(function() {
|
||||
$('<li>[Kind of a frivolous example...but this line resulted from the whenHandledThenExecute() callback]</li>').appendTo("#example6");
|
||||
});
|
||||
postal.channel("Donna.Noble.*")
|
||||
.publish({ value:"Donna Noble has left the library." });
|
||||
whteSubscription.unsubscribe();
|
||||
|
||||
// Using withConstraint to apply a predicate to the subscription
|
||||
var drIsInTheTardis = false,
|
||||
wcChannel = postal.channel("Tardis.Depart"),
|
||||
wcSubscription = wcChannel.subscribe(function(data) {
|
||||
$('<li>' + data.value + '</li>').appendTo("#example7");
|
||||
}).withConstraint(function() { return drIsInTheTardis; } );
|
||||
postal.channel("Tardis.Depart")
|
||||
.publish({ value:"Time for time travel....fantastic!" });
|
||||
postal.channel("Tardis.Depart")
|
||||
.publish({ value:"Time for time travel....fantastic!" });
|
||||
drIsInTheTardis = true;
|
||||
postal.channel("Tardis.Depart")
|
||||
.publish({ value:"Time for time travel....fantastic!" });
|
||||
wcSubscription.unsubscribe();
|
||||
|
||||
// Using withContext to set the "this" context
|
||||
var ctxChannel = postal.channel("Dalek.Meet.CyberMen"),
|
||||
ctxSubscription = ctxChannel.subscribe(function(data) {
|
||||
$('<li>' + data.value + '</li>').appendTo(this);
|
||||
}).withContext($("#example8"));
|
||||
postal.channel("Dalek.Meet.CyberMen")
|
||||
.publish({ value:"Exterminate!" });
|
||||
postal.channel("Dalek.Meet.CyberMen")
|
||||
.publish({ value:"Delete!" });
|
||||
ctxSubscription.unsubscribe();
|
||||
|
||||
// Using withDelay() to delay the subscription evaluation
|
||||
var wdChannel = postal.channel("He.Will.Knock.Four.Times"),
|
||||
wdSubscription = wdChannel.subscribe(function(data) {
|
||||
$('<li>' + data.value + '</li>').appendTo($("#example9"));
|
||||
}).withDelay(5000);
|
||||
postal.channel("He.Will.Knock.Four.Times")
|
||||
.publish({ value:"Knock!" });
|
||||
postal.channel("He.Will.Knock.Four.Times")
|
||||
.publish({ value:"Knock!" });
|
||||
postal.channel("He.Will.Knock.Four.Times")
|
||||
.publish({ value:"Knock!" });
|
||||
postal.channel("He.Will.Knock.Four.Times")
|
||||
.publish({ value:"Knock!" });
|
||||
wdSubscription.unsubscribe();
|
||||
});
|
||||
839
example/standard/js/underscore.js
Normal file
839
example/standard/js/underscore.js
Normal file
|
|
@ -0,0 +1,839 @@
|
|||
// Underscore.js 1.1.7
|
||||
// (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
|
||||
// Underscore is freely distributable under the MIT license.
|
||||
// Portions of Underscore are inspired or borrowed from Prototype,
|
||||
// Oliver Steele's Functional, and John Resig's Micro-Templating.
|
||||
// For all details and documentation:
|
||||
// http://documentcloud.github.com/underscore
|
||||
|
||||
(function() {
|
||||
|
||||
// Baseline setup
|
||||
// --------------
|
||||
|
||||
// Establish the root object, `window` in the browser, or `global` on the server.
|
||||
var root = this;
|
||||
|
||||
// Save the previous value of the `_` variable.
|
||||
var previousUnderscore = root._;
|
||||
|
||||
// Establish the object that gets returned to break out of a loop iteration.
|
||||
var breaker = {};
|
||||
|
||||
// Save bytes in the minified (but not gzipped) version:
|
||||
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
|
||||
|
||||
// Create quick reference variables for speed access to core prototypes.
|
||||
var slice = ArrayProto.slice,
|
||||
unshift = ArrayProto.unshift,
|
||||
toString = ObjProto.toString,
|
||||
hasOwnProperty = ObjProto.hasOwnProperty;
|
||||
|
||||
// All **ECMAScript 5** native function implementations that we hope to use
|
||||
// are declared here.
|
||||
var
|
||||
nativeForEach = ArrayProto.forEach,
|
||||
nativeMap = ArrayProto.map,
|
||||
nativeReduce = ArrayProto.reduce,
|
||||
nativeReduceRight = ArrayProto.reduceRight,
|
||||
nativeFilter = ArrayProto.filter,
|
||||
nativeEvery = ArrayProto.every,
|
||||
nativeSome = ArrayProto.some,
|
||||
nativeIndexOf = ArrayProto.indexOf,
|
||||
nativeLastIndexOf = ArrayProto.lastIndexOf,
|
||||
nativeIsArray = Array.isArray,
|
||||
nativeKeys = Object.keys,
|
||||
nativeBind = FuncProto.bind;
|
||||
|
||||
// Create a safe reference to the Underscore object for use below.
|
||||
var _ = function(obj) { return new wrapper(obj); };
|
||||
|
||||
// Export the Underscore object for **CommonJS**, with backwards-compatibility
|
||||
// for the old `require()` API. If we're not in CommonJS, add `_` to the
|
||||
// global object.
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
module.exports = _;
|
||||
_._ = _;
|
||||
} else {
|
||||
// Exported as a string, for Closure Compiler "advanced" mode.
|
||||
root['_'] = _;
|
||||
}
|
||||
|
||||
// Current version.
|
||||
_.VERSION = '1.1.7';
|
||||
|
||||
// Collection Functions
|
||||
// --------------------
|
||||
|
||||
// The cornerstone, an `each` implementation, aka `forEach`.
|
||||
// Handles objects with the built-in `forEach`, arrays, and raw objects.
|
||||
// Delegates to **ECMAScript 5**'s native `forEach` if available.
|
||||
var each = _.each = _.forEach = function(obj, iterator, context) {
|
||||
if (obj == null) return;
|
||||
if (nativeForEach && obj.forEach === nativeForEach) {
|
||||
obj.forEach(iterator, context);
|
||||
} else if (obj.length === +obj.length) {
|
||||
for (var i = 0, l = obj.length; i < l; i++) {
|
||||
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
|
||||
}
|
||||
} else {
|
||||
for (var key in obj) {
|
||||
if (hasOwnProperty.call(obj, key)) {
|
||||
if (iterator.call(context, obj[key], key, obj) === breaker) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Return the results of applying the iterator to each element.
|
||||
// Delegates to **ECMAScript 5**'s native `map` if available.
|
||||
_.map = function(obj, iterator, context) {
|
||||
var results = [];
|
||||
if (obj == null) return results;
|
||||
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
|
||||
each(obj, function(value, index, list) {
|
||||
results[results.length] = iterator.call(context, value, index, list);
|
||||
});
|
||||
return results;
|
||||
};
|
||||
|
||||
// **Reduce** builds up a single result from a list of values, aka `inject`,
|
||||
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
|
||||
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
|
||||
var initial = memo !== void 0;
|
||||
if (obj == null) obj = [];
|
||||
if (nativeReduce && obj.reduce === nativeReduce) {
|
||||
if (context) iterator = _.bind(iterator, context);
|
||||
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
|
||||
}
|
||||
each(obj, function(value, index, list) {
|
||||
if (!initial) {
|
||||
memo = value;
|
||||
initial = true;
|
||||
} else {
|
||||
memo = iterator.call(context, memo, value, index, list);
|
||||
}
|
||||
});
|
||||
if (!initial) throw new TypeError("Reduce of empty array with no initial value");
|
||||
return memo;
|
||||
};
|
||||
|
||||
// The right-associative version of reduce, also known as `foldr`.
|
||||
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
|
||||
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
|
||||
if (obj == null) obj = [];
|
||||
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
|
||||
if (context) iterator = _.bind(iterator, context);
|
||||
return memo !== void 0 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
|
||||
}
|
||||
var reversed = (_.isArray(obj) ? obj.slice() : _.toArray(obj)).reverse();
|
||||
return _.reduce(reversed, iterator, memo, context);
|
||||
};
|
||||
|
||||
// Return the first value which passes a truth test. Aliased as `detect`.
|
||||
_.find = _.detect = function(obj, iterator, context) {
|
||||
var result;
|
||||
any(obj, function(value, index, list) {
|
||||
if (iterator.call(context, value, index, list)) {
|
||||
result = value;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
// Return all the elements that pass a truth test.
|
||||
// Delegates to **ECMAScript 5**'s native `filter` if available.
|
||||
// Aliased as `select`.
|
||||
_.filter = _.select = function(obj, iterator, context) {
|
||||
var results = [];
|
||||
if (obj == null) return results;
|
||||
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
|
||||
each(obj, function(value, index, list) {
|
||||
if (iterator.call(context, value, index, list)) results[results.length] = value;
|
||||
});
|
||||
return results;
|
||||
};
|
||||
|
||||
// Return all the elements for which a truth test fails.
|
||||
_.reject = function(obj, iterator, context) {
|
||||
var results = [];
|
||||
if (obj == null) return results;
|
||||
each(obj, function(value, index, list) {
|
||||
if (!iterator.call(context, value, index, list)) results[results.length] = value;
|
||||
});
|
||||
return results;
|
||||
};
|
||||
|
||||
// Determine whether all of the elements match a truth test.
|
||||
// Delegates to **ECMAScript 5**'s native `every` if available.
|
||||
// Aliased as `all`.
|
||||
_.every = _.all = function(obj, iterator, context) {
|
||||
var result = true;
|
||||
if (obj == null) return result;
|
||||
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
|
||||
each(obj, function(value, index, list) {
|
||||
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
// Determine if at least one element in the object matches a truth test.
|
||||
// Delegates to **ECMAScript 5**'s native `some` if available.
|
||||
// Aliased as `any`.
|
||||
var any = _.some = _.any = function(obj, iterator, context) {
|
||||
iterator = iterator || _.identity;
|
||||
var result = false;
|
||||
if (obj == null) return result;
|
||||
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
|
||||
each(obj, function(value, index, list) {
|
||||
if (result |= iterator.call(context, value, index, list)) return breaker;
|
||||
});
|
||||
return !!result;
|
||||
};
|
||||
|
||||
// Determine if a given value is included in the array or object using `===`.
|
||||
// Aliased as `contains`.
|
||||
_.include = _.contains = function(obj, target) {
|
||||
var found = false;
|
||||
if (obj == null) return found;
|
||||
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
|
||||
any(obj, function(value) {
|
||||
if (found = value === target) return true;
|
||||
});
|
||||
return found;
|
||||
};
|
||||
|
||||
// Invoke a method (with arguments) on every item in a collection.
|
||||
_.invoke = function(obj, method) {
|
||||
var args = slice.call(arguments, 2);
|
||||
return _.map(obj, function(value) {
|
||||
return (method.call ? method || value : value[method]).apply(value, args);
|
||||
});
|
||||
};
|
||||
|
||||
// Convenience version of a common use case of `map`: fetching a property.
|
||||
_.pluck = function(obj, key) {
|
||||
return _.map(obj, function(value){ return value[key]; });
|
||||
};
|
||||
|
||||
// Return the maximum element or (element-based computation).
|
||||
_.max = function(obj, iterator, context) {
|
||||
if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
|
||||
var result = {computed : -Infinity};
|
||||
each(obj, function(value, index, list) {
|
||||
var computed = iterator ? iterator.call(context, value, index, list) : value;
|
||||
computed >= result.computed && (result = {value : value, computed : computed});
|
||||
});
|
||||
return result.value;
|
||||
};
|
||||
|
||||
// Return the minimum element (or element-based computation).
|
||||
_.min = function(obj, iterator, context) {
|
||||
if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
|
||||
var result = {computed : Infinity};
|
||||
each(obj, function(value, index, list) {
|
||||
var computed = iterator ? iterator.call(context, value, index, list) : value;
|
||||
computed < result.computed && (result = {value : value, computed : computed});
|
||||
});
|
||||
return result.value;
|
||||
};
|
||||
|
||||
// Sort the object's values by a criterion produced by an iterator.
|
||||
_.sortBy = function(obj, iterator, context) {
|
||||
return _.pluck(_.map(obj, function(value, index, list) {
|
||||
return {
|
||||
value : value,
|
||||
criteria : iterator.call(context, value, index, list)
|
||||
};
|
||||
}).sort(function(left, right) {
|
||||
var a = left.criteria, b = right.criteria;
|
||||
return a < b ? -1 : a > b ? 1 : 0;
|
||||
}), 'value');
|
||||
};
|
||||
|
||||
// Groups the object's values by a criterion produced by an iterator
|
||||
_.groupBy = function(obj, iterator) {
|
||||
var result = {};
|
||||
each(obj, function(value, index) {
|
||||
var key = iterator(value, index);
|
||||
(result[key] || (result[key] = [])).push(value);
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
// Use a comparator function to figure out at what index an object should
|
||||
// be inserted so as to maintain order. Uses binary search.
|
||||
_.sortedIndex = function(array, obj, iterator) {
|
||||
iterator || (iterator = _.identity);
|
||||
var low = 0, high = array.length;
|
||||
while (low < high) {
|
||||
var mid = (low + high) >> 1;
|
||||
iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
|
||||
}
|
||||
return low;
|
||||
};
|
||||
|
||||
// Safely convert anything iterable into a real, live array.
|
||||
_.toArray = function(iterable) {
|
||||
if (!iterable) return [];
|
||||
if (iterable.toArray) return iterable.toArray();
|
||||
if (_.isArray(iterable)) return slice.call(iterable);
|
||||
if (_.isArguments(iterable)) return slice.call(iterable);
|
||||
return _.values(iterable);
|
||||
};
|
||||
|
||||
// Return the number of elements in an object.
|
||||
_.size = function(obj) {
|
||||
return _.toArray(obj).length;
|
||||
};
|
||||
|
||||
// Array Functions
|
||||
// ---------------
|
||||
|
||||
// Get the first element of an array. Passing **n** will return the first N
|
||||
// values in the array. Aliased as `head`. The **guard** check allows it to work
|
||||
// with `_.map`.
|
||||
_.first = _.head = function(array, n, guard) {
|
||||
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
|
||||
};
|
||||
|
||||
// Returns everything but the first entry of the array. Aliased as `tail`.
|
||||
// Especially useful on the arguments object. Passing an **index** will return
|
||||
// the rest of the values in the array from that index onward. The **guard**
|
||||
// check allows it to work with `_.map`.
|
||||
_.rest = _.tail = function(array, index, guard) {
|
||||
return slice.call(array, (index == null) || guard ? 1 : index);
|
||||
};
|
||||
|
||||
// Get the last element of an array.
|
||||
_.last = function(array) {
|
||||
return array[array.length - 1];
|
||||
};
|
||||
|
||||
// Trim out all falsy values from an array.
|
||||
_.compact = function(array) {
|
||||
return _.filter(array, function(value){ return !!value; });
|
||||
};
|
||||
|
||||
// Return a completely flattened version of an array.
|
||||
_.flatten = function(array) {
|
||||
return _.reduce(array, function(memo, value) {
|
||||
if (_.isArray(value)) return memo.concat(_.flatten(value));
|
||||
memo[memo.length] = value;
|
||||
return memo;
|
||||
}, []);
|
||||
};
|
||||
|
||||
// Return a version of the array that does not contain the specified value(s).
|
||||
_.without = function(array) {
|
||||
return _.difference(array, slice.call(arguments, 1));
|
||||
};
|
||||
|
||||
// Produce a duplicate-free version of the array. If the array has already
|
||||
// been sorted, you have the option of using a faster algorithm.
|
||||
// Aliased as `unique`.
|
||||
_.uniq = _.unique = function(array, isSorted) {
|
||||
return _.reduce(array, function(memo, el, i) {
|
||||
if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo[memo.length] = el;
|
||||
return memo;
|
||||
}, []);
|
||||
};
|
||||
|
||||
// Produce an array that contains the union: each distinct element from all of
|
||||
// the passed-in arrays.
|
||||
_.union = function() {
|
||||
return _.uniq(_.flatten(arguments));
|
||||
};
|
||||
|
||||
// Produce an array that contains every item shared between all the
|
||||
// passed-in arrays. (Aliased as "intersect" for back-compat.)
|
||||
_.intersection = _.intersect = function(array) {
|
||||
var rest = slice.call(arguments, 1);
|
||||
return _.filter(_.uniq(array), function(item) {
|
||||
return _.every(rest, function(other) {
|
||||
return _.indexOf(other, item) >= 0;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Take the difference between one array and another.
|
||||
// Only the elements present in just the first array will remain.
|
||||
_.difference = function(array, other) {
|
||||
return _.filter(array, function(value){ return !_.include(other, value); });
|
||||
};
|
||||
|
||||
// Zip together multiple lists into a single array -- elements that share
|
||||
// an index go together.
|
||||
_.zip = function() {
|
||||
var args = slice.call(arguments);
|
||||
var length = _.max(_.pluck(args, 'length'));
|
||||
var results = new Array(length);
|
||||
for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
|
||||
return results;
|
||||
};
|
||||
|
||||
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
|
||||
// we need this function. Return the position of the first occurrence of an
|
||||
// item in an array, or -1 if the item is not included in the array.
|
||||
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
|
||||
// If the array is large and already in sort order, pass `true`
|
||||
// for **isSorted** to use binary search.
|
||||
_.indexOf = function(array, item, isSorted) {
|
||||
if (array == null) return -1;
|
||||
var i, l;
|
||||
if (isSorted) {
|
||||
i = _.sortedIndex(array, item);
|
||||
return array[i] === item ? i : -1;
|
||||
}
|
||||
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
|
||||
for (i = 0, l = array.length; i < l; i++) if (array[i] === item) return i;
|
||||
return -1;
|
||||
};
|
||||
|
||||
|
||||
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
|
||||
_.lastIndexOf = function(array, item) {
|
||||
if (array == null) return -1;
|
||||
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
|
||||
var i = array.length;
|
||||
while (i--) if (array[i] === item) return i;
|
||||
return -1;
|
||||
};
|
||||
|
||||
// Generate an integer Array containing an arithmetic progression. A port of
|
||||
// the native Python `range()` function. See
|
||||
// [the Python documentation](http://docs.python.org/library/functions.html#range).
|
||||
_.range = function(start, stop, step) {
|
||||
if (arguments.length <= 1) {
|
||||
stop = start || 0;
|
||||
start = 0;
|
||||
}
|
||||
step = arguments[2] || 1;
|
||||
|
||||
var len = Math.max(Math.ceil((stop - start) / step), 0);
|
||||
var idx = 0;
|
||||
var range = new Array(len);
|
||||
|
||||
while(idx < len) {
|
||||
range[idx++] = start;
|
||||
start += step;
|
||||
}
|
||||
|
||||
return range;
|
||||
};
|
||||
|
||||
// Function (ahem) Functions
|
||||
// ------------------
|
||||
|
||||
// Create a function bound to a given object (assigning `this`, and arguments,
|
||||
// optionally). Binding with arguments is also known as `curry`.
|
||||
// Delegates to **ECMAScript 5**'s native `Function.bind` if available.
|
||||
// We check for `func.bind` first, to fail fast when `func` is undefined.
|
||||
_.bind = function(func, obj) {
|
||||
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
|
||||
var args = slice.call(arguments, 2);
|
||||
return function() {
|
||||
return func.apply(obj, args.concat(slice.call(arguments)));
|
||||
};
|
||||
};
|
||||
|
||||
// Bind all of an object's methods to that object. Useful for ensuring that
|
||||
// all callbacks defined on an object belong to it.
|
||||
_.bindAll = function(obj) {
|
||||
var funcs = slice.call(arguments, 1);
|
||||
if (funcs.length == 0) funcs = _.functions(obj);
|
||||
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
|
||||
return obj;
|
||||
};
|
||||
|
||||
// Memoize an expensive function by storing its results.
|
||||
_.memoize = function(func, hasher) {
|
||||
var memo = {};
|
||||
hasher || (hasher = _.identity);
|
||||
return function() {
|
||||
var key = hasher.apply(this, arguments);
|
||||
return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
|
||||
};
|
||||
};
|
||||
|
||||
// Delays a function for the given number of milliseconds, and then calls
|
||||
// it with the arguments supplied.
|
||||
_.delay = function(func, wait) {
|
||||
var args = slice.call(arguments, 2);
|
||||
return setTimeout(function(){ return func.apply(func, args); }, wait);
|
||||
};
|
||||
|
||||
// Defers a function, scheduling it to run after the current call stack has
|
||||
// cleared.
|
||||
_.defer = function(func) {
|
||||
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
|
||||
};
|
||||
|
||||
// Internal function used to implement `_.throttle` and `_.debounce`.
|
||||
var limit = function(func, wait, debounce) {
|
||||
var timeout;
|
||||
return function() {
|
||||
var context = this, args = arguments;
|
||||
var throttler = function() {
|
||||
timeout = null;
|
||||
func.apply(context, args);
|
||||
};
|
||||
if (debounce) clearTimeout(timeout);
|
||||
if (debounce || !timeout) timeout = setTimeout(throttler, wait);
|
||||
};
|
||||
};
|
||||
|
||||
// Returns a function, that, when invoked, will only be triggered at most once
|
||||
// during a given window of time.
|
||||
_.throttle = function(func, wait) {
|
||||
return limit(func, wait, false);
|
||||
};
|
||||
|
||||
// Returns a function, that, as long as it continues to be invoked, will not
|
||||
// be triggered. The function will be called after it stops being called for
|
||||
// N milliseconds.
|
||||
_.debounce = function(func, wait) {
|
||||
return limit(func, wait, true);
|
||||
};
|
||||
|
||||
// Returns a function that will be executed at most one time, no matter how
|
||||
// often you call it. Useful for lazy initialization.
|
||||
_.once = function(func) {
|
||||
var ran = false, memo;
|
||||
return function() {
|
||||
if (ran) return memo;
|
||||
ran = true;
|
||||
return memo = func.apply(this, arguments);
|
||||
};
|
||||
};
|
||||
|
||||
// Returns the first function passed as an argument to the second,
|
||||
// allowing you to adjust arguments, run code before and after, and
|
||||
// conditionally execute the original function.
|
||||
_.wrap = function(func, wrapper) {
|
||||
return function() {
|
||||
var args = [func].concat(slice.call(arguments));
|
||||
return wrapper.apply(this, args);
|
||||
};
|
||||
};
|
||||
|
||||
// Returns a function that is the composition of a list of functions, each
|
||||
// consuming the return value of the function that follows.
|
||||
_.compose = function() {
|
||||
var funcs = slice.call(arguments);
|
||||
return function() {
|
||||
var args = slice.call(arguments);
|
||||
for (var i = funcs.length - 1; i >= 0; i--) {
|
||||
args = [funcs[i].apply(this, args)];
|
||||
}
|
||||
return args[0];
|
||||
};
|
||||
};
|
||||
|
||||
// Returns a function that will only be executed after being called N times.
|
||||
_.after = function(times, func) {
|
||||
return function() {
|
||||
if (--times < 1) { return func.apply(this, arguments); }
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
// Object Functions
|
||||
// ----------------
|
||||
|
||||
// Retrieve the names of an object's properties.
|
||||
// Delegates to **ECMAScript 5**'s native `Object.keys`
|
||||
_.keys = nativeKeys || function(obj) {
|
||||
if (obj !== Object(obj)) throw new TypeError('Invalid object');
|
||||
var keys = [];
|
||||
for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key;
|
||||
return keys;
|
||||
};
|
||||
|
||||
// Retrieve the values of an object's properties.
|
||||
_.values = function(obj) {
|
||||
return _.map(obj, _.identity);
|
||||
};
|
||||
|
||||
// Return a sorted list of the function names available on the object.
|
||||
// Aliased as `methods`
|
||||
_.functions = _.methods = function(obj) {
|
||||
var names = [];
|
||||
for (var key in obj) {
|
||||
if (_.isFunction(obj[key])) names.push(key);
|
||||
}
|
||||
return names.sort();
|
||||
};
|
||||
|
||||
// Extend a given object with all the properties in passed-in object(s).
|
||||
_.extend = function(obj) {
|
||||
each(slice.call(arguments, 1), function(source) {
|
||||
for (var prop in source) {
|
||||
if (source[prop] !== void 0) obj[prop] = source[prop];
|
||||
}
|
||||
});
|
||||
return obj;
|
||||
};
|
||||
|
||||
// Fill in a given object with default properties.
|
||||
_.defaults = function(obj) {
|
||||
each(slice.call(arguments, 1), function(source) {
|
||||
for (var prop in source) {
|
||||
if (obj[prop] == null) obj[prop] = source[prop];
|
||||
}
|
||||
});
|
||||
return obj;
|
||||
};
|
||||
|
||||
// Create a (shallow-cloned) duplicate of an object.
|
||||
_.clone = function(obj) {
|
||||
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
|
||||
};
|
||||
|
||||
// Invokes interceptor with the obj, and then returns obj.
|
||||
// The primary purpose of this method is to "tap into" a method chain, in
|
||||
// order to perform operations on intermediate results within the chain.
|
||||
_.tap = function(obj, interceptor) {
|
||||
interceptor(obj);
|
||||
return obj;
|
||||
};
|
||||
|
||||
// Perform a deep comparison to check if two objects are equal.
|
||||
_.isEqual = function(a, b) {
|
||||
// Check object identity.
|
||||
if (a === b) return true;
|
||||
// Different types?
|
||||
var atype = typeof(a), btype = typeof(b);
|
||||
if (atype != btype) return false;
|
||||
// Basic equality test (watch out for coercions).
|
||||
if (a == b) return true;
|
||||
// One is falsy and the other truthy.
|
||||
if ((!a && b) || (a && !b)) return false;
|
||||
// Unwrap any wrapped objects.
|
||||
if (a._chain) a = a._wrapped;
|
||||
if (b._chain) b = b._wrapped;
|
||||
// One of them implements an isEqual()?
|
||||
if (a.isEqual) return a.isEqual(b);
|
||||
if (b.isEqual) return b.isEqual(a);
|
||||
// Check dates' integer values.
|
||||
if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime();
|
||||
// Both are NaN?
|
||||
if (_.isNaN(a) && _.isNaN(b)) return false;
|
||||
// Compare regular expressions.
|
||||
if (_.isRegExp(a) && _.isRegExp(b))
|
||||
return a.source === b.source &&
|
||||
a.global === b.global &&
|
||||
a.ignoreCase === b.ignoreCase &&
|
||||
a.multiline === b.multiline;
|
||||
// If a is not an object by this point, we can't handle it.
|
||||
if (atype !== 'object') return false;
|
||||
// Check for different array lengths before comparing contents.
|
||||
if (a.length && (a.length !== b.length)) return false;
|
||||
// Nothing else worked, deep compare the contents.
|
||||
var aKeys = _.keys(a), bKeys = _.keys(b);
|
||||
// Different object sizes?
|
||||
if (aKeys.length != bKeys.length) return false;
|
||||
// Recursive comparison of contents.
|
||||
for (var key in a) if (!(key in b) || !_.isEqual(a[key], b[key])) return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
// Is a given array or object empty?
|
||||
_.isEmpty = function(obj) {
|
||||
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
|
||||
for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
// Is a given value a DOM element?
|
||||
_.isElement = function(obj) {
|
||||
return !!(obj && obj.nodeType == 1);
|
||||
};
|
||||
|
||||
// Is a given value an array?
|
||||
// Delegates to ECMA5's native Array.isArray
|
||||
_.isArray = nativeIsArray || function(obj) {
|
||||
return toString.call(obj) === '[object Array]';
|
||||
};
|
||||
|
||||
// Is a given variable an object?
|
||||
_.isObject = function(obj) {
|
||||
return obj === Object(obj);
|
||||
};
|
||||
|
||||
// Is a given variable an arguments object?
|
||||
_.isArguments = function(obj) {
|
||||
return !!(obj && hasOwnProperty.call(obj, 'callee'));
|
||||
};
|
||||
|
||||
// Is a given value a function?
|
||||
_.isFunction = function(obj) {
|
||||
return !!(obj && obj.constructor && obj.call && obj.apply);
|
||||
};
|
||||
|
||||
// Is a given value a string?
|
||||
_.isString = function(obj) {
|
||||
return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
|
||||
};
|
||||
|
||||
// Is a given value a number?
|
||||
_.isNumber = function(obj) {
|
||||
return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed));
|
||||
};
|
||||
|
||||
// Is the given value `NaN`? `NaN` happens to be the only value in JavaScript
|
||||
// that does not equal itself.
|
||||
_.isNaN = function(obj) {
|
||||
return obj !== obj;
|
||||
};
|
||||
|
||||
// Is a given value a boolean?
|
||||
_.isBoolean = function(obj) {
|
||||
return obj === true || obj === false;
|
||||
};
|
||||
|
||||
// Is a given value a date?
|
||||
_.isDate = function(obj) {
|
||||
return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear);
|
||||
};
|
||||
|
||||
// Is the given value a regular expression?
|
||||
_.isRegExp = function(obj) {
|
||||
return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
|
||||
};
|
||||
|
||||
// Is a given value equal to null?
|
||||
_.isNull = function(obj) {
|
||||
return obj === null;
|
||||
};
|
||||
|
||||
// Is a given variable undefined?
|
||||
_.isUndefined = function(obj) {
|
||||
return obj === void 0;
|
||||
};
|
||||
|
||||
// Utility Functions
|
||||
// -----------------
|
||||
|
||||
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
|
||||
// previous owner. Returns a reference to the Underscore object.
|
||||
_.noConflict = function() {
|
||||
root._ = previousUnderscore;
|
||||
return this;
|
||||
};
|
||||
|
||||
// Keep the identity function around for default iterators.
|
||||
_.identity = function(value) {
|
||||
return value;
|
||||
};
|
||||
|
||||
// Run a function **n** times.
|
||||
_.times = function (n, iterator, context) {
|
||||
for (var i = 0; i < n; i++) iterator.call(context, i);
|
||||
};
|
||||
|
||||
// Add your own custom functions to the Underscore object, ensuring that
|
||||
// they're correctly added to the OOP wrapper as well.
|
||||
_.mixin = function(obj) {
|
||||
each(_.functions(obj), function(name){
|
||||
addToWrapper(name, _[name] = obj[name]);
|
||||
});
|
||||
};
|
||||
|
||||
// Generate a unique integer id (unique within the entire client session).
|
||||
// Useful for temporary DOM ids.
|
||||
var idCounter = 0;
|
||||
_.uniqueId = function(prefix) {
|
||||
var id = idCounter++;
|
||||
return prefix ? prefix + id : id;
|
||||
};
|
||||
|
||||
// By default, Underscore uses ERB-style template delimiters, change the
|
||||
// following template settings to use alternative delimiters.
|
||||
_.templateSettings = {
|
||||
evaluate : /<%([\s\S]+?)%>/g,
|
||||
interpolate : /<%=([\s\S]+?)%>/g
|
||||
};
|
||||
|
||||
// JavaScript micro-templating, similar to John Resig's implementation.
|
||||
// Underscore templating handles arbitrary delimiters, preserves whitespace,
|
||||
// and correctly escapes quotes within interpolated code.
|
||||
_.template = function(str, data) {
|
||||
var c = _.templateSettings;
|
||||
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
|
||||
'with(obj||{}){__p.push(\'' +
|
||||
str.replace(/\\/g, '\\\\')
|
||||
.replace(/'/g, "\\'")
|
||||
.replace(c.interpolate, function(match, code) {
|
||||
return "'," + code.replace(/\\'/g, "'") + ",'";
|
||||
})
|
||||
.replace(c.evaluate || null, function(match, code) {
|
||||
return "');" + code.replace(/\\'/g, "'")
|
||||
.replace(/[\r\n\t]/g, ' ') + "__p.push('";
|
||||
})
|
||||
.replace(/\r/g, '\\r')
|
||||
.replace(/\n/g, '\\n')
|
||||
.replace(/\t/g, '\\t')
|
||||
+ "');}return __p.join('');";
|
||||
var func = new Function('obj', tmpl);
|
||||
return data ? func(data) : func;
|
||||
};
|
||||
|
||||
// The OOP Wrapper
|
||||
// ---------------
|
||||
|
||||
// If Underscore is called as a function, it returns a wrapped object that
|
||||
// can be used OO-style. This wrapper holds altered versions of all the
|
||||
// underscore functions. Wrapped objects may be chained.
|
||||
var wrapper = function(obj) { this._wrapped = obj; };
|
||||
|
||||
// Expose `wrapper.prototype` as `_.prototype`
|
||||
_.prototype = wrapper.prototype;
|
||||
|
||||
// Helper function to continue chaining intermediate results.
|
||||
var result = function(obj, chain) {
|
||||
return chain ? _(obj).chain() : obj;
|
||||
};
|
||||
|
||||
// A method to easily add functions to the OOP wrapper.
|
||||
var addToWrapper = function(name, func) {
|
||||
wrapper.prototype[name] = function() {
|
||||
var args = slice.call(arguments);
|
||||
unshift.call(args, this._wrapped);
|
||||
return result(func.apply(_, args), this._chain);
|
||||
};
|
||||
};
|
||||
|
||||
// Add all of the Underscore functions to the wrapper object.
|
||||
_.mixin(_);
|
||||
|
||||
// Add all mutator Array functions to the wrapper.
|
||||
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
|
||||
var method = ArrayProto[name];
|
||||
wrapper.prototype[name] = function() {
|
||||
method.apply(this._wrapped, arguments);
|
||||
return result(this._wrapped, this._chain);
|
||||
};
|
||||
});
|
||||
|
||||
// Add all accessor Array functions to the wrapper.
|
||||
each(['concat', 'join', 'slice'], function(name) {
|
||||
var method = ArrayProto[name];
|
||||
wrapper.prototype[name] = function() {
|
||||
return result(method.apply(this._wrapped, arguments), this._chain);
|
||||
};
|
||||
});
|
||||
|
||||
// Start chaining a wrapped Underscore object.
|
||||
wrapper.prototype.chain = function() {
|
||||
this._chain = true;
|
||||
return this;
|
||||
};
|
||||
|
||||
// Extracts the result from a wrapped and chained object.
|
||||
wrapper.prototype.value = function() {
|
||||
return this._wrapped;
|
||||
};
|
||||
|
||||
})();
|
||||
11
example/standard/style.css
Normal file
11
example/standard/style.css
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
div {
|
||||
font-family: Tahoma, Arial;
|
||||
font-size: 10pt;
|
||||
}
|
||||
|
||||
.results {
|
||||
margin-bottom:20px;
|
||||
padding: 10px;
|
||||
border-top: 1pt solid lightsteelblue;
|
||||
border-bottom: 1pt solid lightsteelblue;
|
||||
}
|
||||
20
lib/browser/amd/postal.diagnostics.js
Normal file
20
lib/browser/amd/postal.diagnostics.js
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
define(['postal', 'underscore'], function(postal, _) {
|
||||
postal.addWireTap(function(data, envelope) {
|
||||
var all = _.extend(envelope, { data: data });
|
||||
if(!JSON) {
|
||||
throw "This browser or environment does not provide JSON support";
|
||||
}
|
||||
try {
|
||||
console.log(JSON.stringify(all));
|
||||
}
|
||||
catch(exception) {
|
||||
try {
|
||||
all.data = "ERROR: " + exception.message;
|
||||
console.log(JSON.stringify(all));
|
||||
}
|
||||
catch(ex) {
|
||||
console.log("Unable to parse data to JSON: " + exception);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
BIN
lib/browser/amd/postal.diagnostics.min.gz.js
Normal file
BIN
lib/browser/amd/postal.diagnostics.min.gz.js
Normal file
Binary file not shown.
1
lib/browser/amd/postal.diagnostics.min.js
vendored
Normal file
1
lib/browser/amd/postal.diagnostics.min.js
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
define(["postal","underscore"],function(a,b){a.addWireTap(function(a,c){var d=b.extend(c,{data:a});if(!JSON)throw"This browser or environment does not provide JSON support";try{console.log(JSON.stringify(d))}catch(e){try{d.data="ERROR: "+e.message,console.log(JSON.stringify(d))}catch(f){console.log("Unable to parse data to JSON: "+e)}}})})
|
||||
329
lib/browser/amd/postal.js
Normal file
329
lib/browser/amd/postal.js
Normal file
|
|
@ -0,0 +1,329 @@
|
|||
define(['underscore'], function(_) {
|
||||
/*
|
||||
postal.js
|
||||
Author: Jim Cowart
|
||||
License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license)
|
||||
Version 0.4.0
|
||||
*/
|
||||
|
||||
var DEFAULT_EXCHANGE = "/",
|
||||
DEFAULT_PRIORITY = 50,
|
||||
DEFAULT_DISPOSEAFTER = 0,
|
||||
NO_OP = function() { },
|
||||
parsePublishArgs = function(args) {
|
||||
var parsed = { envelope: { } }, env;
|
||||
switch(args.length) {
|
||||
case 3:
|
||||
if(typeof args[1] === "Object" && typeof args[2] === "Object") {
|
||||
parsed.envelope.exchange = DEFAULT_EXCHANGE;
|
||||
parsed.envelope.topic = args[0];
|
||||
parsed.payload = args[1];
|
||||
env = parsed.envelope;
|
||||
parsed.envelope = _.extend(env, args[2]);
|
||||
}
|
||||
else {
|
||||
parsed.envelope.exchange = args[0];
|
||||
parsed.envelope.topic = args[1];
|
||||
parsed.payload = args[2];
|
||||
}
|
||||
break;
|
||||
case 4:
|
||||
parsed.envelope.exchange = args[0];
|
||||
parsed.envelope.topic = args[1];
|
||||
parsed.payload = args[2];
|
||||
env = parsed.envelope;
|
||||
parsed.envelope = _.extend(env, args[3]);
|
||||
break;
|
||||
default:
|
||||
parsed.envelope.exchange = DEFAULT_EXCHANGE;
|
||||
parsed.envelope.topic = args[0];
|
||||
parsed.payload = args[1];
|
||||
break;
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
|
||||
var DistinctPredicate = function() {
|
||||
var previous;
|
||||
return function(data) {
|
||||
var eq = false;
|
||||
if(_.isString(data)) {
|
||||
eq = data === previous;
|
||||
previous = data;
|
||||
}
|
||||
else {
|
||||
eq = _.isEqual(data, previous);
|
||||
previous = _.clone(data);
|
||||
}
|
||||
return !eq;
|
||||
};
|
||||
};
|
||||
|
||||
var ChannelDefinition = function(exchange, topic) {
|
||||
this.exchange = exchange;
|
||||
this.topic = topic;
|
||||
};
|
||||
|
||||
ChannelDefinition.prototype = {
|
||||
subscribe: function(callback) {
|
||||
var subscription = new SubscriptionDefinition(this.exchange, this.topic, callback);
|
||||
postal.configuration.bus.subscribe(subscription);
|
||||
return subscription;
|
||||
},
|
||||
|
||||
publish: function(data, envelope) {
|
||||
var env = _.extend({
|
||||
exchange: this.exchange,
|
||||
timeStamp: new Date(),
|
||||
topic: this.topic
|
||||
}, envelope);
|
||||
postal.configuration.bus.publish(data, env);
|
||||
}
|
||||
};
|
||||
|
||||
var SubscriptionDefinition = function(exchange, topic, callback) {
|
||||
this.exchange = exchange;
|
||||
this.topic = topic;
|
||||
this.callback = callback;
|
||||
this.priority = DEFAULT_PRIORITY;
|
||||
this.constraints = [];
|
||||
this.maxCalls = DEFAULT_DISPOSEAFTER;
|
||||
this.onHandled = NO_OP;
|
||||
this.context = null;
|
||||
};
|
||||
|
||||
SubscriptionDefinition.prototype = {
|
||||
unsubscribe: function() {
|
||||
postal.configuration.bus.unsubscribe(this);
|
||||
},
|
||||
|
||||
defer: function() {
|
||||
var fn = this.callback;
|
||||
this.callback = function(data) {
|
||||
setTimeout(fn,0,data);
|
||||
};
|
||||
return this;
|
||||
},
|
||||
|
||||
disposeAfter: function(maxCalls) {
|
||||
if(_.isNaN(maxCalls) || maxCalls <= 0) {
|
||||
throw "The value provided to disposeAfter (maxCalls) must be a number greater than zero.";
|
||||
}
|
||||
|
||||
var fn = this.onHandled;
|
||||
var dispose = _.after(maxCalls, _.bind(function() {
|
||||
this.unsubscribe(this);
|
||||
}, this));
|
||||
|
||||
this.onHandled = function() {
|
||||
fn.apply(this.context, arguments);
|
||||
dispose();
|
||||
};
|
||||
return this;
|
||||
},
|
||||
|
||||
ignoreDuplicates: function() {
|
||||
this.withConstraint(new DistinctPredicate());
|
||||
return this;
|
||||
},
|
||||
|
||||
whenHandledThenExecute: function(callback) {
|
||||
if(! _.isFunction(callback)) {
|
||||
throw "Value provided to 'whenHandledThenExecute' must be a function";
|
||||
}
|
||||
this.onHandled = callback;
|
||||
return this;
|
||||
},
|
||||
|
||||
withConstraint: function(predicate) {
|
||||
if(! _.isFunction(predicate)) {
|
||||
throw "Predicate constraint must be a function";
|
||||
}
|
||||
this.constraints.push(predicate);
|
||||
return this;
|
||||
},
|
||||
|
||||
withConstraints: function(predicates) {
|
||||
var self = this;
|
||||
if(_.isArray(predicates)) {
|
||||
_.each(predicates, function(predicate) { self.withConstraint(predicate); } );
|
||||
}
|
||||
return self;
|
||||
},
|
||||
|
||||
withContext: function(context) {
|
||||
this.context = context;
|
||||
return this;
|
||||
},
|
||||
|
||||
withDebounce: function(milliseconds) {
|
||||
if(_.isNaN(milliseconds)) {
|
||||
throw "Milliseconds must be a number";
|
||||
}
|
||||
var fn = this.callback;
|
||||
this.callback = _.debounce(fn, milliseconds);
|
||||
return this;
|
||||
},
|
||||
|
||||
withDelay: function(milliseconds) {
|
||||
if(_.isNaN(milliseconds)) {
|
||||
throw "Milliseconds must be a number";
|
||||
}
|
||||
var fn = this.callback;
|
||||
this.callback = function(data) {
|
||||
setTimeout(fn, milliseconds, data);
|
||||
};
|
||||
return this;
|
||||
},
|
||||
|
||||
withPriority: function(priority) {
|
||||
if(_.isNaN(priority)) {
|
||||
throw "Priority must be a number";
|
||||
}
|
||||
this.priority = priority;
|
||||
return this;
|
||||
},
|
||||
|
||||
withThrottle: function(milliseconds) {
|
||||
if(_.isNaN(milliseconds)) {
|
||||
throw "Milliseconds must be a number";
|
||||
}
|
||||
var fn = this.callback;
|
||||
this.callback = _.throttle(fn, milliseconds);
|
||||
return this;
|
||||
}
|
||||
};
|
||||
|
||||
var bindingsResolver = {
|
||||
cache: { },
|
||||
|
||||
compare: function(binding, topic) {
|
||||
if(this.cache[topic] && this.cache[topic][binding]) {
|
||||
return true;
|
||||
}
|
||||
var rgx = new RegExp("^" + this.regexify(binding) + "$"), // match from start to end of string
|
||||
result = rgx.test(topic);
|
||||
if(result) {
|
||||
if(!this.cache[topic]) {
|
||||
this.cache[topic] = {};
|
||||
}
|
||||
this.cache[topic][binding] = true;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
regexify: function(binding) {
|
||||
return binding.replace(/\./g,"\\.") // escape actual periods
|
||||
.replace(/\*/g, ".*") // asterisks match any value
|
||||
.replace(/#/g, "[A-Z,a-z,0-9]*"); // hash matches any alpha-numeric 'word'
|
||||
}
|
||||
};
|
||||
|
||||
var localBus = {
|
||||
|
||||
subscriptions: {},
|
||||
|
||||
wireTaps: [],
|
||||
|
||||
publish: function(data, envelope) {
|
||||
_.each(this.wireTaps,function(tap) {
|
||||
tap(data, envelope);
|
||||
});
|
||||
|
||||
_.each(this.subscriptions[envelope.exchange], function(topic) {
|
||||
_.each(topic, function(binding){
|
||||
if(postal.configuration.resolver.compare(binding.topic, envelope.topic)) {
|
||||
if(_.all(binding.constraints, function(constraint) { return constraint(data); })) {
|
||||
if(typeof binding.callback === 'function') {
|
||||
binding.callback.apply(binding.context, [data, envelope]);
|
||||
binding.onHandled();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
subscribe: function(subDef) {
|
||||
var idx, found, fn;
|
||||
|
||||
if(!this.subscriptions[subDef.exchange]) {
|
||||
this.subscriptions[subDef.exchange] = {};
|
||||
}
|
||||
if(!this.subscriptions[subDef.exchange][subDef.topic]) {
|
||||
this.subscriptions[subDef.exchange][subDef.topic] = [];
|
||||
}
|
||||
|
||||
idx = this.subscriptions[subDef.exchange][subDef.topic].length - 1;
|
||||
if(!_.any(this.subscriptions[subDef.exchange][subDef.topic], function(cfg) { return cfg === subDef; })) {
|
||||
for(; idx >= 0; idx--) {
|
||||
if(this.subscriptions[subDef.exchange][subDef.topic][idx].priority <= subDef.priority) {
|
||||
this.subscriptions[subDef.exchange][subDef.topic].splice(idx + 1, 0, subDef);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(!found) {
|
||||
this.subscriptions[subDef.exchange][subDef.topic].unshift(subDef);
|
||||
}
|
||||
}
|
||||
|
||||
return _.bind(function() { this.unsubscribe(subDef); }, this);
|
||||
},
|
||||
|
||||
unsubscribe: function(config) {
|
||||
if(this.subscriptions[config.exchange][config.topic]) {
|
||||
var len = this.subscriptions[config.exchange][config.topic].length,
|
||||
idx = 0;
|
||||
for ( ; idx < len; idx++ ) {
|
||||
if (this.subscriptions[config.exchange][config.topic][idx] === config) {
|
||||
this.subscriptions[config.exchange][config.topic].splice( idx, 1 );
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
addWireTap: function(callback) {
|
||||
this.wireTaps.push(callback);
|
||||
return function() {
|
||||
var idx = this.wireTaps.indexOf(callback);
|
||||
if(idx !== -1) {
|
||||
this.wireTaps.splice(idx,1);
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
var postal = {
|
||||
configuration: {
|
||||
bus: localBus,
|
||||
resolver: bindingsResolver
|
||||
},
|
||||
|
||||
channel: function(exchange, topic) {
|
||||
var exch = arguments.length === 2 ? exchange : DEFAULT_EXCHANGE,
|
||||
tpc = arguments.length === 2 ? topic : exchange;
|
||||
return new ChannelDefinition(exch, tpc);
|
||||
},
|
||||
|
||||
subscribe: function(exchange, topic, callback) {
|
||||
var exch = arguments.length === 3 ? exchange : DEFAULT_EXCHANGE,
|
||||
tpc = arguments.length === 3 ? topic : exchange,
|
||||
callbk = arguments.length === 3 ? callback : topic;
|
||||
var channel = this.channel(exch, tpc);
|
||||
return channel.subscribe(callbk);
|
||||
},
|
||||
|
||||
publish: function(exchange, topic, payload, envelopeOptions) {
|
||||
var parsedArgs = parsePublishArgs([].slice.call(arguments,0));
|
||||
var channel = this.channel(parsedArgs.envelope.exchange, parsedArgs.envelope.topic);
|
||||
channel.publish(parsedArgs.payload, parsedArgs.envelope);
|
||||
},
|
||||
|
||||
addWireTap: function(callback) {
|
||||
this.configuration.bus.addWireTap(callback);
|
||||
}
|
||||
};
|
||||
|
||||
return postal; });
|
||||
BIN
lib/browser/amd/postal.min.gz.js
Normal file
BIN
lib/browser/amd/postal.min.gz.js
Normal file
Binary file not shown.
1
lib/browser/amd/postal.min.js
vendored
Normal file
1
lib/browser/amd/postal.min.js
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
define(["underscore"],function(a){var b="/",c=50,d=0,e=function(){},f=function(c){var d={envelope:{}},e;switch(c.length){case 3:typeof c[1]=="Object"&&typeof c[2]=="Object"?(d.envelope.exchange=b,d.envelope.topic=c[0],d.payload=c[1],e=d.envelope,d.envelope=a.extend(e,c[2])):(d.envelope.exchange=c[0],d.envelope.topic=c[1],d.payload=c[2]);break;case 4:d.envelope.exchange=c[0],d.envelope.topic=c[1],d.payload=c[2],e=d.envelope,d.envelope=a.extend(e,c[3]);break;default:d.envelope.exchange=b,d.envelope.topic=c[0],d.payload=c[1]}return d},g=function(){var b;return function(c){var d=!1;return a.isString(c)?(d=c===b,b=c):(d=a.isEqual(c,b),b=a.clone(c)),!d}},h=function(a,b){this.exchange=a,this.topic=b};h.prototype={subscribe:function(a){var b=new i(this.exchange,this.topic,a);return l.configuration.bus.subscribe(b),b},publish:function(b,c){var d=a.extend({exchange:this.exchange,timeStamp:new Date,topic:this.topic},c);l.configuration.bus.publish(b,d)}};var i=function(a,b,f){this.exchange=a,this.topic=b,this.callback=f,this.priority=c,this.constraints=[],this.maxCalls=d,this.onHandled=e,this.context=null};i.prototype={unsubscribe:function(){l.configuration.bus.unsubscribe(this)},defer:function(){var a=this.callback;return this.callback=function(b){setTimeout(a,0,b)},this},disposeAfter:function(b){if(a.isNaN(b)||b<=0)throw"The value provided to disposeAfter (maxCalls) must be a number greater than zero.";var c=this.onHandled,d=a.after(b,a.bind(function(){this.unsubscribe(this)},this));return this.onHandled=function(){c.apply(this.context,arguments),d()},this},ignoreDuplicates:function(){return this.withConstraint(new g),this},whenHandledThenExecute:function(b){if(!a.isFunction(b))throw"Value provided to 'whenHandledThenExecute' must be a function";return this.onHandled=b,this},withConstraint:function(b){if(!a.isFunction(b))throw"Predicate constraint must be a function";return this.constraints.push(b),this},withConstraints:function(b){var c=this;return a.isArray(b)&&a.each(b,function(a){c.withConstraint(a)}),c},withContext:function(a){return this.context=a,this},withDebounce:function(b){if(a.isNaN(b))throw"Milliseconds must be a number";var c=this.callback;return this.callback=a.debounce(c,b),this},withDelay:function(b){if(a.isNaN(b))throw"Milliseconds must be a number";var c=this.callback;return this.callback=function(a){setTimeout(c,b,a)},this},withPriority:function(b){if(a.isNaN(b))throw"Priority must be a number";return this.priority=b,this},withThrottle:function(b){if(a.isNaN(b))throw"Milliseconds must be a number";var c=this.callback;return this.callback=a.throttle(c,b),this}};var j={cache:{},compare:function(a,b){if(this.cache[b]&&this.cache[b][a])return!0;var c=new RegExp("^"+this.regexify(a)+"$"),d=c.test(b);return d&&(this.cache[b]||(this.cache[b]={}),this.cache[b][a]=!0),d},regexify:function(a){return a.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/#/g,"[A-Z,a-z,0-9]*")}},k={subscriptions:{},wireTaps:[],publish:function(b,c){a.each(this.wireTaps,function(a){a(b,c)}),a.each(this.subscriptions[c.exchange],function(d){a.each(d,function(d){l.configuration.resolver.compare(d.topic,c.topic)&&a.all(d.constraints,function(a){return a(b)})&&typeof d.callback=="function"&&(d.callback.apply(d.context,[b,c]),d.onHandled())})})},subscribe:function(b){var c,d,e;this.subscriptions[b.exchange]||(this.subscriptions[b.exchange]={}),this.subscriptions[b.exchange][b.topic]||(this.subscriptions[b.exchange][b.topic]=[]),c=this.subscriptions[b.exchange][b.topic].length-1;if(!a.any(this.subscriptions[b.exchange][b.topic],function(a){return a===b})){for(;c>=0;c--)if(this.subscriptions[b.exchange][b.topic][c].priority<=b.priority){this.subscriptions[b.exchange][b.topic].splice(c+1,0,b),d=!0;break}d||this.subscriptions[b.exchange][b.topic].unshift(b)}return a.bind(function(){this.unsubscribe(b)},this)},unsubscribe:function(a){if(this.subscriptions[a.exchange][a.topic]){var b=this.subscriptions[a.exchange][a.topic].length,c=0;for(;c<b;c++)if(this.subscriptions[a.exchange][a.topic][c]===a){this.subscriptions[a.exchange][a.topic].splice(c,1);break}}},addWireTap:function(a){return this.wireTaps.push(a),function(){var b=this.wireTaps.indexOf(a);b!==-1&&this.wireTaps.splice(b,1)}}},l={configuration:{bus:k,resolver:j},channel:function(a,c){var d=arguments.length===2?a:b,e=arguments.length===2?c:a;return new h(d,e)},subscribe:function(a,c,d){var e=arguments.length===3?a:b,f=arguments.length===3?c:a,g=arguments.length===3?d:c,h=this.channel(e,f);return h.subscribe(g)},publish:function(a,b,c,d){var e=f([].slice.call(arguments,0)),g=this.channel(e.envelope.exchange,e.envelope.topic);g.publish(e.payload,e.envelope)},addWireTap:function(a){this.configuration.bus.addWireTap(a)}};return l})
|
||||
18
lib/browser/standard/postal.diagnostics.js
Normal file
18
lib/browser/standard/postal.diagnostics.js
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
postal.addWireTap(function(data, envelope) {
|
||||
var all = _.extend(envelope, { data: data });
|
||||
if(!JSON) {
|
||||
throw "This browser or environment does not provide JSON support";
|
||||
}
|
||||
try {
|
||||
console.log(JSON.stringify(all));
|
||||
}
|
||||
catch(exception) {
|
||||
try {
|
||||
all.data = "ERROR: " + exception.message;
|
||||
console.log(JSON.stringify(all));
|
||||
}
|
||||
catch(ex) {
|
||||
console.log("Unable to parse data to JSON: " + exception);
|
||||
}
|
||||
}
|
||||
});
|
||||
Binary file not shown.
329
lib/browser/standard/postal.js
Normal file
329
lib/browser/standard/postal.js
Normal file
|
|
@ -0,0 +1,329 @@
|
|||
(function(global, undefined) {
|
||||
/*
|
||||
postal.js
|
||||
Author: Jim Cowart
|
||||
License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license)
|
||||
Version 0.4.0
|
||||
*/
|
||||
|
||||
var DEFAULT_EXCHANGE = "/",
|
||||
DEFAULT_PRIORITY = 50,
|
||||
DEFAULT_DISPOSEAFTER = 0,
|
||||
NO_OP = function() { },
|
||||
parsePublishArgs = function(args) {
|
||||
var parsed = { envelope: { } }, env;
|
||||
switch(args.length) {
|
||||
case 3:
|
||||
if(typeof args[1] === "Object" && typeof args[2] === "Object") {
|
||||
parsed.envelope.exchange = DEFAULT_EXCHANGE;
|
||||
parsed.envelope.topic = args[0];
|
||||
parsed.payload = args[1];
|
||||
env = parsed.envelope;
|
||||
parsed.envelope = _.extend(env, args[2]);
|
||||
}
|
||||
else {
|
||||
parsed.envelope.exchange = args[0];
|
||||
parsed.envelope.topic = args[1];
|
||||
parsed.payload = args[2];
|
||||
}
|
||||
break;
|
||||
case 4:
|
||||
parsed.envelope.exchange = args[0];
|
||||
parsed.envelope.topic = args[1];
|
||||
parsed.payload = args[2];
|
||||
env = parsed.envelope;
|
||||
parsed.envelope = _.extend(env, args[3]);
|
||||
break;
|
||||
default:
|
||||
parsed.envelope.exchange = DEFAULT_EXCHANGE;
|
||||
parsed.envelope.topic = args[0];
|
||||
parsed.payload = args[1];
|
||||
break;
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
|
||||
var DistinctPredicate = function() {
|
||||
var previous;
|
||||
return function(data) {
|
||||
var eq = false;
|
||||
if(_.isString(data)) {
|
||||
eq = data === previous;
|
||||
previous = data;
|
||||
}
|
||||
else {
|
||||
eq = _.isEqual(data, previous);
|
||||
previous = _.clone(data);
|
||||
}
|
||||
return !eq;
|
||||
};
|
||||
};
|
||||
|
||||
var ChannelDefinition = function(exchange, topic) {
|
||||
this.exchange = exchange;
|
||||
this.topic = topic;
|
||||
};
|
||||
|
||||
ChannelDefinition.prototype = {
|
||||
subscribe: function(callback) {
|
||||
var subscription = new SubscriptionDefinition(this.exchange, this.topic, callback);
|
||||
postal.configuration.bus.subscribe(subscription);
|
||||
return subscription;
|
||||
},
|
||||
|
||||
publish: function(data, envelope) {
|
||||
var env = _.extend({
|
||||
exchange: this.exchange,
|
||||
timeStamp: new Date(),
|
||||
topic: this.topic
|
||||
}, envelope);
|
||||
postal.configuration.bus.publish(data, env);
|
||||
}
|
||||
};
|
||||
|
||||
var SubscriptionDefinition = function(exchange, topic, callback) {
|
||||
this.exchange = exchange;
|
||||
this.topic = topic;
|
||||
this.callback = callback;
|
||||
this.priority = DEFAULT_PRIORITY;
|
||||
this.constraints = [];
|
||||
this.maxCalls = DEFAULT_DISPOSEAFTER;
|
||||
this.onHandled = NO_OP;
|
||||
this.context = null;
|
||||
};
|
||||
|
||||
SubscriptionDefinition.prototype = {
|
||||
unsubscribe: function() {
|
||||
postal.configuration.bus.unsubscribe(this);
|
||||
},
|
||||
|
||||
defer: function() {
|
||||
var fn = this.callback;
|
||||
this.callback = function(data) {
|
||||
setTimeout(fn,0,data);
|
||||
};
|
||||
return this;
|
||||
},
|
||||
|
||||
disposeAfter: function(maxCalls) {
|
||||
if(_.isNaN(maxCalls) || maxCalls <= 0) {
|
||||
throw "The value provided to disposeAfter (maxCalls) must be a number greater than zero.";
|
||||
}
|
||||
|
||||
var fn = this.onHandled;
|
||||
var dispose = _.after(maxCalls, _.bind(function() {
|
||||
this.unsubscribe(this);
|
||||
}, this));
|
||||
|
||||
this.onHandled = function() {
|
||||
fn.apply(this.context, arguments);
|
||||
dispose();
|
||||
};
|
||||
return this;
|
||||
},
|
||||
|
||||
ignoreDuplicates: function() {
|
||||
this.withConstraint(new DistinctPredicate());
|
||||
return this;
|
||||
},
|
||||
|
||||
whenHandledThenExecute: function(callback) {
|
||||
if(! _.isFunction(callback)) {
|
||||
throw "Value provided to 'whenHandledThenExecute' must be a function";
|
||||
}
|
||||
this.onHandled = callback;
|
||||
return this;
|
||||
},
|
||||
|
||||
withConstraint: function(predicate) {
|
||||
if(! _.isFunction(predicate)) {
|
||||
throw "Predicate constraint must be a function";
|
||||
}
|
||||
this.constraints.push(predicate);
|
||||
return this;
|
||||
},
|
||||
|
||||
withConstraints: function(predicates) {
|
||||
var self = this;
|
||||
if(_.isArray(predicates)) {
|
||||
_.each(predicates, function(predicate) { self.withConstraint(predicate); } );
|
||||
}
|
||||
return self;
|
||||
},
|
||||
|
||||
withContext: function(context) {
|
||||
this.context = context;
|
||||
return this;
|
||||
},
|
||||
|
||||
withDebounce: function(milliseconds) {
|
||||
if(_.isNaN(milliseconds)) {
|
||||
throw "Milliseconds must be a number";
|
||||
}
|
||||
var fn = this.callback;
|
||||
this.callback = _.debounce(fn, milliseconds);
|
||||
return this;
|
||||
},
|
||||
|
||||
withDelay: function(milliseconds) {
|
||||
if(_.isNaN(milliseconds)) {
|
||||
throw "Milliseconds must be a number";
|
||||
}
|
||||
var fn = this.callback;
|
||||
this.callback = function(data) {
|
||||
setTimeout(fn, milliseconds, data);
|
||||
};
|
||||
return this;
|
||||
},
|
||||
|
||||
withPriority: function(priority) {
|
||||
if(_.isNaN(priority)) {
|
||||
throw "Priority must be a number";
|
||||
}
|
||||
this.priority = priority;
|
||||
return this;
|
||||
},
|
||||
|
||||
withThrottle: function(milliseconds) {
|
||||
if(_.isNaN(milliseconds)) {
|
||||
throw "Milliseconds must be a number";
|
||||
}
|
||||
var fn = this.callback;
|
||||
this.callback = _.throttle(fn, milliseconds);
|
||||
return this;
|
||||
}
|
||||
};
|
||||
|
||||
var bindingsResolver = {
|
||||
cache: { },
|
||||
|
||||
compare: function(binding, topic) {
|
||||
if(this.cache[topic] && this.cache[topic][binding]) {
|
||||
return true;
|
||||
}
|
||||
var rgx = new RegExp("^" + this.regexify(binding) + "$"), // match from start to end of string
|
||||
result = rgx.test(topic);
|
||||
if(result) {
|
||||
if(!this.cache[topic]) {
|
||||
this.cache[topic] = {};
|
||||
}
|
||||
this.cache[topic][binding] = true;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
regexify: function(binding) {
|
||||
return binding.replace(/\./g,"\\.") // escape actual periods
|
||||
.replace(/\*/g, ".*") // asterisks match any value
|
||||
.replace(/#/g, "[A-Z,a-z,0-9]*"); // hash matches any alpha-numeric 'word'
|
||||
}
|
||||
};
|
||||
|
||||
var localBus = {
|
||||
|
||||
subscriptions: {},
|
||||
|
||||
wireTaps: [],
|
||||
|
||||
publish: function(data, envelope) {
|
||||
_.each(this.wireTaps,function(tap) {
|
||||
tap(data, envelope);
|
||||
});
|
||||
|
||||
_.each(this.subscriptions[envelope.exchange], function(topic) {
|
||||
_.each(topic, function(binding){
|
||||
if(postal.configuration.resolver.compare(binding.topic, envelope.topic)) {
|
||||
if(_.all(binding.constraints, function(constraint) { return constraint(data); })) {
|
||||
if(typeof binding.callback === 'function') {
|
||||
binding.callback.apply(binding.context, [data, envelope]);
|
||||
binding.onHandled();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
subscribe: function(subDef) {
|
||||
var idx, found, fn;
|
||||
|
||||
if(!this.subscriptions[subDef.exchange]) {
|
||||
this.subscriptions[subDef.exchange] = {};
|
||||
}
|
||||
if(!this.subscriptions[subDef.exchange][subDef.topic]) {
|
||||
this.subscriptions[subDef.exchange][subDef.topic] = [];
|
||||
}
|
||||
|
||||
idx = this.subscriptions[subDef.exchange][subDef.topic].length - 1;
|
||||
if(!_.any(this.subscriptions[subDef.exchange][subDef.topic], function(cfg) { return cfg === subDef; })) {
|
||||
for(; idx >= 0; idx--) {
|
||||
if(this.subscriptions[subDef.exchange][subDef.topic][idx].priority <= subDef.priority) {
|
||||
this.subscriptions[subDef.exchange][subDef.topic].splice(idx + 1, 0, subDef);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(!found) {
|
||||
this.subscriptions[subDef.exchange][subDef.topic].unshift(subDef);
|
||||
}
|
||||
}
|
||||
|
||||
return _.bind(function() { this.unsubscribe(subDef); }, this);
|
||||
},
|
||||
|
||||
unsubscribe: function(config) {
|
||||
if(this.subscriptions[config.exchange][config.topic]) {
|
||||
var len = this.subscriptions[config.exchange][config.topic].length,
|
||||
idx = 0;
|
||||
for ( ; idx < len; idx++ ) {
|
||||
if (this.subscriptions[config.exchange][config.topic][idx] === config) {
|
||||
this.subscriptions[config.exchange][config.topic].splice( idx, 1 );
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
addWireTap: function(callback) {
|
||||
this.wireTaps.push(callback);
|
||||
return function() {
|
||||
var idx = this.wireTaps.indexOf(callback);
|
||||
if(idx !== -1) {
|
||||
this.wireTaps.splice(idx,1);
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
var postal = {
|
||||
configuration: {
|
||||
bus: localBus,
|
||||
resolver: bindingsResolver
|
||||
},
|
||||
|
||||
channel: function(exchange, topic) {
|
||||
var exch = arguments.length === 2 ? exchange : DEFAULT_EXCHANGE,
|
||||
tpc = arguments.length === 2 ? topic : exchange;
|
||||
return new ChannelDefinition(exch, tpc);
|
||||
},
|
||||
|
||||
subscribe: function(exchange, topic, callback) {
|
||||
var exch = arguments.length === 3 ? exchange : DEFAULT_EXCHANGE,
|
||||
tpc = arguments.length === 3 ? topic : exchange,
|
||||
callbk = arguments.length === 3 ? callback : topic;
|
||||
var channel = this.channel(exch, tpc);
|
||||
return channel.subscribe(callbk);
|
||||
},
|
||||
|
||||
publish: function(exchange, topic, payload, envelopeOptions) {
|
||||
var parsedArgs = parsePublishArgs([].slice.call(arguments,0));
|
||||
var channel = this.channel(parsedArgs.envelope.exchange, parsedArgs.envelope.topic);
|
||||
channel.publish(parsedArgs.payload, parsedArgs.envelope);
|
||||
},
|
||||
|
||||
addWireTap: function(callback) {
|
||||
this.configuration.bus.addWireTap(callback);
|
||||
}
|
||||
};
|
||||
|
||||
global.postal = postal; })(window);
|
||||
Binary file not shown.
Loading…
Reference in a new issue