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

后端 未结 1 1054
轮回少年
轮回少年 2021-02-03 13:31

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

相关标签:
1条回答
  • 2021-02-03 14:10

    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.

    0 讨论(0)
提交回复
热议问题