Ember: unsaved models in dynamic URLs

五迷三道 提交于 2020-01-05 04:42:29

问题


I'm currently using the FixtureAdapter in my Ember app, but when I switch to the RESTAdapter, my URLs no longer work.

The app is a scorekeeping type thing, and I want users to be able to log all the scores without having to be connected to the Web. After the game is finished they can optionally save all the data to the server.

Now, when Ember wants to route to say, matches/:match_id, the ID isn't there because I didn't commit anything to the server/store, so my models don't yet have an ID and I get URLs like: /match/null/games/null

Is this expected behaviour? And if so, is there a workaround? I thought about using model.clientId and then overriding the model hook for each route to try and fetch the Model from the store using the id when present and falling back to clientId. Any other ideas?

UPDATE March 10, 2013:

The following seems to fit my needs and allows to (for now) forget about moving back and forth between local storage and the REST adapter:

App.Store = DS.Store.extend({
  revision: 11,
  adapter: DS.RESTAdapter.extend({
    namespace: 'api/v1',
    bulkCommit: true,
    generateIdForRecord: function(store, record) {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
      });
    }
  })
});

UUID function taken from: Create GUID / UUID in JavaScript?


回答1:


If a record hasn't been committed, then it shouldn't have an id yet. Furthermore, a url that serializes the application state of viewing that record doesn't make any sense because the record won't exist in another browser until it is committed. You couldn't just paste the url elsewhere and have it load where you left off.

I think what you really want to do is serialize the application state differently (ie. generate a less specific url) when the record is uncommitted. You can achieve this by overriding the serialize method in your route.

For example,

App.PostRoute = Ember.Route.extend({
    serialize: function(model, params) {
        if (model && model.get('isNew')) {
            // corresponds to path '/post/:post_id'
            return { post_id: 'new'}
        }

        return this._super(model, params);
    }
});

Now if you call transitionToRoute('post', post) from your controller, where post is a newly created but uncommitted record, the application state will be serialized to the path /post/new. If you pass it a committed record with an id, it will be serialized as usual.



来源:https://stackoverflow.com/questions/15187401/ember-unsaved-models-in-dynamic-urls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!