如何在创建后立即显示关联模型的属性?

时间:2013-11-29 21:32:44

标签: javascript ember.js ember-model

如果我创建新的电影对象,则不会显示所有者(App.User)的关联用户名。它仅在我重新加载页面后显示。我知道如何在创建新电影后立即显示关联的用户名吗?

到目前为止

代码:

App.Movie = Ember.Model.extend({
  objectId: Ember.attr(),
  title: Ember.attr(),
  year: Ember.attr(),

  owner: Ember.belongsTo('App.User', {
    key: 'owner',
    serializer: UserType
  })
});

App.User = Ember.Model.extend({
  objectId: Ember.attr(),
  username: Ember.attr(),
});

App.Movie.adapter = Ember.Adapter.create({
  createRecord: function(record) {
    return Ember.$.ajax({
      headers: {
        'X-Parse-Application-Id': '',
        'X-Parse-REST-API-Key': ''
      },
      type: 'POST',
      url: 'https://api.parse.com/1/classes/Movie',
      contentType: 'application/json',
      data: JSON.stringify(record)
    }).then(function(data) {
      record.load(data.objectId, record.get('_data'));
      record.didCreateRecord();
    });
  }
});

{{#each movie in this}}
  <tr>
    <td>{{movie.year}}</td>
    <td>{{movie.title}}</td>
    <td>{{movie.owner.username}}</td>
  </tr>
{{/each}}

App.MoviesIndexController = Ember.ArrayController.extend({
  rawDescription: '',
  year: '',
  title: '',

  errors: null,

  actions: {
    createMovie: function () {
      var rawDescription = this.get('rawDescription');

      if (!rawDescription.match(/([^$]+)(\d{4})/)) {
        this.set('errors', {
          rawDescription: 'Oh snap! Please include the movie\'s title and year.'
        });
      } else if (!this.isUnique({
        rawDescription: rawDescription
      })) {
        this.set('errors', {
          rawDescription: 'Oh snap! The movie already exists.'
        });
      } else {
        var rv = this.parseRawDescription(this.get('rawDescription')),
          title = rv[1],
          year = rv[2],
          newMovie = App.Movie.create({
            owner: App.Session.authUser,
            ratings: [{ objectId: App.Session.objectId, value: 0 }]
            title: title,
            watched: false,
            year: year,
          });

        newMovie.save();

        this.setProperties({ rawDescription: '', errors: null });
      }
    }
  }
});

1 个答案:

答案 0 :(得分:0)

我将其显示为正常工作,您确定App.Session.authUser已填充吗?如果你在创建后尝试console.log(newMovie.get('owner.username'))它会显示什么吗?

http://emberjs.jsbin.com/AYidAdi/1/edit