EmberJS - 依賴注入



它是一個將一個物件的依賴項提供給另一個物件的過程,並被 Ember 應用程式用於宣告和例項化物件以及它們之間的依賴類。Ember.ApplicationEmber.ApplicationInstance 類在 Ember 的依賴注入實現中發揮著重要作用。

Ember.Application 類宣告和配置物件,並用作依賴項宣告的“登錄檔”,而 Ember.ApplicationInstance 類充當例項化物件的“所有者”。但是,Ember.Application 類充當應用程式的主要登錄檔,每個 Ember.ApplicationInstance 類都充當登錄檔。

工廠註冊

工廠指定應用程式的一部分,例如路由、模板等,並使用特定鍵進行註冊。例如,索引模板使用 template:index 定義,應用程式路由使用 route:application 定義。

註冊鍵包括兩部分;一個是工廠型別,第二個是工廠的名稱,這兩個部分用冒號(:)分隔。例如,您可以透過使用 logger:main 鍵註冊 Logger 工廠來初始化應用程式。

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 應用程式中使用工廠註冊、注入和例項查詢。建立一個名為 dependency-inject 的元件,它將在 app/components/ 下定義。開啟 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

開啟 init.js 檔案(位於 app/initializers/ 下)並新增以下程式碼:

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

現在開啟 message.js 服務檔案(位於 app/services/ 下)並使用以下程式碼:

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 Tutorialspoint!!!";
   }
});

接下來,建立一個初始化程式,在應用程式啟動時配置應用程式。可以使用以下命令建立初始化程式:

ember generate initializer logger

開啟 logger.js 初始化程式檔案(位於 app/initializers/ 下)並使用以下程式碼:

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

開啟 logger.js 初始化程式檔案(位於 app/instance-initializers/ 下)並使用以下程式碼:

//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 Dependency Injection

接下來,單擊“單擊此處”按鈕,它將顯示服務頁面上的文字,如下面的螢幕截圖所示:

Ember.js Dependency Injection

現在轉到控制檯並檢查從例項初始化程式中顯示的日誌訊息,如上圖所示,文字顯示後:

Ember.js Dependency Injection

接下來,單擊“計劃任務”按鈕以安排按優先順序順序處理的佇列上的工作:

Ember.js Dependency Injection
emberjs_application_concerns.htm
廣告

© . All rights reserved.