问题描述
我想弄清楚如何为 Angularjs <= 1.2 创建我自己的一次性绑定".我找到了这个 answer,描述了如何创建自己的 bindOnce 指令.在使用以下指令时,我确实看到了这一点:
I am trying to figure out how to create my own "one time binding", for Angularjs <= 1.2.I found this answer, describing how to create your own bindOnce directive. I do see that when using the following directive:
app.directive('bindOnce', function() {
return {
scope: true,
link: function( $scope ) {
setTimeout(function() {
$scope.$destroy();
}, 0);
}
}
});
数据绑定一次.但是,我可以看到 $$watchers 仍在运行.看看下面的JSBin - 运行评论的观察者控制台上的计数代码将显示观察者还活着.
Data is binded once. But, I can see that the $$watchers is still on. Take a look at the following JSBin - running the commented watcher count code on the console will reveal that the watchers are still alive.
EDIT:由于某种原因,当使用与 angular 1.3 相同的指令时,观察者计数 dod 变为 0!!!
EDIT: for some reason, when using the same directive with angular 1.3, the watcher count dod changed to be 0!!!
推荐答案
使用 cleanup
函数移除观察者:
Use the cleanup
function to remove watchers:
function cleanup(element)
{
element.off().removeData();
var injector = currentSpec.$injector;
element.$injector = null;
// clean up jquery's fragment cache
angular.forEach(angular.element.fragments, function(val, key) {
delete angular.element.fragments[key];
});
angular.forEach(angular.callbacks, function(val, key)
{
delete angular.callbacks[key];
});
angular.callbacks.counter = 0;
}
使用自毁服务作为一次简单的绑定:
Use a self-destructing service as a simple bind once:
function onetime()
{
/*...*/
onetime = Function;
}
angular.module('myApp').constant('bindonce', onetime);
angular.module('myApp').controller('foo', function($bindonce){
this.$inject = '$bindonce';
$scope.mybind = $bindonce();
}
使用迁移指南作为参考以查找重大更改:
Use the migration guide for reference to find breaking changes:
参考资料
这篇关于Angularjs - $scope.$destroy 不会删除观察者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!