#410 Ember Part 2 pro
Here we continue our look into Ember.js. First we add a JSON API to persist the entries through ember-data. Then we finish up the project by adding a computed property and a view object.
- Download:
- source codeProject Files in Zip (84 KB)
- mp4Full Size H.264 Video (26.8 MB)
- m4vSmaller H.264 Video (14.9 MB)
- webmFull Size VP8 Video (20.6 MB)
- ogvFull Size Theora Video (32.7 MB)
Resources
- Ember.js
- ember-data
- Episode 408: Ember Part 1
- Episode 409: Active Model Serializers
- Episode 405: AngularJS
terminal
rails g resource entry name winner:boolean
app/controllers/entries_controller.rb
class EntriesController < ApplicationController respond_to :json def index respond_with Entry.all end def show respond_with Entry.find(params[:id]) end def create respond_with Entry.create(params[:entry]) end def update respond_with Entry.update(params[:id], params[:entry]) end def destroy respond_with Entry.destroy(params[:id]) end end
app/assets/javascripts/models/entry.js
Raffler.Entry = DS.Model.extend({ name: DS.attr('string'), winner: DS.attr('boolean') });
app/assets/javascripts/models/router.js.coffee
Raffler.EntriesRoute = Ember.Route.extend model: -> Raffler.Entry.find()
app/assets/javascripts/models/store.js.coffee
DS.RESTAdapter.configure("plurals", entry: "entries")
app/assets/javascripts/controllers/entries_controller.js.coffee
Raffler.EntriesController = Ember.ArrayController.extend addEntry: (name) -> Raffler.Entry.createRecord(name: name) @get('store').commit() drawWinner: -> @setEach('highlight', false) pool = @rejectProperty('winner') if pool.length > 0 entry = pool[Math.floor(Math.random()*pool.length)] entry.set('winner', true) entry.set('highlight', true) @get('store').commit() allWinners: (-> @everyProperty('winner', true) ).property('@each.winner')
app/assets/javascripts/views/new_entry_view.js.coffee
Raffler.NewEntryView = Ember.View.extend templateName: 'new_entry' tagName: 'form' submit: -> @get('controller').send('addEntry', @get('newEntryName')) @set('newEntryName', "") false
app/assets/javascripts/templates/entries.handlebars
{{view Raffler.NewEntryView}} <ul> {{#each controller}} <li> {{name}} {{#if winner}} <span {{bindAttr class="winner highlight"}}>WINNER</span> {{/if}} </li> {{/each}} </ul> <button {{action drawWinner}} {{bindAttr disabled="allWinners"}}>Draw Winner</button>
app/assets/javascripts/templates/new_entry.handlebars
{{view Ember.TextField valueBinding="view.newEntryName"}} <input type="submit" value="Add">