gpt4 book ai didi

javascript - 在 Ember.js 中使用需要将对象注入(inject)到其他对象中

转载 作者:行者123 更新时间:2023-12-03 11:19:09 27 4
gpt4 key购买 nike

我想了解 needs 属性是否可用于将任意对象注入(inject) Controller 、路由和 View 中。

我正在开发一个 Ember.js 应用程序,其中我正在编写一个自定义数据服务层,该层与后端通信以加载和保留数据。我定义了代表各种后端服务的 Ember 对象,例如:

App.SessionServiceClient = Em.Object.extend({
// methods and attributes
});

App.UserServiceClient = Em.Object.extend({
// methods and attributes
});

我现在将这些对象注册到应用程序的容器中,以使它们可用于 DI:

App.register('service:session', App.SessionServiceClient, {singleton: false});
App.register('service:user', App.UserServiceClient, {singleton: false});

现在对象可用于注入(inject),如果我有一个仅需要 SessionServiceClient 的 Controller ,我可以执行以下操作:

App.SignInController = Em.ObjectController.extend({
needs: ['service:user'], // using the needs to declare dependency
actions: {
// actions for the view
}
});

当我尝试这个时,它不起作用。 Ember.js 可以做到这一点还是我做错了?

最佳答案

最佳实践是使用初始化程序将您的服务注入(inject)到您需要它的 Controller 中。SEe http://ember.zone/ember-application-initializers/

Ember.Application.initializer({
name: "sessionLoader",
after: "store",

initialize: function(container, application) {
container.register('service:session', App.SessionServiceClient, {singleton: false});
container.injection('route', 'session', 'service:session');
container.injection('controller', 'session', 'service:session');
});
}
});

此外,您应该真正尝试切换到 Ember-CLI 或至少使用 ES6 模块结构。 (即使用导入而不是全局变量。)

关于javascript - 在 Ember.js 中使用需要将对象注入(inject)到其他对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27199132/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com