3
votes

The tutorials & guides that I've found suggest that Ember.js models are very data centric, in that you have data in the browser that is persisted to the server and/or a model is filled with data from the server.

How about something that is more verb centric? For example, my case is that, so far, I have a "Search" model, where a search has a query, a state ("beforesearch","duringsearch", etc...), and, hopefully, some results. I want for the search to then "runQuery", which fires off an ajax request to the server, which returns and fills the model with the results, and changes its state to "aftersearch".

What's the best way of handling such verbs on models? Should the "runQuery" go via ember-data, or just manually fired off using $.ajax or similar? Am I maybe thinking about models in the wrong way, and this should actually go via a controller?

Edit: After reading up a bit on REST, I think what I'm wanting is to POST to a "controller" resource. So, for example:

POST: /searches (to create a search)

POST: /searches/1/run (to execute search 1's "run" controller

Does Ember.js / ember-data have a recommended way of calling controller resources like this?

1

1 Answers

3
votes

Ember-data is very oriented around using model objects that contain various information fields and relationships and are defined by a unique id. Half of my API is like what ember-data expects and half is like you described, it is more about data processing or performing a calculation than creating/retrieving/updating/deleting a data object that has an id. It doesn't make sense to treat these calculations the same and assign it an id and persist it in the database.

In my case, since I have both ember-data style data objects and calculation functionality I use a mix of ember-data and custom ajax requests. I have relational data stored that is retrieved by ember-data but I augment the models to include access to the calculation portions.

For example:

App.Event = DS.Model.extend({
  name: DS.attr('string'),
  items: DS.hasMany('App.Item'),
  ...etc...

  searchData: null,
  searchInEvent: function(data) {
    var _this = this;
    return $.ajax({
      url: "/api/events/" + this.get('id') + "/search/",
      dataType: 'json',
      type: 'POST',
      data: data
    }).then(function(result){
      _this.set('searchData', result);
    });
  }
});

App.Event is a normal ember-data model and is loaded by the router through the usual ember conventions, and as the various controllers need access to the search functionality they can access it through searchInEvent and searchData that were added to the model.