我很好奇使用Ember.js实现服务层的最佳方法是什么。 A在Ember指南中找不到任何关于它的建议。 例如,我有一些验证码,我可以在多个控制器中使用,我不想将它们复制并粘贴到所有控制器中。
你会使用普通的javascript对象和方法,实现服务逻辑,还是有更类似于ember的方法呢?
感谢。
答案 0 :(得分:2)
Emberjs内置了对服务层的内置支持,现在还没有记录。您可以使用基于依赖注入的服务层。
见下面的例子。还有public repository on GitHub with example
<强>的index.html 强>
<!doctype html>
<html lang="en" data-framework="emberjs">
<head>
<meta charset="utf-8">
<title>ember_js_di_example</title>
<script src="./bower_components/jquery/dist/jquery.js"></script>
<script src="./bower_components/handlebars/handlebars.js"></script>
<script src="./bower_components/ember/ember.js"></script>
<script src="./index.js"></script>
</head>
<body>
<script type="text/x-handlebars" id="Home">
<div>
<div>My name is <b>{{me.name}}</b></div>
<div>My wife name is <b>{{me.wife.name}}</b></div>
<div>My wife name is <b>{{wife.name}}</b> (based on controller injection)</div>
<div>My children name is <b>{{me.children.name}}</b></div>
</div>
</script>
<script type="text/x-handlebars">
{{ outlet }}
</script>
<强> index.js 强>
var Services = Ember.Namespace.create();
// service class one
Services.Me = Ember.Object.extend({
name: function () {
return 'Jan'
}.property()
})
// service class two
Services.Wife = Ember.Object.extend({
name: function () {
return 'Sarka'
}.property()
})
// service class three
Services.Children = Ember.Object.extend({
name: function () {
return 'Ondra'
}.property()
})
App = Ember.Application.create({
LOG_TRANSITIONS: true,
ready: function () {
// Register service class - instance will be created on demand
this.register('service:me', Services.Me);
this.register('service:wife', Services.Wife);
// Register already instantiated service
this.register('service:children', Services.Children.create(), {instantiate: false});
// inject service to all routes, controllers, service will be accessible as me property
this.inject('route', 'me', 'service:me');
this.inject('controller', 'me', 'service:me');
// inject wife and children to me, will be accessible as wife and children property
this.inject('service:me', 'wife', 'service:wife');
this.inject('service:me', 'children', 'service:children');
// inject wife only to application controller, will be accessible as wife property on home controller
this.inject('controller:Home', 'wife', 'service:wife')
}
});
App.Router.map(function () {
this.resource('Home', {path: '/home'});
});
答案 1 :(得分:0)
我认为目前重用控制器代码的最佳方法是使用继承...也就是说,如果你想在多个控制器中使用公共代码,那么创建一种带有重复逻辑的抽象控制器,然后为您的其他控制器扩展。这就是我过去做过的事情,对我来说效果很好。
但是,我在路由器方面遇到了类似的问题。你总是可以使用mixin。示例:
App.MyAbstractController = Em.Controller.extend({
commonMethod: function() {
// something common to all controllers
}
})
App.ActualControllerOne = App.MyAbstractController.extend();
App.ActualControllerTwo = App.MyAbstractController.extend();