JavaScript Patterns and Principles
Upcoming SlideShare
Loading in...5
×
 

JavaScript Patterns and Principles

on

  • 3,191 views

 

Statistics

Views

Total Views
3,191
Views on SlideShare
763
Embed Views
2,428

Actions

Likes
6
Downloads
36
Comments
0

8 Embeds 2,428

http://aaronhardy.com 2420
http://prlog.ru 2
http://www.newsblur.com 1
http://webcache.googleusercontent.com 1
http://silverreader.com 1
http://cloud.feedly.com 1
http://translate.googleusercontent.com 1
https://www.google.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

JavaScript Patterns and Principles JavaScript Patterns and Principles Presentation Transcript

  • © 2013 Adobe Systems Incorporated. All Rights Reserved.© 2013 Adobe Systems Incorporated. All Rights Reserved.JavaScript Patterns And PrinciplesAaron Hardy | Software Engineer, Analytics
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Architecture Misconceptions2jQuery ismy architecture.
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Architecture Misconceptions3jQuery ismy architecture.Websites arejust the V in MVC.
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Architecture Misconceptions4jQuery ismy architecture.Websites arejust the V in MVC.We’re already usingMVC so we’re good.
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Architecture Misconceptions5jQuery ismy architecture.Websites arejust the V in MVC.We’re already usingMVC so we’re good.
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.JavaScript Patterns And Principles§  Modularity§  Communication Patterns§  Patterns Within MV*6
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.JavaScript Patterns And Principles§  Modularity§  Communication Patterns§  Patterns Within MV*7
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Building Large Apps8The secret to building large apps is NEVERbuild large apps. Break your applicationinto small pieces. Assemble those testable,bite-sized pieces into your application.- Justin Meyer
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Modules Should Be…9Independentof other modules
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Modules Should Be…10Independentof other modulesLimited knowledgeof the rest of the app
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Modules Should Be…11Independentof other modulesReusablewithout refactoringLimited knowledgeof the rest of the app
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Modules Should Be…12Independentof other modulesReusablewithout refactoringLimited knowledgeof the rest of the appFunctionalwhen other modules break
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Modules Should Be…13Independentof other modulesTestablein isolationReusablewithout refactoringLimited knowledgeof the rest of the appFunctionalwhen other modules break
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Possible ModulesFeedAddress BookChat RoomMenuShared Service14
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.JavaScript Patterns And Principles§  Modularity§  Communication Patterns§  Callback§  Promise§  Event Emitter§  Publish/Subscribe§  Patterns Within MV*15
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.JavaScript Patterns And Principles§  Modularity§  Communication Patterns§  Callback§  Promise§  Event Emitter§  Publish/Subscribe§  Patterns Within MV*16
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Callbacks In Real Life§  TODO: Picture of a fast food line while I explain how it demonstrates callbacks in real life.17CC Image Courtesy of The Consumerist on Flickr
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Callback Examplevar customer = {placeOrder: function() {restaurant.takeOrder(burger, this.onFoodReady);},onFoodReady: function(food) { … }};18
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Callback Examplevar customer = {placeOrder: function() {restaurant.takeOrder(burger, this.onFoodReady);},onFoodReady: function(food) { … }};var restaurant = {takeOrder: function(order, foodReadyCallback) {// call foodReadyCallback(food) when food is ready}};19
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Callback Key PointsUsed to notify of completion of an asynchronous taskSimpleEfficientNo libraries required20
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.JavaScript Patterns And Principles§  Modularity§  Communication Patterns§  Callback§  Promise§  Event Emitter§  Publish/Subscribe§  Patterns Within MV*21
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Promises In Real Life22
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.jQuery Promise Anatomy23takeSeatingRequest()promise Promisethen()Customer Restaurant
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.jQuery Promise Anatomy24takeSeatingRequest()promiseDeferredresolve()reject()promise()Promisethen()Customer Restaurant
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Promise Examplevar customer = {requestSeating: function() {var promise = restaurant.takeSeatingRequest();promise.then(this.sit);}sit: function() { … }};25
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Promise Examplevar customer = {requestSeating: function() {var promise = restaurant.takeSeatingRequest();promise.then(this.sit);}sit: function(table) { … }};var restaurant = {takeSeatingRequest: function() {var deferred = $.Deferred();setTimeout(function() {deferred.resolve({seats: 4});}, 5000);return deferred.promise();}};26
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Promise Examplevar customer = {requestSeating: function() {var promise = restaurant.takeSeatingRequest();promise.then(this.sit);promise.fail(this.leave);}sit: function(table) { … },leave: function() { … }};var restaurant = {takeSeatingRequest: function() {var deferred = $.Deferred();deferred.reject(); // Sorry, we’re closed!return deferred.promise();}};27
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Asynchronous Sequence Using Callbacksstep1(function(value1) {step2(value1, function(value2) {step3(value2, function(value3) {step4(value3, function(value4) {console.log(Success, value4);}}}}28
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Asynchronous Sequence Using Callbacksstep1(function(value1) {step2(value1, function(value2) {step3(value2, function(value3) {step4(value3, function(value4) {console.log(Success, value4);}}}}29PYRAMID OF DOOM
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Asynchronous Sequence Using Promisesstep1().then(step2).then(step3).then(step4).then(function(value) {console.log(Success, value);});30Supported in jQuery 1.8+
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Try-catch In A Synchronous Worldtry {var value = step1();value = step2(value);value = step3(value);value = step4(value);console.log(Success, value);} catch (error) {console.log(Failure, error);} finally {console.log(Time to clean up resources!);}31
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Asynchronous Try-catch Using Promisesstep1().then(step2).then(step3).then(step4).then(function(value) {console.log(Success, value);}).catch(function(error) {console.log(Failure, error);}).finally(function() {console.log(Time to clean up resources!);});32Supported in the Q promise library
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Asynchronous Parallel Using Callbacksvar requestsPending = 2;var onComplete = function(tweets) {requestsPending--;if (requestsPending == 0) {// Display tweets from both requests.}}loadTweets(#adobe, onComplete);loadTweets(#summit, onComplete);33
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Asynchronous Parallel Using Callbacksvar requestsPending = 2;var onComplete = function(tweets) {requestsPending--;if (requestsPending == 0) {// Display tweets from both requests.}}loadTweets(#adobe, onComplete);loadTweets(#summit, onComplete);34o_O
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Asynchronous Parallel Using Promisesvar adobePromise = loadTweets(#adobe);var summitPromise = loadTweets(#summit);$.when(adobePromise, summitPromise).then(displayTweets);35
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Promise Key PointsUsed to notify of completion of an asynchronous taskObject passable now representing something to be determined in the futureGreat for sequential/parallel managementGenerally makes use of a third party library36
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.JavaScript Patterns And Principles§  Modularity§  Communication Patterns§  Callback§  Promise§  Event Emitter§  Publish/Subscribe§  Patterns Within MV*37
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Event Emitters In Real Life§  TODO: Coupon text photo while I explain the similarities to event emitters.38CC Image Courtesy of Incase on Flickr
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.DOM Event Emitter Examplevar foo = document.getElementById(foo);foo.addEventListener(click, function() {alert(bar);});foo.addEventListener(click, function() {alert(baz);});39
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.jQuery Event Emitter Examplevar customer = {receiveCoupon: function(coupon) { … }};40
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.jQuery Event Emitter Examplevar customer = {receiveCoupon: function(coupon) { … }};var restaurant = {offerCoupon: function(coupon) {$(this).trigger(couponAvailable, coupon);}};41
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.jQuery Event Emitter Examplevar customer = {receiveCoupon: function(coupon) { … }};var restaurant = {offerCoupon: function(coupon) {$(this).trigger(couponAvailable, coupon);}};$(restaurant).on(couponAvailable, customer.receiveCoupon);42
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Event Emitter Key PointsNotifies of state change, user interaction, etc.Fires an event any number of times (possibly never)Native for DOMArbitrary objects make use of a third-party library43
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.JavaScript Patterns And Principles§  Modularity§  Communication Patterns§  Callback§  Promise§  Event Emitter§  Publish/Subscribe§  Patterns within MV*44
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Pub/Sub Anatomy45Pub/Sub Buspublish()subscribe()unsubscribe()
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Pub/Sub Anatomy46Pub/Sub Buspublish()subscribe()unsubscribe()Customerbus.subscribe(couponAvailable, function() { … });
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Pub/Sub Anatomy47Pub/Sub Buspublish()subscribe()unsubscribe()RestaurantCustomerbus.publish(couponAvailable, Buy 1 get 1 free);
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Pub/Sub Example48Archive Report spam Delete Mark as unreadAndroid 4.2.1 vs iOS 6Videos magically don’t have soundIf you could scale this to market it would be very valuable, no?Clone SSD (Windows system partition) to HDD partitionJIRA help – Greenhopper + Scrum + SubtasksQuestion setting up a VPN on firewallShopping CartsThe end of textbooks?3MeMail
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Pub/Sub Example49Android 4.2.1 vs iOS 6Videos magically don’t have soundIf you could scale this to market it would be very valuable, no?Clone SSD (Windows system partition) to HDD partitionJIRA help – Greenhopper + Scrum + SubtasksQuestion setting up a VPN on firewallShopping CartsThe end of textbooks?0MeMailArchive Report spam Delete Mark as unreadInboxService
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Pub/Sub Example50Android 4.2.1 vs iOS 6Videos magically don’t have soundIf you could scale this to market it would be very valuable, no?Clone SSD (Windows system partition) to HDD partitionJIRA help – Greenhopper + Scrum + SubtasksQuestion setting up a VPN on firewallShopping CartsThe end of textbooks?3MeMailMark all as read
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Pub/Sub Example51Android 4.2.1 vs iOS 6Videos magically don’t have soundIf you could scale this to market it would be very valuable, no?Clone SSD (Windows system partition) to HDD partitionJIRA help – Greenhopper + Scrum + SubtasksQuestion setting up a VPN on firewallShopping CartsThe end of textbooks?3MeMailbus.publish(selectedEmailsChanged, selectedEmails);BusMark all as read
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Pub/Sub Example52Android 4.2.1 vs iOS 6Videos magically don’t have soundIf you could scale this to market it would be very valuable, no?Clone SSD (Windows system partition) to HDD partitionJIRA help – Greenhopper + Scrum + SubtasksQuestion setting up a VPN on firewallShopping CartsThe end of textbooks?3MeMailArchive Report spam Delete Mark as read
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Pub/Sub Example53Android 4.2.1 vs iOS 6Videos magically don’t have soundIf you could scale this to market it would be very valuable, no?Clone SSD (Windows system partition) to HDD partitionJIRA help – Greenhopper + Scrum + SubtasksQuestion setting up a VPN on firewallShopping CartsThe end of textbooks?3MeMailBusServiceArchive Report spam Delete Mark as readbus.publish(markAsReadRequested, emails);
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Pub/Sub Example54Android 4.2.1 vs iOS 6Videos magically don’t have soundIf you could scale this to market it would be very valuable, no?Clone SSD (Windows system partition) to HDD partitionJIRA help – Greenhopper + Scrum + SubtasksQuestion setting up a VPN on firewallShopping CartsThe end of textbooks?3MeMailBusServicebus.publish(markedAsRead, emails);Archive Report spam Delete Mark as read
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Pub/Sub Example55Android 4.2.1 vs iOS 6Videos magically don’t have soundIf you could scale this to market it would be very valuable, no?Clone SSD (Windows system partition) to HDD partitionJIRA help – Greenhopper + Scrum + SubtasksQuestion setting up a VPN on firewallShopping CartsThe end of textbooks?2MeMailArchive Report spam Delete Mark as unread
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Pub/Sub Key PointsCommunication between modulesPublishers and subscribers don’t address one anotherProvides excellent decoupling56
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Which Pattern Should I Use?57Is the communicationbetween modules?Is it communicatinga response to requested task?Do you need to representa future value?Is sequence/parallelmanagement important?No YesNo YesNo YesEvent EmitterCallback PromisePub/Sub
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.JavaScript Patterns And Principles§  Modularity§  Communication Patterns§  Patterns Within MV*§  State Change Detection§  Declarative Markup§  View Manipulation§  Dependency Injection58
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.MVC59ModelRepresents dataor stateViewPresentation anduser controlsControllerLogic between viewsand models
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.MVP60ModelRepresents dataor stateViewPresentation anduser controlsPresenterLogic between viewsand models
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.MVVM61ModelRepresents dataor stateViewPresentation anduser controlsViewModelLogic between viewsand models
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.MV*62ModelRepresents dataor stateViewPresentation anduser controls*
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.MV* Frameworks63
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Comparison At A Glance64Requires Underscore/LoDash and jQuery/Zepto6K + 4K (Underscore) + 28K (jQuery 2.0) gzippedNon-prescriptiveExtensions add functionality and/or prescriptionEventful proxy modelsUsed in tandem with a template engineBinding available through extensionsDependency injection available through extensionsjqLite built-in29K gzippedPrescriptiveIntended to be a full(er) stack out of the boxDirty checkingCustom HTML tags and attributes (directives)Two-way data-binding built-inDependency injection built-in
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.JavaScript Patterns And Principles§  Modularity§  Communication Patterns§  Patterns Within MV*§  State Change detection§  Declarative Markup§  View Manipulation§  Dependency Injection65
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Backbone: Proxy Models66var book = {title: A Tale of Two Cities,author: Charles Dickens,genre: Historical,};var bookView = new BookView(book);book.genre = Social Criticism;How does BookView knowthat the book’s genre changed?
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Backbone: Proxy Models67var book = {title: A Tale of Two Cities,author: Charles Dickens,genre: Historical,};var bookView = new BookView(book);book.genre = Social Criticism;bookView.genreChanged(); We could manually tell it…
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Backbone: Proxy Models68var book = {title: A Tale of Two Cities,author: Charles Dickens,genre: Historical,};var bookView = new BookView(book);book.genre = Social Criticism;bookView.genreChanged(); We could manually tell it…but not without creatinga tangled mess.
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Backbone: Proxy Models69Let’s wrap our objectin a proxy.var book = new Backbone.Model({title: A Tale of Two Cities,author: Charles Dickens,genre: Historical,});var bookView = new BookView(book);book.set({genre: Social Criticism}); Now we must use theproxy functions.(Until ECMAScript Harmony!)
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Backbone: Proxy Models70Meanwhile, inside BookView…book.on(change:genre, onChange);var book = new Backbone.Model({title: A Tale of Two Cities,author: Charles Dickens,genre: Historical,});var bookView = new BookView(book);book.set({genre: Social Criticism});
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Backbone: Proxy Models71We do something similar forarrays.var books = new Backbone.Collection([book1,book2,book3]);var booksView = new BooksView(books);books.add(book4);books.on(add, onAdd);
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Angular: Dirty Checking72Meanwhile inside BookView…var book = {title: A Tale of Two Cities,author: Charles Dickens,genre: Historical,};…pass book to BookView…book.genre = Social Criticism;$scope.book = book;$scope.$watch(book, function() {console.log(changed!);}, true);
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Angular: Dirty Checking73User ClickChange ObjectWatchers: Is theobject differentthan last time?Yes. React.Watchers: Is theobject differentthan last time?NoDigest CycleTriggered automaticallyon user interaction,http responses, etc.Can be manually triggered.TriggerWait
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.JavaScript Patterns And Principles§  Modularity§  Communication Patterns§  Patterns within MV*§  State Change Detection§  Declarative Markup§  View Manipulation§  Dependency Injection74
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Backbone: Templates<script id="users-template"type="text/x-handlebars-template"><ul>{{#users}}<li>Name: {{name}}, Email: {{email}}</li>{{/users}}</ul></script>75
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Backbone: Templatesvar data = {users: [{ name: John, email: john@example.com },{ name: Jane, email: jane@example.com }]};var source = $(#users-template).html();var template = Handlebars.compile(source);var html = template(data);$(body).html(html);76
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Backbone: Templates<body><ul><li>Name: John, Email: john@example.com</li><li>Name: Jane, Email: jane@example.com</li></ul></body>77
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Angular: Directives<ul><li ng-repeat="user in users">Username: {{user.name}}, Email: {{user.email}}</li></ul>function MyController($scope) {$scope.users = [{name: John, email: john@example.com},{name: Jane, email: jane@example.com}];}78
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.JavaScript Patterns And Principles§  Modularity§  Communication Patterns§  Patterns Within MV*§  State Change Detection§  Declarative Markup§  View Manipulation§  Dependency Injection79
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Backbone: Responding To And Updating ViewName: <input type="text" class="name-in"><h1>Hello <span class="name-out"></span></h1>Backbone.View.extend({events: {keyup .name-in: onNameChange},onNameChange: function(event) {// TODO: Optimizevar name = $(event.target).val();this.$(.name-out).text(name);}});80
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Angular: BindingName: <input type="text" ng-model="yourName"><h1>Hello {{yourName}}</h1>81
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.JavaScript Patterns And Principles§  Modularity§  Communication Patterns§  Patterns within MV*§  State change detection§  Declarative Markup§  View Manipulation§  Dependency Injection82
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Without Dependency Injection83var TweetStream = function() {this.twitter = new TwitterService();};TweetStream.prototype.showTweets = function() {var tweets = this.twitter.getTweets();…};var stream = new TweetStream();stream.showTweets();
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.With Dependency Injection84var TweetStream = function(twitter) {this.twitter = twitter;};TweetStream.prototype.showTweets = function() {var tweets = this.twitter.getTweets();…};var twitter = new TwitterService();var stream = new TweetStream(twitter);stream.showTweets();We inverted control of theTwitterService construction.
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Inversion of Control ContainerWhen rank is requested, provide the value 1337.When twitter is requested, provide a new instance of TwitterService.When dialog is requested, provide the SearchDialog constructor.When logger is requested, provide a singleton instance of AsyncLogger.When chat is requested, provide whatever is returned from chatFactory.85
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Angular: Dependency Injection86var MyController = function($http, $scope) {$http.get(http://github.com/…).success(function(commits) {$scope.commits = commits;});};$injector.instantiate(MyController);How does $injector knowwhat to inject for $httpand $scope?
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Angular: Dependency Injection87var MyController = function($http, $scope) {$http.get(http://github.com/…).success(function(commits) {$scope.commits = commits;});};$injector.instantiate(MyController);How does $injector knowwhat to inject for $httpand $scope?By using toString() andsome well-crafted regex.
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Angular: Dependency Injection88var MyController = function($http, $scope) {$http.get(http://github.com/…).success(function(commits) {$scope.commits = commits;});};$injector.instantiate(MyController);What if we reverse theparameter order?
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Angular: Dependency Injection89var MyController = function($scope, $http) {$http.get(http://github.com/…).success(function(commits) {$scope.commits = commits;});};$injector.instantiate(MyController);What if we reverse theparameter order?It still works!
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Angular: Dependency Injection90var MyController = function(a, b) {a.get(http://github.com/…).success(function(c) {b.commits = c;});};$injector.instantiate(MyController);What if we reverse theparameter order?It still works!Until we minify it.
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Angular: Dependency Injection91var MyController = function(a, b) {a.get(http://github.com/…).success(function(c) {b.commits = c;});};MyController.$inject = [$http, $scope];$injector.instantiate(MyController);What if we reverse theparameter order?It still works!Until we minify it.Then we have to annotate.
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.JavaScript Patterns And Principles§  Modularity§  Communication Patterns§  Patterns Within MV*92
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Promise Implementations93QjQueryrsvp.jskriskowal/qjquery/jquerytildeio/rsvp.js
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Pub/Sub Implementations94Postal.jsAmplifyJSPubSubJSpostaljs/postal.jsappendto/amplifymroderick/pubsubjs
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Inversion of Control and Dependency Injection95Article by Martin Fowlerhttp://martinfowler.com/articles/injection.htmlWikipedia source of truthhttp://en.wikipedia.org/wiki/Dependency_injectionLightweight inversion of control container with exampleshttps://github.com/Aaronius/injectorjs
  • © 2013 Adobe Systems Incorporated. All Rights Reserved.Inversion of Control and Dependency Injection96Article by Martin Fowlerhttp://martinfowler.com/articles/injection.htmlWikipedia source of truthhttp://en.wikipedia.org/wiki/Dependency_injectionLightweight inversion of control container with exampleshttps://github.com/Aaronius/injectorjs