Creating a single model in EmberJS

What is the correct way to define a model and route to build a model that can be used as application data.

App.Router.map(function(){ this.resource("main", {path:"/"}); }); App.MainRoute = Ember.Route.extend({ model:function(){ return App.Main.find(); } }); App.Main = DS.Model.extend({ appName:DS.attr('string') }); App.Store = DS.Store.extend({ revision: 11, adapter: DS.RESTAdapter.create({ namespace: 'api/v1' }) }); 

As a result, it calls api/v1/mains . But I want it to call api/v1/main , which returns the application data, which is the only object, e.g.

 { "appName":"MyApp", "lastLogin": "Sat May 11 2013 11:20:03 GMT+0530", ... } 

I know about setting up the plural, but I think this is the wrong way to do this. Any help would be greatly appreciated. Thanks in advance.

EDIT: when setting up Plurals rendering template

 App = Ember.Application.create(); App.Router.map(function(){ this.resource("main", {path:"/"}); }); App.MainRoute = Ember.Route.extend({ model:function(){ return App.Main.find(); } }); DS.RESTAdapter.configure("plurals", { main: "main" }); App.Store = DS.Store.extend({ revision: 11, adapter: DS.RESTAdapter.create({ namespace: 'api/v1' }) }); App.Main = DS.Model.extend({ "appName":DS.attr('string') }); 

json received from server

 { "main": { "app_name": "My App" } } 

:

 <script type="text/x-handlebars" data-template-name="main"> This is {{appName}} </script> 
+4
source share
2 answers

The original problem is that you are calling App.Main.find() , which will automatically lead to the creation of an Ember.Arraycontroller for the content from you MainController (generated automatically due to your routing name). This also prompts for a multiple version of your model.

So, changing your plurals to the / main item, you will get the information as you show, but it still appears inside Ember.Arraycontroller . Therefore, to view this template, you must run it through {{#each}} . So this would probably work if you ran it:

 <script type="text/x-handlebars" data-template-name="main"> {{#each main}} This is {{appName}} {{/each}} </script> 

Your solution, identifying an individual record by parsing the key in find() , is correct, because (as you have already correctly pointed out) causes the creation of a singleton ( Ember.ObjectController ), which can then be directly interrogated.

+1
source

Not sure if this is the right approach, but solved it by calling

 App.Main.find("data"); 

and determining the route /api/v1/main/data on the server side.

As a result, App.Main.find("data"); works like selecting a single record from a list of records, and an ObjectController generated for main

0
source

Source: https://habr.com/ru/post/1480199/


All Articles