Emberjs-app-concrn-dependency-injection

提供:Dev Guides
移動先:案内検索

EmberJS-依存性注入

これは、あるオブジェクトの依存関係を別のオブジェクトに提供するプロセスであり、オブジェクトとオブジェクト間の依存関係クラスを宣言およびインスタンス化するためにEmberアプリケーションによって使用されます。 _Ember.Application_および_Ember.ApplicationInstance_クラスは、Emberの依存性注入の実装で重要な役割を果たします。

_Ember.Application_クラスはオブジェクトを宣言および構成し、依存関係宣言の「レジストリ」として使用されます。_Ember.ApplicationInstance_クラスはインスタンス化されたオブジェクトの「所有者」として機能します。 ただし、_Ember.Application_クラスはアプリケーションのプライマリレジストリとして機能し、各_Ember.ApplicationInstance_クラスはレジストリとして機能します。

工場登録

ファクトリは、ルート、テンプレートなどのアプリケーションパーツを指定します。 特定のキーで登録されます。 たとえば、インデックステンプレートは_template:index_で定義され、アプリケーションルートは_route:application_で定義されます。

登録キーには2つの部分が含まれます。 1つは工場タイプ、2つ目は工場の名前、両方のセグメントはコロン(:)で分割されています。 たとえば、_Logger factory_を_logger:main key_に登録することにより、アプリケーションを初期化できます。

application.register('mylog:logmsg', MyLogger);

工場注入

一度登録すると、ファクトリを注入できます。 たとえば、次のコードを考慮してください-

application.inject('route', 'mylog', 'mylog:logmsg');

すべてのタイプのルートファクトリは_mylog_プロパティで表され、このプロパティの値は_mylog:logmsg_ファクトリから取得されます。 また、完全なキーを使用して特定の工場に注入することもできます-

application.inject('route:index', 'mylog', 'mylog:logmsg');

ここでは、_mylog_プロパティのみがインデックスルートに挿入されます。

ファクトリインスタンスのルックアップ

ファクトリインスタンスの_lookup_メソッドをアプリケーションインスタンスで使用して、実行中のアプリケーションからインスタンス化されたファクトリを取得できます。 文字列を使用してファクトリを決定し、オブジェクトを返します。

たとえば、アプリケーションインスタンスで_lookup_メソッドを呼び出して、以下に示すようにインスタンス化されたファクトリをフェッチできます-

applicationInstance.lookup('factory-type:factory-name');

以下に示す例は、Emberアプリケーションでのファクトリ登録、インジェクション、およびインスタンスルックアップの使用を示しています。 _app/components/_の下に定義される_dependency-inject_という名前のコンポーネントを作成します。 _dependency-inject.js_ファイルを開き、次のコードを追加します-

import Ember from 'ember';
var inject = Ember.inject;

export default Ember.Component.extend ({
  //load the service in the file/app/services/message.js
   message: inject.service(),
   message: 'Click the above button to change text!!!',
   actions: {
      pressMe: function () {

        //after clicking button, above message will get display at console
         var testText = this.get('start').thisistest();
         this.set('message', testText);
        //after clicking button, it will enter in the component page
         this.get('logger').log('Entered in component!');
      },

      scheduleTasks: function () {
        //scheduling work on specific queues like "sync" or "afterRender"
         Ember.run.schedule('afterRender', this, function () {
            console.log("CUSTOM: I'm in afterRender");
            Ember.run.schedule('sync', this, function () {
               console.log("CUSTOM: I'm back in sync");
            });
         });
      }
   }
});

今コンポーネントテンプレートファイル_app/templates/components/dependency-inject.hbs_を開き、次のコードを入力してください-

<button {{action "pressMe"}}>Click Here</button><br>
<h2>{{message}}</h2>
<button {{action "scheduleTasks"}}>Schedule Tasks!</button>
{{yield}}

_application.hbs_ファイルを開き、次のコード行を追加します-

{{dependency-inject}}
{{outlet}}

私たちは、次のコマンドを使用して、アプリケーションを構成するイニシャライザを作成する必要があります-

ember generate initializer init

_app/initializers/_の下に作成された_init.js_ファイルを開き、次のコードを追加します-

export function initialize(app) {
  //injecting the 'start' property into the component
   app.inject('component', 'start', 'service:message');
}

export default {
  //initializer name
   name: 'init',
   initialize: initialize
};

アプリケーションのさまざまな部分で利用できるサービスを作成します。 次のコマンドを使用して、サービスを作成します-

ember generate service message

今、次のコードで_app/services/_の下に作成された_message.js_サービスファイルを開きます-

import Ember from 'ember';

export default Ember.Service.extend ({
   isAuthenticated: true,
  //after clicking the button, 'thisistest()' triggers and display the below text
   thisistest: function () {
      return "Welcome to finddevguides!!!";
   }
});

次に、起動時にアプリケーションを構成する初期化子を作成します。 初期化子は、次のコマンドを使用して作成できます-

ember generate initializer logger

次のコードで_app/initializers/_の下に作成された_logger.js_初期化ファイルを開きます-

import Ember from 'ember';

//it is an application initializer that run as your application boots
export function initialize(application) {
   var Logger = Ember.Object.extend({
      log(m) {
         console.log(m);
      }
   });

  //Registration key includes two parts; one is factory type and second is
      name of factory
   application.register('logger:main', Logger);

  //Once a factory is registered, it can be injected by using 'application.inject'
      along with 'logger' property
  //and value for this property will come from 'logger:main'factory
   application.inject('component:dependency-inject', 'logger', 'logger:main');
}

export default {
   name: 'logger',
   initialize: initialize
};

次に、次のコマンドを使用して、アプリケーションのインスタンス初期化子を作成します-

ember generate instance-initializer logger

次のコードで_app/instance-initializers/_の下に作成された_logger.js_初期化ファイルを開きます-

//Application instance initializers run as an application instance is loaded
export function initialize(applicationInstance) {
   var logger = applicationInstance.lookup('logger:main');

  //it indicates that instance has booted at console log
   logger.log('Hello...This message is from an instance-initializer!');
}

export default {
  //it is an instance initializer name
   name: 'logger',
   initialize: initialize
};

出力

emberサーバーを実行します。次の出力が表示されます-

Ember.js依存性注入

次に、[ここをクリック]ボタンをクリックします。下のスクリーンショットに示すように、サービスページのテキストが表示されます-

Ember.js依存性注入

今すぐコンソールに移動し、上記のスクリーンショットのようにテキストが表示された後にインスタンス初期化子から表示されるログメッセージを確認します-

Ember.js依存性注入

次に、_schedule Tasks_ボタンをクリックして、優先順位で処理されるキューでの作業をスケジュールします-

Ember.js依存性注入