是否有内置的方法可以阻止$broadcast
事件进入范围链?
$broadcast
事件传递的事件对象没有stopPropagation
方法(docs on $rootScope提及。)但是this merged pull request建议$broadcast
个事件可以stopPropagation
打电话给他们。
答案 0 :(得分:43)
angularJS 1.1.2源代码片段:
$emit: function(name, args) {
// ....
event = {
name: name,
targetScope: scope,
stopPropagation: function() {
stopPropagation = true;
},
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
// ....
}
$broadcast: function(name, args) {
// ...
event = {
name: name,
targetScope: target,
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
// ...
}
正如您所看到的,$ broadcast中的事件对象没有“stopPropagation”。
您可以使用preventDefault将事件标记为“不需要处理此事件”,而不是stopPropagation。这不会停止事件传播,但这会告诉孩子范围:“不需要处理此事件”
答案 1 :(得分:7)
由于broadcast没有stopPropagation方法,你需要使用defaultPrevented属性,这在递归指令中是有意义的。
$scope.$on('test', function(event) {
if (!event.defaultPrevented) {
event.defaultPrevented = true;
console.log('Handle event here for the root node only.');
}
});
答案 2 :(得分:1)
我为此目的实施了一个事件小偷:
.factory("stealEvent", [function () {
/**
* If event is already "default prevented", noop.
* If event isn't "default prevented", executes callback.
* If callback returns a truthy value or undefined,
* stops event propagation if possible, and flags event as "default prevented".
*/
return function (callback) {
return function (event) {
if (!event.defaultPrevented) {
var stopEvent = callback.apply(null, arguments);
if (typeof stopEvent === "undefined" || stopEvent) {
event.stopPropagation && event.stopPropagation();
event.preventDefault();
}
}
};
};
}]);
使用:
$scope.$on("AnyEvent", stealEvent(function (event, anyOtherParameter) {
if ($scope.keepEvent) {
// do some stuff with anyOtherParameter
return true; // steal event
} else {
return false; // let event available for other listeners
}
}));
$scope.$on("AnyOtherEvent", stealEvent(function (event, anyOtherParameter) {
// do some stuff with anyOtherParameter, event stolen by default
}));