How to make Ember.js behave with Grails controller names?

Grails is quite powerful and allows you to turn domain objects into JSON with a single statement ( object as JSON ). Unfortunately, this is not enough to interact with Ember.js for several reasons.

How can I make Grails play well with Ember.js?

+4
source share
2 answers

Good question me!

Ember.js and its auto-AJAX-in-browser-data-store ninjitsu expect the URL to look a certain way and the JSON to look a certain way. Due to the fact that each tool works, it is easier to make appropriate changes on both sides of the equation!

What Grails Offers

For a MyCoolDomainClass domain MyCoolDomainClass with MyCoolDomainClassController , Grails wants to provide the URL /app/myCoolDomainClass . If you configured the controller to contain something line by line:

 def index() { render MyCoolDomainClass.list() as JSON } 

You will get an answer that looks like this:

[{ id: 1, name: "Bob"}, {id: 2, name: "Sally"}]

What does Ember want

In Ember.js, you can create a model with the same properties. Using ember-data , you can easily connect the data store in the browser using your backend. Unfortunately, what Ember.js wants is different. He expects url /my_cool_domain_class provide data:

{ mycooldomainclass: [ { id: 1, name: "Bob"}, {id: 2, name "Sally"}] }

Combination

UPDATE . I created an ember-data-grails repository on Github that takes care of all these modifications for you, and demonstrates how to make a controller that plays well!

+12
source

I start with emberjs, working for two years in Grails 1.3.7, so this is what I would do so that you can:

 { mycooldomainclass: [ { id: 1, name: "Bob"}, {id: 2, name "Sally"}] } 

It is quite simple:

 def c = Product.createCriteria() def products = c.list{ //your criteria } res = products.collect {a -> return [id:a.id, name:a.name, price:a.price, categoryname: a.category.name] } response.setHeader( "Pragma", "no-cache" ) response.setHeader( "Cache-Control", "no-cache" ) response.setDateHeader( "Expires", 0 ) render(contentType: 'text/json') {[ 'mycooldomainclass': res ]} 
0
source

All Articles