简体   繁体   中英

How to use custom urls with ember-data?

How is it possible to use custom urls with ember-data? For example:

PUT /users/:user_id/deactivate
PUT /tasks/:task_id/complete
PUT /jobs/1/hold

There doesn't seem to be any way to do this right now with ember-data. However, it's trivial just to fall back to ajax and use that instead. For example:

App.UsersController = Ember.ArrayController.extend
  actions:
    deactivate: (user) ->
      # Set the user to be deactivated
      user.set('deactivated', true)

      # AJAX PUT request to deactivate the user on the server
      self = @
      $.ajax({
        url: "/users/#{user.get('id')}/deactivate"
        type: 'PUT'
      }).done(->
        # successful response. Transition somewhere else or do whatever
      ).fail (response) ->
        # something went wrong, deal with the response (response.responseJSON) and rollback any changes to the user
        user.rollback()

You can define fairly complex URLs from within your Ember router.

App.Router.map(function() {
  this.resource('posts', function() {
    this.route('new');
  });
  this.resource('post', { path: '/posts/:post_id' }, function() {
    this.resource('comments', function() {
      this.route('new');
    });
    this.route('comment', { path: 'comments/:comment_id'});
  });
});

This gives us:

/posts
/posts/new
/posts/:post_id
/posts/:posts_id/comments
/posts/:posts_id/comments/new
/posts/:posts_id/comments/:comment_id

Ember decides whether to use GET, POST, PUT or DELETE depending on whether it is fetching from the server, persisting a new resource, updating an existing resource or deleting it.

See here for a basic but functioning blog type app with posts and comments which can be persisted or here for a much more complex app which fetches resources from a 3rd party server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM