Skip to content

Instantly share code, notes, and snippets.

@humbertodosreis
Last active October 24, 2016 20:43
Show Gist options
  • Save humbertodosreis/f29ad08a996a0ffc0ea8e38792ab47fe to your computer and use it in GitHub Desktop.
Save humbertodosreis/f29ad08a996a0ffc0ea8e38792ab47fe to your computer and use it in GitHub Desktop.
Example pubsub with PubSub lib
// require PubSub.js and jQuery
var Model = (function (pubsub) {
function updatePhone(telefone) {
pubsub.publish("service-started"); // notify observers
$.post('/customer/update-phone', {phone: phone}, function (response) {
if (response.status == true) {
pubsub.publish('phone-updated', {phone: phone}); // notify observers
} else {
// notify observers
pubsub.publish('service-failed', {
error: response.message || 'Service Error. Try Again!'
});
}
}).always(function () {
pubsub.publish("service-finished"); // notify observers
}).fail(function () {
// notify observers
pubsub.publish('service-failed', {
error: 'Service Error. Try Again!'
});
});
}
return {
updatePhone: updatePhone
};
})(PubSub);
var PhoneView = (function ($, pubsub, model, undefined) {
// cache DOM
var $container = $("#any-element")
// events
pubsub.subscribe("phone-updated", phoneUpdatedEventHandler);
pubsub.subscribe("service-failed", serviceFailedEventHandler);
pubsub.subscribe("service-started", serviceStardedEventHandler);
pubsub.subscribe("service-finished", serviceFinishedEventHandler);
function phoneUpdatedEventHandler() {
console.log("phone updated");
}
function serviceFailedEventHandler(msg, data)
{
console.log(data);
console.log("service failed");
}
function serviceStardedEventHandler() {
console.log("service started");
}
function serviceFinishedEventHandler() {
console.log("service finished");
}
return {
init : function () {
model.updatePhone("+55 11 99999-9999");
}
};
})(jQuery, PubSub, Model);
$(document).ready(function () {
PhoneView.init();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment