Share
Embed
An Introduction to Custom Events
Slides from a talk given at Async Brighton on the 25th August 2011 http://asyncjs.com/pubsub/
Aron
September 26, 2011
Transcript
34 slides
-
AsyncJS • 25th August 2011 • Aron Carroll A introduction
to custom events -
AsyncJS • 25th August 2011 • Aron Carroll Introduction •
Simply a way of informing objects of changes • One object broadcasts events (or topics) • Others register interest (or subscribe) by providing a callback for a event to the broadcaster • Callbacks are called each time a event is broadcast -
AsyncJS • 25th August 2011 • Aron Carroll var jeff
= { read: function (issue) { alert("Wow, what interesting content"); } }; newspaper.subscribe("issue", jeff.read); newspaper.publish("issue", new Issue()); // ALERT: "Wow, what interesting content" Navigation -
AsyncJS • 25th August 2011 • Aron Carroll Introduction •
Common idiom on the web • We’re all used to click, submit, load events • Great for decoupling code into smaller modules -
AsyncJS • 25th August 2011 • Aron Carroll Events, Pub/Sub
& Observers • Publish / Subscribe • Observer • Custom Events -
AsyncJS • 25th August 2011 • Aron Carroll redButton.onclick =
function () { launchTheRocketShip(); }; Examples / DOM Events -
AsyncJS • 25th August 2011 • Aron Carroll redButton.addEventListener( "click",
function () { launchTheRocketShip(); }, false ); Examples / DOM Events -
AsyncJS • 25th August 2011 • Aron Carroll function cookRecipe(recipe)
{ // pots, pans, timings etc... } function getMagicRecipe(cb) { return jQuery.get("magic-recipe.txt", cb); } getMagicRecipe(cookRecipe); Examples / jQuery.ajax() -
AsyncJS • 25th August 2011 • Aron Carroll // As
of jQuery 1.5 var request = getMagicRecipe(cookRecipe); request.error(function () { orderFishWithChips(); }); Examples / jQuery.ajax() -
AsyncJS • 25th August 2011 • Aron Carroll var thermos
= new Thermos({ beverage: "tea", fullness: 0.8, temperature: 50 }); // View watches for changes to properties var view = new ThermosStatusView({ model: thermos }); // View automatically updates thermos.drink(0.8); Examples / Backbone -
AsyncJS • 25th August 2011 • Aron Carroll var Thermos
= Model.extend({ drink: function (drunk) { var oldAmount = this.get("fullness"), newAmount = oldAmount - drunk; // .set() publishes a “change” event return this.set({fullness: newAmount}); } }); Examples / Backbone -
AsyncJS • 25th August 2011 • Aron Carroll var ThermosStatusView
= View.extend({ intialize: function () { // View watches for “change” this.model.bind( "change:fullness", this.onFullnessChange ); }, onFullnessChange: function (amount) { if (amount > 0) { this.updateThermosGauge(amount); } else { this.displaySeriousWarningAlert(); } } }); Examples / Backbone -
AsyncJS • 25th August 2011 • Aron Carroll So why
is this useful? -
AsyncJS • 25th August 2011 • Aron Carroll Uses Breaking
UI into components -
AsyncJS • 25th August 2011 • Aron Carroll Uses /
Loose Coupling GenreNavigation FindMeABookForm BookInfo LibraryBooks -
AsyncJS • 25th August 2011 • Aron Carroll Uses /
Loose Coupling GenreNavigation FindMeABookForm BookInfo LibraryBooks ControllerLogic publishes “searched” publishes “changed” publishes “selected” listens to “search” finds matching books updates LibraryBooks listens to “selected” finds book updates BookInfo listens to “changes” finds books in genre updates LibraryBooks -
AsyncJS • 25th August 2011 • Aron Carroll $stall =
$("#circusStall").coconutShy(); $stall.bind("hit", function (coconut) { if (!coconut.isGluedToStand()) { alert("Prizes!"); } }); Uses / Loose Coupling / jQuery Plug-ins -
AsyncJS • 25th August 2011 • Aron Carroll Uses Notification
of changing data & state -
AsyncJS • 25th August 2011 • Aron Carroll Uses /
Notification of changes • UI Elements: Sliders, Pop-ups & Select boxes • Counters & Flags: Message counts, Notifications • Model data: Change of username -
AsyncJS • 25th August 2011 • Aron Carroll Uses /
Notification of changes IngredientsForm CakeListing (will have many cakes) OvenView CakeModel MODELS VIEWS -
AsyncJS • 25th August 2011 • Aron Carroll Uses /
Extensibility Extend an objects functionality by using events to perform a different action or enhance an existing one. This is great for plugins & frameworks. -
AsyncJS • 25th August 2011 • Aron Carroll // Update
the position of a custom marker // when the user pans the map. google.maps.addListener( map, "drag", updateCustomUIPosition ); Uses / Extensibility -
AsyncJS • 25th August 2011 • Aron Carroll Disadvantages •
Harder to debug • Loose coupling -
AsyncJS • 25th August 2011 • Aron Carroll Existing Libraries
• Ben Allman’s TinyPubSub- Great if you use jQuery. But slow as tied to DOM. • PubSub js - Simple and fast. • MicroEvents - Alternative to PubSub • EventEmitter in Node.js • Most JavaScript libraries have own implementation -
AsyncJS • 25th August 2011 • Aron Carroll Summary •
Break your JavaScript into components • Fire events when interesting things happen • (I) prefer observable objects over global pub/sub -
AsyncJS • 25th August 2011 • Aron Carroll Useful Links
• http://msdn.microsoft.com/en-us/scriptjunkie/hh201955 • http://www.addyosmani.com/resources/ essentialjsdesignpatterns/book/#observerpatternjavascript • http://blog.rebeccamurphey.com/pubsub-screencast • http://yehudakatz.com/2009/04/20/evented-programming- with-jquery/ -
AsyncJS • 25th August 2011 • Aron Carroll Useful Links
• TinyPubSub – https://gist.github.com/661855 • PubSubJS – https://github.com/phiggins42/bloody-jquery- plugins/blob/master/pubsub.js • MicroEvents – http://notes.jetienne.com/2011/03/22/ microeventjs.html • EventEmitter – http://nodejs.org/docs/v0.4.9/api/events.html