簡體   English   中英

將事件偵聽器停止在“ $ destroy”上。 TypeError:$ on不是函數;

[英]Stop event listeners on '$destroy'. TypeError: $on is not a function;

我試圖在范圍被破壞的同時停止所有事件監聽器。

我收到此錯誤:

TypeError: vm.$on is not a function; 

vm.on(..)都不起作用

    angular.module('app.layout')
      .controller('DashboardController', DashboardController);

      DashboardController.$inject = ['$interval','dataservice'];


      function DashboardController($interval, dataservice) {
        var vm = this;
        vm.name = "DashboardController";


        console.log('Init Dashboard Controller');
        initEvents();
/*
 ...
*/

    /////////////////////////////

    function initEvents() {
          vm.$on('$destroy', function() {
            vm.stop();
            console.log('DashboardController scope destroyed.');
          })
        }

問題是vm沒有聲明$on(... ,您必須使用$scope 。將其插入控制器並像$scope.$on一樣聲明。

當使用controllerAs語法時,這常常被人誤解為根本不應該使用$scope 但是,建議您避免在某些活動中使用$scope而不從控制器中取消它。 范圍將始終存在,它是控制器的內部組件,只是不要像視圖模型那樣使用它,但是無論如何,您都可以使用它來執行諸如偵聽事件,廣播,發送等任務。

嘗試類似的事情(在對依賴項注入$scope之后):

$scope.$on('$destroy', function() {
    vm.stop();
    console.log('DashboardController scope destroyed.');
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM