Ember.js - Editing items in a list

by ud3323

HTML

<script src="https://github.com/downloads/emberjs/ember.js/ember-0.9.1.min.js"></script>
<script type="text/x-handlebars">
    {{#collection contentBinding="App.projectController"}}
        {{content.name}} ({{content.source}})

        {{#view App.ProjectEditLink projectBinding="content" tagName="span"}}
            <a href="#">edit</a>
        {{/view}}
        <br>
    {{/collection}}

    <hr>

    {{view App.ProjectForm projectBinding="App.projectController.current"}}
</script>

<script type="text/x-handlebars" data-template-name="project_form_template">
    <label for="source">Edit source:</label>
    {{view Ember.TextField id="source" valueBinding="App.projectController.editValue"}}
    
    {{#view Ember.Button target="App.projectController" action="saveCurrent"}}
        Save
    {{/view}}
</script>

JavaScript

App = Ember.Application.create();

App.Project = Ember.Object.extend({
    save: function(value) { console.log('saving value:' + value) }
});

App.projectController = Ember.ArrayController.create({
    content: [],
    current: null,
    editValue: null,
    
    saveCurrent: function() { 
        this.setPath('current.source', this.get('editValue'));
        this.get('current').save(this.get('editValue'));
    },
    
    // Create an observer to watch for a change in the current project
    currentProjectDidChange: function() {
        this.set('editValue', this.getPath('current.source'));
    }.observes('current')
});

App.ProjectEditLink = Ember.View.extend({
    click: function() {
        App.projectController.set('current', this.get('project'));
    }
});

App.ProjectForm = Ember.View.extend({
    templateName: 'project_form_template'
});

App.projectController.pushObject(App.Project.create({ name: "jQuery",   source: "jquery.js"   }));
App.projectController.pushObject(App.Project.create({ name: "Ember",    source: "ember.js"    }));
App.projectController.pushObject(App.Project.create({ name: "Backbone", source: "backbone.js" }));