【发布时间】:2014-03-09 18:02:11
【问题描述】:
由于 Ember App Kit 使用 ES6 模块,我对放置扩展或配置基类的代码的最佳位置有点困惑。例如,下面的代码可以为无哈希 URL 使用 html5 历史记录:
//enable HTML5
Router.reopen({ location: 'history' });
或以下代码为所有视图提供 afterRender 挂钩:
Ember.View.reopen({
didInsertElement : function() {
this._super();
Ember.run.scheduleOnce('afterRender', this, this.didRenderElement);
}
});
在阅读 Ember App Kit 的 github 上的问题以及 stackoverflow 上的各种答案后,根据我的理解,仅导出 ES6 模块而不包含任何“副作用”,或者换句话说,代码是理想的不是导出对象的一部分。然而,似乎副作用技术目前正在使用,甚至由许多开发人员提出。例如,我将 html5 历史配置放在了我的 router.js 模块中:
/**
* Ember Router
*
* @module Router
* @exports appkit/Router
*/
var Router = Ember.Router.extend({});
//enable HTML5
Router.reopen({ location: 'history' });
Router.map(function() {
this.route('login');
this.route('logout');
this.route('dashboard');
this.route('orders');
this.route('customers');
});
export default Router;
您可以看到模块导出了 Router 对象,但重新打开语句只是松散地位于文件中。
为了让事情井井有条并利用这项技术,我想我可以创建一个配置文件夹,然后在文件夹中创建模块,如 view.js、router.js 等:
view.js
/**
* Ember ViewConfig
*
* @module ViewConfig
* @exports appkit/ViewConfig
*/
Ember.View.reopen({
didInsertElement : function() {
this._super();
Ember.run.scheduleOnce('afterRender', this, this.didRenderElement);
}
});
export default {};
app.js
/*
* Config Classes
*/
import ViewConfig from 'appkit/config/view';
import RouterConfig from 'appkit/config/router';
...
这行得通,但我觉得我打破了惯例。这有意义还是我错过了什么?
编辑: 我想另一种解决方案是使用函数导出对象,例如 applyConfig,然后在 App.js 中导入后调用该函数。但这并没有解决我仍然会在 App.js 本身中使用“副作用”这一事实。
【问题讨论】:
标签: javascript ember.js