Upgrade to Pro — share decks privately, control downloads, hide ads and more …

An Introduction to Custom Events

Avatar for Aron Aron
September 26, 2011

An Introduction to Custom Events

Slides from a talk given at Async Brighton on the 25th August 2011 http://asyncjs.com/pubsub/

Avatar for Aron

Aron

September 26, 2011
Tweet

Other Decks in Programming

Transcript

  1. 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
  2. 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
  3. 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
  4. AsyncJS • 25th August 2011 • Aron Carroll Events, Pub/Sub

    & Observers • Publish / Subscribe • Observer • Custom Events
  5. AsyncJS • 25th August 2011 • Aron Carroll redButton.onclick =

    function () { launchTheRocketShip(); }; Examples / DOM Events
  6. AsyncJS • 25th August 2011 • Aron Carroll redButton.addEventListener( "click",

    function () { launchTheRocketShip(); }, false ); Examples / DOM Events
  7. 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()
  8. AsyncJS • 25th August 2011 • Aron Carroll // As

    of jQuery 1.5 var request = getMagicRecipe(cookRecipe); request.error(function () { orderFishWithChips(); }); Examples / jQuery.ajax()
  9. 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
  10. 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
  11. 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
  12. AsyncJS • 25th August 2011 • Aron Carroll Uses /

    Loose Coupling GenreNavigation FindMeABookForm BookInfo LibraryBooks
  13. 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
  14. 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
  15. 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
  16. AsyncJS • 25th August 2011 • Aron Carroll Uses /

    Notification of changes IngredientsForm CakeListing (will have many cakes) OvenView CakeModel MODELS VIEWS
  17. 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.
  18. 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
  19. 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
  20. 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
  21. 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/
  22. 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