Workshop – Getting the most from Sponduly. Have an agenda Money Getting the most from Sponduly:
Getting the most from Emberjs
-
Upload
devobjective -
Category
Technology
-
view
17 -
download
2
Transcript of Getting the most from Emberjs
Getting the the most from Ember.js
Nolan Erck
Today's Agenda
● What's a SPA?● Brief intro to Model-View-Controller pattern.● What is Ember.js?● Walk-thru some basic features of Ember.js, look
at code samples.● Ember.js vs Angular.js● Questions? Comments?● Lunch!
About Me
● Consultant (southofshasta.com)
– Software Development, On-site Training, Design● Using ColdFusion since 1999 (version 4.x).
● Other stuff: C++, Java, jQuery, PHP, .NET, HTML5,Android, you get the idea...
● Manager of SacInteractive User Group.
● Reformed Video Game Developer (Grim Fandango,SimPark, StarWars Rogue Squadron, etc).
● Music Junkie.
Prerequisites
● Good understanding of “modern” JavaScript.– Scopes, anonymous functions, classes, objects.
● Previous MVC experience is helpful but notreq'd.
● And 1 more thing you need to know...
Prerequisites
● Know that...– Object Oriented Programming is hard.
– SPAs are different than traditional HTML apps.
– Some of it is confusing at first.
● And that's NORMAL.
Single Page Application (SPA)
● Instead of contact.html, about.html, products.html● You have these guys:
– Sitename.com/#/contact
– Sitename.com/#/products
● The whole site is routed through index.html viasome internal machinery.
● The whole site is downloaded at once, thenaccessed via the browser cache.
● Only new data is retrieved from the server.
What is MVC?
● Model View Controller● Design Pattern● Splits your app up into 3 logical sections.
– Model – where your data and related logic goes.
– View – the parts of your app you “view” (HTML,CSS).
– Controller – determines what happens next in theapp (some business logic maybe too).
● The “restaurant” analogy.
What is MVC?
Model
- data
- localStorage
- bus. Logic
- etc
Controller
- route userfrom point ato point b
- route userback to pointa if Modelsaidsomethingwas missing
View
- HTML
- CSS
- jQuery
- Bootstrap
- etc.
The “Model”
● Where your data lives.● Can be a local JS variable.● Can come from localStorage.● REST API.● Some other json/ajax request.● The app doesn't care.● Restaurant: the kitchen.
The “View”
● The part of the app you “view”.– HTML, CSS, JavaScript
<html>
<body>this part here is the “view”
</body>
</html>● Restaurant: the menu and plates of food.
The “Controller”
● Controls what happens next.– Send info to the model.
– Update the View with an error/success message.
– Move the User to a new section of the app.
– Etc.
● Restaurant: the waiter.
What is Ember.js?
● MVC JavaScript framework for SPAs.● Supports bindings, computed properties, etc.● Built-in templates (Handlebars by default. Like
Mustache with logic – if/else, each(), etc).● Lots of other features – we'll just barely scratch
the surface in today's session.
How to get started?
● Go to emberjs.com● Click “download” – ember.js● Also need jQuery installed.● Also also need Handlebars.js.● Node npm options available too
– The “recommended” other stuff always gives metrouble when using npm. I have better luckdownloading the .js files directly. YMMV.
How to get started?
● <script src=”jquery.js></script>● <script src=”handlebars.js></script>● <script src=”ember.js></script>● <script src=”app.js”></script>
var Notes = Ember.Application.create({
});
– Creates a namespace for your application.
● Make a handlebars template.
[DEMO 1]
Ember.JS
● Behind the scenes, Ember.js creates 4 objectswith default behavior:– An application route
– An application controller
– An application view
– An application template
Routes
● URLs in an Ember.js app look like so:– /index.html#/home
● Everything is loaded via index.html● Each #section as its own “view” that's
dynamically injected as the app is running.
RoutesNotes.Router.map(function () {
this.resource('notes', {path: "/"}, function()
{
this.route('note', {path: "/note/:note_id"});
});});
Notes.Router class contains a route named “notes” that maps to URL “/”.Also contains a route “note” that is a subroute of the “notes” route.
A route that has subroutes is called a “resource”.
Subroutes are referred to by their fully-qualified name: notes.note
Same convention is used for controllers, views and templates.
RoutesNotes.Router.map(function () {
this.resource('notes', {path: "/"}, function()
{
this.route('note', {path: "/note/:note_id"});
});});
Based on the above code, Ember created some object implementations for us:
Notes.NotesRouteNotes.NoteControllerNotes.NoteViewnotes template
Notes.NotesNoteRouteNotes.NoteNoteControllerNotes.NoteNoteViewnotes/note template
(Most of that is invisible, unless you want to modify the behavior for some reason.
[DEMO 2 – View Source]
Model – Data StoreNotes.Store = DS.Store.extend({
adapter: DS.LSAdapter
});
(This part uses ember-data-localstorage.js)
Create a Notes Store – acts as a storage place where our Model lives.
DS.LSAdapter = we're using the Local Storage Adapter.
ModelNotes.Note = DS.Model.extend({
name: DS.attr('string'),
value: DS.attr('string')
});
Here's our actual Mode. A “Note” class.
It has 2 fields – “name” and “value”.
They're both marked as “strings”.
Making data available to a Controller
Notes.NotesRoute = Ember.Route.extend({
model: function() {
return this.store.find('note');
}});
(This part uses ember-data.js)
Our NotesRoute extends Ember.Route class.
We use model() function to say which data is available in our route.
Using data in a View<div class="list-group" style="margin-top: 10px;">
{{#each controller}}
<div class="list-group-item">
{{name}}
</div>
{{/each}}
</div>
#each iterates over every “note” in our NotesController.
{{name}} draws the name from that note to the screen.
Selecting a Note (Detail Page)<div class="list-group" style="margin-top: 10px;">
{{#each controller}}
<div class="list-group-item">
{{#linkTo "notes.note" this}}
{{name}}
{{/linkTo}}
</div>
{{/each}}
</div>#linkTo expression wraps around the text I want to link. (Renamed #link-to in laterversions of Ember.js).
[DEMO 4
Saving a Note<button {{action "updateNote"}}>Update</button>
UpdateNote is an action in the NotesNote controller. It fires whenever the button ispressed.
Go to our controller and pass the data into the model where it's saved:
updateNote: function() {
var content = this.get('content');
if (content) {
content.save();
}
}
Deleting a Note
{{#linkTo "notes.note" this class="list-group-item"}}
{{name}}
<button {{action "doDeleteNote" this}}>
Delete
</button>
{{/linkTo}}
In the View:
Deleting a Note
Notes.NotesController = Ember.ArrayController.extend({
[ other stuff removed, for clarity ]
doConfirmDelete: doConfirmDelete: function () {
var selectedNote = this.get('noteForDeletion');
this.set('noteForDeletion', null);
if (selectedNote) {
this.store.deleteRecord(selectedNote);
selectedNote.save();
Putting it all together.
● Can combine Ember with jQuery– It's required anyway
● Can also use Bootstrap, all the Bootstrap add-ons, etc.
[DEMO 6]
Talking to a JSON API
Ember.$.getJSON('http://api/users/me', function(data)
{
var user
= controller.store.createRecord('user', data.user );
controller.set('model', user);
});
Other Resources● Book: EmberJS In Action
● guides.emberjs.com
● StackOverFlow
● Book: Building WebApps With Ember.js (O'Reilly)
● Book: Mastering Ember.js (Packt Publishing)
What's the catch?
● Bigger initial load of the website.– But quicker loads after that.
● A bit of a learning curve.● More “moving parts” to start than, say,
AngularJS.● But if you're comfortable with Java-esque
frameworks, C++, etc, this might feel morenatural to you.
Ember.js vs Angular.js● Both are MVC frameworks.
– All MVC frameworks solve the same core designpattern problem.
– Comes down to 2 things.● Which one feels most comfortable to you.● Do any of the extra add-ons solve an additional need you
have?
– Ember.js is a bit more “explicit”.
– Angular.js has less “boiler plate” before you canstart using it.
– YMMV
– Personally, they're both annoying. :)
Credit where credit is due
● Http://guides.emberjs.com● Book “Ember.JS” in action by Joachim Haagen
Skeie.● Nice people on StackOverflow.
Questions? Comments?
● Ways to reach me:– southofshasta.com
– Twitter @southofshasta
Thanks!