如何使用Ember.js和ember-data创建新记录?

时间:2012-07-23 20:21:20

标签: ember.js ember-data ember-old-router

我已经从我找到的各种文档和示例中编译了这个示例,但是我还没有找到一个完整的示例,使用路由器和ember-data来简单地创建一个新记录,所以这是我的重点。

示例

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

我有一个人(DS.Model),带有firstName和lastName。

我有一个带索引和创建路径的路由器,其中创建表单出现在PeopleView的插座中。

我正在使用Ember.TextField绑定到使用App.Person.createRecord({})创建的新Person的属性,作为PersonCreateController的内容。

请注意,我有意在@wycats的推荐下为每个插座使用单独的控制器:https://github.com/emberjs/ember.js/issues/1050#issuecomment-6497907

问题

我似乎一遍又一遍地遇到同样的问题。我尝试使用像App.Person.find()这样的方法,它会告诉我:

Uncaught TypeError: Cannot read property 'find' of undefined 

这将发生在:

  1. App.Person.find()
  2. App.Person.createRecord({})
  3. App.Store.find(App.Person)
  4. 其他几种方法(我想到的时候会更新这个列表)
  5. 问题

    1. 我甚至使用这些工具以正确的方式创建了新记录吗?
    2. 为什么我上面会收到此错误? (如果您打开Web检查器,可以看到此错误,暂停未捕获的异常并确保您在结果(fiddle.jshell.net)框架中而不是)

2 个答案:

答案 0 :(得分:4)

我提出了这方面的建议,请参阅http://jsfiddle.net/pangratz666/bb2wc/

<强>车把

<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();​

答案 1 :(得分:3)

随着在pre4中引入新的Ember路由器,我想我会更新这个答案。这是对我有用的(警告:CoffeeScript):

App.Router.map ->
    @resource "posts", ->
        @route "new"

App.PostsNewRoute = Ember.Route.extend
    setupController: (controller, model) ->
        controller.set 'content', {}

App.PostsNewController = Ember.ObjectController.extend
    submitForm: (event) ->
        App.Post.createRecord @content
        @transitionToRoute 'posts.index'

App.PostsNewView = Ember.View.extend
    controller: 'App.PostsNewController'

我的模板看起来像这样:

    <script type="text/x-handlebars" data-template-name="posts/new">
      <div class="row">
        <div class="span12">
          <form class="create-post">
            <fieldset>
              <legend>{{_ "Post"}}</legend>
              <label>{{_ "Post Title"}}</label>
              {{view Ember.TextField valueBinding="postTitle"}}
              <!-- etc. etc. -->
            </fieldset>
          </form>
        </div>
      </div>
      <div class="row">
        <div class="span12 push-right">
          <a class="btn btn-primary" {{action "submitForm"}}>{{_ "Save"}}</a>
          {{#linkTo "posts.index" class="btn"}}{{_ "Cancel"}}{{/linkTo}}
        </div>
      </div>
    </script>

我很想听听有关我的方法的评论。