gpt4 book ai didi

javascript - 通过服务广播功能会多次触发该功能,而不是一次

转载 作者:行者123 更新时间:2023-11-28 08:42:37 27 4
gpt4 key购买 nike

我创建了一个共享确认模式方法的服务,并允许在 Controller 之间广播方法。

services.SharedService = function($rootScope, $modal) {

var sharedService = {
controller : '',
method : '',
args : []
};

sharedService.prepare = function(controller, method){
this.controller = controller;
this.method = method;
this.broadCast();
};

sharedService.broadCast = function(){
$rootScope.$broadcast('menuBroadcast');
};



return sharedService;

});

然后我有三个 Controller :

controllers.ctrl1 = function($scope, $rootScope, SharedService) {


$rootScope.$on('menuBroadcast', function() {
if (SharedService.controller == 'ctrl1') {
$scope[SharedService.method]();
}
});
$scope.delete = function(){
var c = window.confirm("Are you sure you want to delete it?");
if(c === true){
//delete
}
};
};

controllers.ctrl2 = function($scope, $rootScope, SharedService) {

$rootScope.$on('menuBroadcast', function() {
if (SharedService.controller == 'ctrl1') {
$scope[SharedService.method]();
}
});

$scope.delete = function(){
var c = window.confirm("Are you sure you want to delete it?");
if(c === true){
//delete
}
};
};
};

controllers.menu = function($scope, SharedService) {
$scope.delete1 = function() {
console.debug("Calling delete 1");
SharedService.prepare('ctrl1', 'delete');
};
$scope.delete2 = function() {
console.debug("Calling delete 2");
SharedService.prepare('ctrl2', 'delete');
};
}

第一次从 ctrl1 打开确认时,单击“确定”按钮按预期工作。我可以多次打开此模式,它会起作用。

然后,切换到 ctrl2,我打开确认,我必须单击两次确定按钮才能关闭确认框。

控制台调试显示“调用delete1”和“调用delete2”仅触发一次。但是 on("menuBroadcast") 中的 console.debug 有时会被触发最多 3 次。知道为什么服务会多次触发该事件吗?注入(inject)时,是否实例化多次?

最佳答案

重复

How can I unregister a broadcast event to rootscope in AngularJS?

Controller 被实例化多次。当调用 $destroy 时,我必须取消注册 $rootScope.$on 监听器。

var cleanUpFunc = $rootScope.$on('menuBroadcast', function {
if (SharedService.controller == 'ctrl1') {
$scope[SharedService.method]();
}
});

$scope.$on('$destroy', function() {
cleanUpFunc();
});

关于javascript - 通过服务广播功能会多次触发该功能,而不是一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20318838/

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