Building Ambitious Web Apps with Ember

1,736 views
1,605 views

Published on

Desert Code Camp 2014.1

Published in: Software
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,736
On SlideShare
0
From Embeds
0
Number of Embeds
67
Actions
Shares
0
Downloads
26
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Building Ambitious Web Apps with Ember

  1. 1. BUILDING AMBITIOUS WEB APPS WITH EMBER.JS DesertCode Camp 2014
  2. 2. GREG BABIARS Developer atSwiftpage http://gregbabiars.com @gbabiars https://github.com/gbabiars
  3. 3. WHAT IS EMBER? Aframework for creatingambitious web applications MVC framework Designed with productivityin mind Inspired byCocoaand Rails Communitydriven
  4. 4. WHY USE EMBER TO BUILD WEB APPS? Increases productivityand reduces boilerplate Conventions guide you down the rightpath As your app grows the complexitystays constant Leverages work of communityto solve common problems Embraces the URL
  5. 5. MYTHS ABOUT EMBER Documentation sucks Hard to test Notflexible
  6. 6. CORE CONCEPTS Observers/Computed Properties Actions &Events Run Loop
  7. 7. EMBER.OBJECT All"classes"in Ember inheritfrom Ember.Object. This is the buildingblock for justabouteverythingin Ember and provides: The abilityto create observers and computed properties .getand .setwhich allow us access and trigger properties through bindings.
  8. 8. EMBER.OBJECT INSTANTIATION varmyObject=Ember.Object.create({ firstName:'Greg', lastName:'Babiars' }); myObject.set('firstName','Gregory'); myObject.get('firstName');//Gregory
  9. 9. EXTENDING AN OBJECT varPerson=Ember.Object.extend({ firstName:'', lastName:'', sayName:function(){ console.log(this.get('firstName')+''+this.get('lastName'); } }); varmyPerson=Person.create({firstName:'John',lastName:'Doe'}); myPerson.sayName();//JohnDoe
  10. 10. COMPUTED PROPERTIES Methods thatcan be accessed as properties Allows us to propagate changes through our application We can specifyour dependentproperties thattrigger an update
  11. 11. COMPUTED PROPERTIES varPerson=Ember.Object.extend({ firstName:'', lastName:'', name:function(){ returnthis.get('firstName')+''+this.get('lastName'); }.property('firstName','lastName') }); varmyPerson=Person.create({firstName:'John',lastName:'Doe'}); myPerson.get('name');//JohnDoe
  12. 12. OBSERVERS Methods thatare called when adependentkeyhas changed
  13. 13. OBSERVERS varPerson=Ember.Object.extend({ firstName:'', lastName:'', nameChanged:function(){ console.log('Anamehaschanged'); }.observes('firstName','lastName') }); varmyPerson=Person.create({firstName:'John',lastName:'Doe'}); myPerson.set('firstName','Jane');//Anamehaschangedwillbelogged
  14. 14. ACTIONS Triggered in templates using{{action}} or JS using.send() Can be handled in views, controllers or routes Handlers mustbe defined in the actions hash Starts in controller, bubbles up through parentroutes until handler is found
  15. 15. EVENTS Low levelDOM events (click, scroll, etc) Handled in views mostly Does notneed to be namespaced
  16. 16. RUN LOOP Asetof queues thatbatch and order work Intelligentlyexecutes your application to maximize efficiency and effectiveness Have access to schedule usingEmber.run
  17. 17. ARCHITECTURE Application Router Routes Controllers Views Components Templates
  18. 18. EMBER.APPLICATION Instantiate asingle instance for your application. Can optionally pass in an elementid to use as the rootof your application. Creates the namespace for your application. varApp=Ember.Application.create();
  19. 19. EMBER.ROUTER Used to define the route structure of your application. This is done usingRouter.map. App.Router.map(function(){ this.resource('posts',function(){ this.route('post',{path:':post_id'});//Mapsto/posts/1 }); this.resource('about',{path:'my-about-page'}); });
  20. 20. EMBER.ROUTER Can define routes and resources. Resources can have have other routes and resources nested under them while routes cannot. Resources automaticallydefines index, loadingand error routes. Routes are terminal.
  21. 21. EMBER.ROUTER Resources willgenerate aroute, controller and template atrun time if one matchingthe namingconvention is notfound. For example, our posts resource willlookup or generate: PostsRoute PostsController posts.handlebars
  22. 22. EMBER.ROUTE Route objects give you controlover whathappens within a specific route of your application. Ithas hooks thatallows you to customize the following: Loadingthe modelfor thatroute Settingup the state of the controller Customize whatis rendered Custom logic when entering/existingthe route Handle actions thatbubble up Allows us to transition to other routes
  23. 23. EMBER.ROUTE App.PostsRoute=Ember.Route.extend({ //Loadthemodel,ifapromiseitwillnotcontinueuntilitresolves model:function(){ returnthis.store.find('post'); }, //Customizethestateofthecontroller setupController:function(controller,model){ controller.set('model',model); controller.set('isEditing',false); }, //Customizewhatisrendered renderTemplate:function(controller){ this.render('post-list',{controller:controller}); } });
  24. 24. EMBER.CONTROLLER Controllers are designed to manage application state. Theyhave severalproperties: One is generated for each route Can depend on other controllers Holds transientstate and logic for aspecific template Typicallyhas amodelthatrepresents an objector array Handles actions triggered from the template
  25. 25. EMBER.OBJECTCONTROLLER Example of an objectcontroller App.PostController=Ember.ObjectController.extend({ hasComments:function(){ returnthis.get('model.comments.length')>0; }.property('model.comments.length') actions:{ cancel:function(){ this.get('model').rollback(); } } });
  26. 26. EMBER.ARRAYCONTROLLER Example of an arraycontroller App.PostsController=Ember.ArrayController.extend({ hasReadAllPosts:function(){ varunreadreadPosts=this.get('model').filterBy('isRead',false); returnunreadPosts.get('length')===0; }.property('posts.@each.isRead'), actions:{ readPost:function(post){ post.set('isRead',true'); } } });
  27. 27. EMBER.VIEW Able to specifythe tagName, css classes Handles DOM events (click, keypress, etc) Can have conditionalhtmlattributes (class, disabled, etc) Has abackingcontroller Notcommonlyused
  28. 28. EMBER.VIEW App.PostView=Ember.View.extend({ tagName:'article', classNameBindings:['selected:active'], selected:false, templateName:'post-detail', click:function(){ this.get('controller').doSomething(); } }); {{viewApp.PostViewpostBinding="post"selected="false"}}
  29. 29. EMBER.COMPONENT Subclass of Ember.View, designed for reuse Sandboxed, backingcontroller and contextis itself Allproperties mustbe passed in viatemplate Mustexplicitlybind externalactions to actions inside the component Bestplace to wrap 3rd partyplugins, i.e. jQueryplugins
  30. 30. EMBER.COMPONENT App.ButtonComponent=Ember.Component.extend({ tagName:'button', classNames:['btn'], click:function(){ this.sendAction(); } }); App.DemoController=Ember.Controller.extend({ buttonText:'ClickMe', actions:{ doSomething:function(){console.log('buttontriggeredthis');} } }); {{buttontext=buttonTextaction="doSomething"}}
  31. 31. EMBER.COMPONENT Modalexample App.ModalComponent=Ember.Component.extend({ classNames:['modal','fade'], isOpen:false, didInsertElement:function(){ this.$().modal({ show:false }); }, actions:{ submit:function(){this.sendAction();} }, toggleVisible:function() { this.$().modal(this.get("isOpen")?"show":"hide"); }.observes("isOpen") });
  32. 32. EMBER.COMPONENT Modalexample (cont.) Modalcomponenttemplate <divclass="modal-content"> {{yield}} </div> <divclass="modal-footer"> <button{{action"submit"}}>Submit</button> </div>
  33. 33. EMBER.COMPONENT Modalexample (cont.) Person controller App.PersonController=Ember.Controller.extend({ formOpen:false, actions:{ toggleForm:function(){ this.toggleProperty('formOpen'); }, save:function(){ this.get('model').save(); } } });
  34. 34. EMBER.COMPONENT Modalexample (cont.) Person Template <button{{action"toggleForm"}}>ToggleForm</button> {{#modalaction="save"isOpen=formOpen}} <label>Name:</label> {{inputvalue=model.name}} {{/modal}}
  35. 35. TEMPLATES Always have abackingcontext, typicallyacontroller Handlebars -Logicless templates, logic lives in JS Automaticallyupdate properties Can trigger actions
  36. 36. TEMPLATES Simple syntax example <div> <h1>{{person.name}}</h1> ##{{person.company}}</h2> </div>
  37. 37. TEMPLATES Usingeach and link-to <ul> {{#eachpostinmodel}} <li> {{link-topost.name"post"post}} </li> {{/each}} </ul>
  38. 38. TEMPLATES Triggeringan action <button{{action"save"model}}></button>
  39. 39. WHAT ABOUT PERSISTENCE? Wellthat's awhole differenttalk!
  40. 40. PERSISTENCE LIBRARIES Ember Data Ember Model Ember Persistence Foundation (EPF) ic-ajax
  41. 41. FURTHER LEARNING http://emberjs.com/guides http://emberjs.com/api https://www.youtube.com/user/EmberNYC http://emberweekly.com/

×