data models in ember
I have an ember-cli app where I need to dynamically generate some ember data models based on configuration data that resides in a remote location. I have an initializer which defers application readiness, and fetches the config data via ajax.
Now in an old-school ember app, from that point I would simply generate my DS.Model
objects and assign them to the global App
ember application instance. However, in an ember-cli I am not sure how to define the models so that they can be found by the rest of the application, since by default ember-cli's resolver generates models and their name based on filename/directory structure.
It turns out it was a bit simpler than I thought. Basically just needed to use Ember.Application.register
in my initializer for each model that I dynamically generated, like so:
import Ember from "ember";
import request from "ic-ajax";
import DS from "ember-data";
export default {
name: 'model-config',
initialize: function(container, application) {
application.deferReadiness();
request('/path/to/model/config/data').then(function(response) {
Ember.$.each(response.tables, function(modelName, modelCfg) {
var cfg = {};
Ember.$.each(modelCfg, function(fieldName, fieldCfg) {
if(typeof fieldCfg === 'string') {
cfg[fieldName] = DS.attr(fieldCfg);
} else {
cfg[fieldName] = DS[fieldCfg.type](fieldCfg.model);
}
});
application.register('model:' + modelName, DS.Model.extend(cfg));
});
application.advanceReadiness();
});
}
};
链接地址: http://www.djcxy.com/p/90962.html
下一篇: 数据模型在余烬中