Ember.js之动态创建模型

本人原文地址发布在:点击这里

 

What problem did we meet?

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.

if we define a model as: 

1 var Person = DS.Model.extend({
2   firstName: DS.attr('string'),
3   birthday:  DS.attr('date')
4 });

And we used like this:

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.

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

 

How did we solve this problem?

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.

 

I will give an example as below:

 

Step 1:

 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.

 

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.

  

Reference

[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)

 

 

 

posted @ 2015-08-20 18:43  史蒂芬King  阅读(752)  评论(0编辑  收藏  举报