workshop 16: emberjs parte i
TRANSCRIPT
Raúl Delgado & Andrés Lamilla
Front End WorkshopsEmberJS General Overview
[email protected]@visual-engin.com
A framework for creating ambitious web applications.
● Focus on ambitious web applications: applications that look and act like desktop applications, but happen to be delivered via web technologies
● More productive out of the box: provide a complete development stack to make the developer productive immediately. (Ember CLI, application structure, thousands addons).
● Stability without stagnation: backward compatibility is important and can be maintained while still innovating and evolving the framework.
● Future web standards foresight: pioneer of many standards around Javascript and the web. (promises, web components and ES6 syntax)
Philosophy
● Routes: the state of an application is represented by a URL● Models: data associated with the current state of the application● Templates: HTMLBars templating language. (Handlebars
variation)● Components: custom HTML tag● Services: singleton objects to hold long-lived data such as user
sessions
Five essential Concepts
Big Picture
● In December 2011, the SproutCore 2.0 framework was renamed to Ember.js● The framework was created by Yehuda Katz, a member of the jQuery, Ruby
on Rails and SproutCore core teams● Ember follows a six-week release cycle. Every six weeks a new release is
made available, and at the same time a beta for the next release is also published
● Ember follows the semantic versioning convention. This means that breaking changes are only introduced at major version numbers such as 1.0, 2.0 etc.
● Ember 2.0 was released August 13, 2015. Introduction of the Glimmer rendering engine
● It follows the Convention over configuration design paradigm● Stable release 2.4.3 / March 17, 2016
Facts
Ember cli
● Strong conventional project structure● Powerful addon system for extension● Uses babel, which turns ES2015 module syntax into AMD (RequireJS-esq)
modules.● Use QUnit and Ember QUnit by default. But, you are free to use other options
such as Mocha and Ember Mocha.● Use Bower, for front-end dependencies and npm, for managing internal
dependencies● Is configurable via a file named .ember-cli
Ember cli
Has support for:● Handlebars● HTMLBars● Emblem● LESS● Sass● Compass● Stylus● CoffeeScript● EmberScript● Minified JS & CSS
Ember cli
Commands:● ember● ember new <app-name>● ember init● ember build● ember server● ember generate <generator-name> <options>● ember help generate● ember destroy <generator-name> <options>● ember test● ember install <addon-name>
Ember cli
npm install -g [email protected] new ember-quickstartcd ember-quickstartember serveLivereload server on http://localhost:49152Serving on http://localhost:4200/ember generate route scientistsinstalling route create app/routes/scientists.js create app/templates/scientists.hbsupdating router add route scientistsinstalling route-test create tests/unit/routes/scientists-test.jsember build --env production
Ember cli
ember install ember-cli-sassember install ember-cli-bootstrap-sassymv app/styles/app.css app/styles/app.scssecho '@import "bootstrap";' > app/styles/app.scss
Ember cli
Ember.object
Ember implements its own object system. The base object is Ember.Object. All of the other objects in Ember extend Ember.Object.Ember.Object can observe properties change. This simple architectural decision is responsible for much of the consistency across Ember. Every Ember object can observe the properties of other objects, bind their properties to the properties of other objects, specify and update computed properties, and much more.
This gives enormous power and flexibility !
Ember.object
Ember.object vs JS object
Defining new Ember Class:
Ember.object
Properties:
person1 = Person.extend({ firstName: “John”, lastName: “McClaine”, fullName(): { let fullName = this.firstName + ‘ ’ + this.lastName; alert(`my name is ${fullName} !`) }})
person1.get(‘firstName’) //Johnperson1.get(‘lastName’) //McClaneperson1.fullName()
//my name is John Mclane !
Person = Ember.Object.extend()user = Person.create()
Observers:
Ember.object
Person = Ember.Object.extend({ firstName: null, lastName: null, fullName: Ember.computed( 'firstName', 'lastName', function() {
return `${this.get('firstName')} ${this.get('lastName')}`; }), fullNameChanged: Ember.observer( 'fullName', () => {
// deal with the changeconsole.log(`fullName changed to: ${this.get('fullName')}`);
})})
var person = Person.create({ firstName : Harry, lastName : ‘Stamper’})
person.get(‘fullName’) // Harry Stamperperson.set(‘firstName’, “Grace”)
// fullName changet to: Grace Stamper
Models
The models are objects that represent the underlying data that the application presents the user. Different applications have very different models, depending on what are the problems they are trying to solve.
You can create a model with the command:
This will generate:
Models
$ ember generate model person
ModelsDefining attributes:
To define attributes to our model, we have four methods:- Attr- hasMany- belonsTo- normalizeModelName
attr:
ModelsRelationship methods: hasMany & belongsTo:
One-to-one:
One-to-many:
Many-to-many:
Routing
Ember is URL-driven so it always starts in the URL. In the example, our router has the following definition:
Routing
An instance of the Route invoke the model() method where we turn the model.Here it looks like a dummy object is returned:
Once model() has been returned, the renderComponent() method call ItemDisplayComponent model.
Not only push data paths. They can also receive actions.
Actions are sent from components or other routes, so that the logic transitions involving URL or another route-level issue.
Routing
RoutingWhat’s going on here?1. The Router parses the /items/2 URL and dispatches
control to a matching route: ItemRoute with a parameter item_id=2
2. ItemRoute invokes its model() hook, in which our app returns a model (Item with id=2) fetched via a service
3. renderComponent() is then run to render the component ItemDisplayComponent, passing it the resolved model Item
4. ItemDisplayComponent is responsible for the user interface: rendering/updating the DOM, and handling browser events
The application route is entered when your app first boots up. Like other routes, it will load a template with the same name (application in this case) by default. You should put your header, footer, and any other decorative content here. All other routes will render their templates into the application.hbs template's {{outlet}}.
This route is part of every application, so you don't need to specify it in your app/router.js.
RoutingThe application route:
Index Routes:At every level of nesting (including the top level), Ember automatically provides a route for the / path named index.
Templates
app/helpers/sum.jsexport function sum(params) { return params.reduce((a, b) => { return a + b; });};
export default Ember.Helper.helper(sum);
Templates
<p>Total: {{sum 1 2 3}}</p>
{{sum (multiply 2 4) 2}}
<div> {{if isFast "I am fast" "I am slow"}}</div>
Templates
<div> {{if isFast (if isFueled "zoooom")}}</div>
{{#if isAtWork}} Ship that code!{{else if isReading}} You can finish War and Peace eventually...{{/if}}
{{#each people as |person|}} Hello, {{person.name}}!{{else}} Sorry, nobody is here.{{/each}}
Templates
<ul> {{#each people as |person index|}} <li>Hello, {{person.name}}! You're number {{index}} in line</li> {{/each}}</ul>
/app/components/store-categories.jsexport default Ember.Component.extend({ willRender() { this.set('categories', { 'Bourbons': ['Bulleit', 'Four Roses', 'Woodford Reserve'], 'Ryes': ['WhistlePig', 'High West'] }); }});
Templates
/app/templates/components/store-categories.hbs<ul> {{#each-in categories as |category products|}} <li>{{category}} <ol> {{#each products as |product|}} <li>{{product}}</li> {{/each}} </ol> </li> {{/each-in}}</ul>
<ul> <li>Bourbons <ol> <li>Bulleit</li> <li>Four Roses</li> <li>Woodford Reserve</li> </ol> </li> <li>Ryes <ol> <li>WhistlePig</li> <li>High West</li> </ol> </li></ul>
/app/components/store-categories.jsexport default Ember.Component.extend({ willRender() { this.set('categories', { 'Bourbons': ['Bulleit', 'Four Roses', 'Woodford Reserve'], 'Ryes': ['WhistlePig', 'High West'] }); },
actions: { addCategory(category) { let categories = this.get('categories'); categories[category] = [ ]; // A manual re-render causes the DOM to be updated this.rerender(); } }});
Templates
app/templates/components/single-post.hbs<p><button {{action "select" post}}>✓</button> {{post.title}}</p>
Templates
app/components/single-post.jsexport default Ember.Component.extend({ actions: { select(post) { console.log(post.get('title')); } }});
app/templates/components/single-post.hbs<p> <button {{action "select" post on="mouseUp"}}>✓</button> {{post.title}}</p>
Components
ember generate component my-component-nameinstalling component create app/components/my-component-name.js create app/templates/components/my-component-name.hbsinstalling component-test create tests/integration/components/my-component-name-test.js
Components
app/templates/components/blog-post.hbs<article class="blog-post"> <h1>{{title}}</h1> <p>{{yield}}</p> <p>Edit title: {{input type="text" value=title}}</p></article>
app/templates/index.hbs{{#each model as |post|}} {{#blog-post title=post.title}} {{post.body}} {{/blog-post}}{{/each}}
app/routes/index.jsexport default Ember.Route.extend({ model() { return this.store.findAll('post'); }});
https://ember-twiddle.com/7ff20a68a367df12a894294d837bc391?openFiles=controllers.application.js%2Cblog-post.template.hbs
Controllers
A controller is a routable object meant to “decorate” a model with display logic.
Controllers
A controller is a routable object meant to “decorate” a model with display logic.
Controllers
Ember CLI Mirage
MirageEmber CLI Mirage is a client side mock server to develop and prototype applications.
Fixtures and FactoriesWe now have a couple of choices. We can create data using fixtures, or generate them through a factory. It's probably a good idea to use factories. They can easily be added to your tests.
Fixtures
Mirage
Factories
More information in...
● https://guides.emberjs.com/v2.4.0/
● http://emberjs.com/api/
● https://ember-twiddle.com/
● http://emberigniter.com/
● http://yoember.com/