How can I create a new record using Ember.js and ember-data?

dmzza picture dmzza · Jul 23, 2012 · Viewed 8.1k times · Source

I have compiled this example from various documentation and examples that I've found, but I haven't found a complete example using a Router and ember-data to simply create a new record, so this is my whack at it.

The Example

http://jsfiddle.net/dmazza/Hb6BQ/4/

I have a person (DS.Model) with a firstName and lastName.

I have a Router with index and create routes, where the create form appears in the outlet of the PeopleView.

I'm using Ember.TextField's bound to the attributes of a new Person created with App.Person.createRecord({}), as the content of PersonCreateController.

Note that I'm intentionally using separate controllers for each outlet as recommended by @wycats here: https://github.com/emberjs/ember.js/issues/1050#issuecomment-6497907

The Problem(s)

I seem to be running into the same problem over and over again. I try to use a method like App.Person.find(), and it will tell me this:

Uncaught TypeError: Cannot read property 'find' of undefined 

This will happen for:

  1. App.Person.find()
  2. App.Person.createRecord({})
  3. App.Store.find(App.Person)
  4. Several other methods (I'll update this list when I think of them)

The Question

  1. Am I even creating a new record the right way using these tools?
  2. Why might I be getting this error above? (You can see this error if you open your web inspector, pause on uncaught exceptions and make sure you are in the result( fiddle.jshell.net ) frame as opposed to )

Answer

pangratz picture pangratz · Jul 23, 2012

I propose something along this lines, see http://jsfiddle.net/pangratz666/bb2wc/:

Handlebars:

<script type="text/x-handlebars" data-template-name="application">
    <div class='container' id='application'>
        <header>
            <h1>People</h1>
        </header>
        <article>
            {{outlet}}
        </article>
    </div>    
</script>

<script type="text/x-handlebars" data-template-name="people">
    <ul>
        {{#each person in controller}}
            <li>{{person.firstName}} {{person.lastName}}</li>
        {{/each}}
    </ul>
    <button {{action newPerson }}>Create New Person</button>
    <hr/>
    {{outlet}}
</script>

<script type="text/x-handlebars" data-template-name="person_create">
    First name: {{view Ember.TextField valueBinding="firstName"}} <br/>
    Last name: {{view Ember.TextField valueBinding="lastName"}} <br/>
    <button {{action submitForm }}>Save</button>
    <button {{action cancel }}>Cancel</button>
    <h3>Current values: {{firstName}} {{lastName}}</h3>
</script>

​JavaScript:

App = Ember.Application.create();

App.Person = DS.Model.extend({
    firstName: DS.attr('string'),
    lastName: DS.attr('string')
});

// Note: these properties are expected to be dasherized
App.Person.FIXTURES = [
    {
    "id": 1,
    "first_name": "Joe",
    "last_name": "Smith"},
{
    "id": 2,
    "first_name": "James",
    "last_name": "Dolan"},
{
    "id": 3,
    "first_name": "Jim",
    "last_name": "Carry"}
];

App.Store = DS.Store.extend({
    revision: 4,
    adapter: DS.FixtureAdapter.create()
});

/*
 * Routing
 */
App.Router = Ember.Router.extend({

    enableLogging: true,

    root: Ember.Route.extend({
        index: Ember.Route.extend({
            route: '/',
            connectOutlets: function(router, people) {
                // set the content to all available persons
                router.get('peopleController').set('content', App.Person.find());
                router.get("applicationController").connectOutlet("people");
            },
            index: Ember.Route.extend({
                route: '/'
            }),
            create: Ember.Route.extend({
                route: '/create',
                connectOutlets: function(router, person) {
                    // set/clear the content for the personCreateController
                    router.get('personCreateController').set('content', {});
                    router.get("peopleController").connectOutlet("personCreate");
                },

                // as proposed in https://github.com/emberjs/ember.js/pull/1139
                exit: function(router) {
                    // called when we navigate away from this route: remove
                    // the connected outlet, which is the createPerson view
                    router.get('peopleController').set('view', null);
                },

                submitForm: function(router, event) {
                    // get the content of the personCreateController
                    var hash = router.getPath('personCreateController.content');
                    // create a new person
                    App.Person.createRecord(hash);
                    // navigate back to the index route
                    router.transitionTo('index');
                },

                // cancel button pressed
                cancel: Ember.Route.transitionTo('index')
            }),

            // show the "dialog" for creating a new person
            newPerson: Ember.Route.transitionTo('create')
        })
    })
});

App.ApplicationController = Ember.Controller.extend();
App.PeopleController = Ember.ArrayController.extend();
App.PersonCreateController = Ember.ObjectController.extend();

App.ApplicationView = Ember.View.extend({ templateName: 'application' });
App.PeopleView = Ember.View.extend({ templateName: 'people' });
App.PersonCreateView = Ember.View.extend({ templateName: 'person_create' });

App.initialize();​