Creating new objects with Ember

I’ve been using Ember on my new projects and while it has a steep learning curve, isn’t as featured as a server-based web framework and documentation is scattered, it allows you to create a clean and maintainable frontend.

The applications I’ve been creating are largely CRUD and I couldn’t find any good guidance on how to structure Ember to create new objects, particularly since the TodoMVC guide had not been updated since Ember 1.10. The TodoMVC guide had previously indicated to create new objects during the create action. But I found that this pattern as-is would leave unsaved objects in the store if the server rejected the POST action and the user navigated back to an index view.

I ended up using an alternate approach of using a form object and instantiating the object in the route. The form object encapsulates client-side validation (rather than inserting this in the controller). As the route created the object, the route is also responsible for tearing down the object if it is not used. This avoids having unsaved records in the local store and not on the server.

Here is an example pattern that I use for “new” routes:

// app/routes/examples/new.js

export default Ember.Route.extend({
  model: function() {
    return this.store.createRecord('example');
  },
  deactivate: function() {
    var model = this.modelFor('examples.new');
    if (model.id === null) {
      this.store.unloadRecord(model);
    }
  }
});

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *