本人原文地址發佈在:點擊這裏javascript
As ember document suggestion, we may define a model as a structure which will be used for serialization or deserialization to request from RESTful-based server or others.java
if we define a model as: json
1 var Person = DS.Model.extend({ 2 firstName: DS.attr('string'), 3 birthday: DS.attr('date') 4 });
And we used like this:app
1 this.store.find('person', 1); // => { id: 1, name: 'steve-buscemi' }
At the last, the 「Store」 will give us an object which has been deserialised by 「Adapter」 in Ember.js, it just like Object-relationship mapping(ORM), we could use an object instead of json string, it’s very convenient.this
It must have a premise that we have known what json string is or a constant structure. But if not,how do we solve this problem in Ember.js? spa
The problem is a common issue about 「how to create an object/model dynamically」, it is difficult maybe, if you have some experience with C# or Java language, because they are both static type of language which is difficult to create or define a structure at runtime. But in javascript you can easily define a object whatever you want, it’s dynamic type of language also in Ember.js, we just need to do little work to implement this feature.code
I will give an example as below:orm
Step 1:server
1 // app/controllers/ 2 3 import DS from ‘ember-data’; 4 5 import Ember from ‘ember’; 6 7 8 modelName: 「info」, 9 10 11 init: function() { 12 13 var info = this.getStructureInfo(); 14 15 this.container.register('model:' + this.get(‘modelName’), this.generateModel(info)); 16 17 }, 18 19 20 generateModel: function(content) { 21 22 var attrs = {}; 23 24 for(var key in content) { 25 26 attrs[key] = DS.attr(‘string’); 27 28 } 29 30 }, 31 32 33 getStructureInfo: function() { 34 35 return [‘car', ‘price', ‘discount’]; 36 37 }
In Step 1, we get structure information from 「getStructureInfo」 function, and then register a 「info」 model created by 「generateModel」 function.blog
Step 2:
1 // app/controllers/ 2 loadData: function() { 3 return this.store.find(this.get(‘modelName’); 4 }
In step 2, we just use 「loadData」 function to load data from store automatically, the only one parameter is modelName. Is it easy?
In Ember.js the container.register function could inject object on runtime, so we could inject model or other object into 「Store」, then we used the 「injected」 object directly.
[ORM](https://en.wikipedia.org/wiki/Object-relational_mapping)
[static vs dynamic language](http://stackoverflow.com/questions/1517582/what-is-the-difference-between-statically-typed-and-dynamically-typed-languages)