Get server URL for Ember DS.Model Class
In using Ember Data for my models, there are some cases where I need to work around the data limitations and access other quasi-restful URLs on my server.
For example, I have a Feed
object that records a stream of data. For accessing the models I have a RESTful endpoint:
/feeds/:feed_id
In order to start and stop recording a feed, I need to send a PATCH
to a url like:
/feeds/:feed_id?update_action=start
Subsequently I can reload my model and see the changes reflected therein.
In this case, I need to access $.ajax
and the URL is the same as the one Ember would use. However, I can't figure out how to eke this information out of Ember.
So far, the best I can do is:
DS.Model.reopen
rootForModel: Ember.computed( ->
@.store.adapterForType(@).serializer.rootForType(@.constructor)
)
pluralRootForModel: Ember.computed( ->
@.store.adapterForType(@).serializer.pluralize(@get("rootForModel"))
)
Such that for an instance of App.FeedItem
I can do:
this.get("rootForModel") # feed_item
this.get("pluralRootForModel") # feed_items
And I'm guessing this would stay in sync with any settings made in the Adapter etc.
Subsequently, I can call like:
$.ajax
url: @get("pluralRootForModel") + "/" + @get("id")
data:
update_action: "start"
type: "PATCH"
Is this totally out in left field? Is there a more direct way to compose these URLs?
Another (related issue) is getting the underscored name for a given model.
App.MyModelController => my_model_controller
I've done something like:
Ember.Object.reopenClass
###*
* The underscored name for this.
* i.e. App.MyClass -> my_class
* From an instance, use this.constructor.underscored_class_name()
* @return {String} This classname, underscored.
###
underscored_class_name: ->
_.underscored("#{@}".replace(/^.*?./g, ""))
Is this crazy? Are there any better ways?
Check out buildURL
in DS.RESTAdapter
.
If you want to use underscores in server paths and keys, check out DS.ActiveModelAdapter
(and its default serializer, DS.ActiveModelSerializer
). This adapter has its own implementation of buildURL
.
上一篇: 如何应用D3条形图的模式?