What is the difference between Adapter and Fixture Adapter and REST Adapter, in ember-data?

别来无恙 提交于 2019-12-31 12:08:30

问题


What is the difference between Adapter and Fixture Adapter and REST Adapter, and when to use each one?


回答1:


Use DS.FixtureAdapter (or DS.FixtureAdapter.create()) when you don't (yet?) care to communicate with a backend, but will store your data as "fixtures" in the client. Once you've declared a model:

App.Thing = DS.Model.extend({
  name: DS.attr('string'),
  // ...
});

You can define your fixtures:

App.Thing.FIXTURES = [
  {
    id: 1,
    name: '...',
    // ...
  },
  {
    id: 2,
    name: '...',
    // ...
  },
];

And then you can use the ember-data methods on them (e.g. App.Thing.findAll(), etc.) and manipulate them, but of course it will only persist as long as the page does (i.e. the javascript environment).

DS.RestAdapter, usable though apparently still under development, was designed to fit well with a Rails API, but could probably be modified / extended to work with whatever RESTful API you're working with. It knows to process App.Thing.findAll() by making a call to /things, and to process App.Thing.find(12) with a call to /things/12. This is a relative path, appended to the namespace parameter you pass in:

App.store = DS.Store.create({
  revision: 4,
  adapter: DS.RestAdapter.create({
    namespace: 'http://what.ever/api/v1'
  })
});

DS.Adapter is rather abstract: the superclass of the aforementioned built-in Adapters. If neither suit your needs, you may well want to implement your own:

App.adapter = DS.Adapter.create({
  find: function(store, type, id) {
    // ...
    jQuery.get( ... , function(data) {
      store.load(type, id, data);
    });
  },
  createRecord: function(store, type, model) {
    // ...
    jQuery.post( ... , function(data) {
      store.didCreateRecord(model, data);
    });
  },
  // ...
});
App.store = DS.Store.create({
  revision: 4,
  adapter: App.adapter
});

Hope that helps. See the readme doc at https://github.com/emberjs/data for more information.



来源:https://stackoverflow.com/questions/11910496/what-is-the-difference-between-adapter-and-fixture-adapter-and-rest-adapter-in

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