postal.js examples
Simple examples of postal.js
by ifandelse
HTML
<script src="https://raw.github.com/documentcloud/underscore/master/underscore.js"></script>
<script src="https://raw.github.com/ifandelse/postal.js/master/lib/standard/postal.js"></script>
<script src="https://raw.github.com/documentcloud/backbone/master/backbone-min.js"></script>
JavaScript
(function(Backbone, bus) {
var SecretSauceModel = Backbone.Model.extend({
constructor: function() {
this.on("change:id", _.bind(this.setSubscriptions, this));
Backbone.Model.prototype.constructor.call(this, attributes, options);
this.on("sync", function(model, resp, options){
bus.data.publish({
topic: this.url() + ".localSync",
cid: this.cid,
data: model.toJSON()
})
}, this);
this.activeOperations = {};
},
getIdentifier: function() {
return this.url();
},
setSubscriptions: function() {
this.subscriptions = this.subscriptions || {};
if(this.subscriptions._localSync) {
this.subscriptions._localSync.unsubscribe();
}
if(this.subscriptions._data) {
this.subscriptions._data.unsubscribe();
}
// we're using the model's "cid" as a way to identify the source of the message.
// we allow this model to update locally if another instance (with same url, etc) updated
this.subscriptions._localSync = bus.data.subscribe(this.getIdentifier() + ".localSync", this.routeDataEvent)
.withConstraint(function(d, e){
return e.originatorId !== self.cid;
})
.withContext( this );
this.subscriptions._data = bus.data.subscribe(this.getIdentifier() + ".#", this.routeEvent).withContext(this);
},
routeEvent: function(data, envelope) {
var meta = envelope.topic.split('.');
var handler = meta[meta.length-1];
if(typeof this[handler] === 'function') {
this[handler](data, envelope);
}
}
});
}(Backbone, postal));