如何找到更改的对象被监视的调用点 [英] How to find the call site that changed an object being watched

查看:95
本文介绍了如何找到更改的对象被监视的调用点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AngularJS允许侦听的对象的变化和将调用供给到$手表功能的提供的回调函数。使用像ngGrid对象AngularJS一个相当大的库频繁改变能够看。

AngularJS allows listening for changes of an object and will call the supplied callback function supplied to the $watch function. With a largish library using AngularJS like ngGrid objects are frequently changed that's being "watched".

在手表调用回调函数,怎么能追溯引起变化的对象调用的网站?

Once the watch callback is invoked, how can one trace back the call site that caused the change to the object?

如果不知道是什么原因导致的变化,并因此造成要调用的手表的处理程序,它被证明是非常困难的调试像ngGrid库。我设置断点到处我可以预见的变量可以改变,然后再尝试建立的执行管线的图形走这导致一个对象被修改的事件链。

Without knowing what caused the change, and so caused the watch handler to be invoked, it is proving very difficult to debug a library like ngGrid. I'm setting breakpoints everywhere I can foresee the variable could be changed, and then trying to build a graph for the execution pipeline to follow the chain of events that lead to an object being changed.

推荐答案

您根本无法做到这一点。 $观看将只需添加一个回调来检查对象是否改变,消化过程中运行。

You simply can't do that. $watch will just add a callback to check whether the object changed, to be run during digests.

我想这是与框架,如骨干,你延长模式对象的主要区别之一。

I guess that's one of the main differences with frameworks like Backbone where you extend a Model object.

话虽这么说,你的可能的有更好的运气试图 $范围$摘要(); 有意(更新模型,射击守望),但它是一个延伸...

That being said, you might have better luck trying to $scope.$digest(); intentionally (updating the model, and firing the watchers), but it's a stretch...

问题是你想有手表和模型的变化之间的相关性,但我们确实没有。添加一个手表只是增加了一些消化循环运行时进行检查。

The problem is you're thinking there's a correlation between watches and model changes, but there simply isn't. Adding a watch just adds something to be checked when the digest loop runs.

此循环不是通过在 $范围,变化的东西引发的,而是调用 $范围。$适用,或直接调用 $范围。$摘要

This loop isn't triggered by changes to something on a $scope, but rather calls to $scope.$apply, or directly calling $scope.$digest.

请注意,大多数的(所有?)角的指令的和相关的组件调用 $范围。$适用以您的名义。例如,之所以 $超时 ngClick 如预期的工作,是因为它们运行 $范围。$适用执行您的回调后,在内部。

Note that most (all?) of Angular's directives and related components call $scope.$apply on your behalf. For example, the reason why $timeout and ngClick work as expected, is because they run $scope.$apply internally after executing your callbacks.

如果你在寻找调用点仅仅是兴趣,能像这样帮你吗?

If you're merely interested in finding the call site, could something like this help you?

$scope.foo = {
  get bar () { return getting(); },
  set bar (value) { setting(value); }
};

var bar;

function setting (value) {
  var stack = getStack();
  console.log(value, stack);
  bar = value;
}

function getting () {
  console.log(getStack());
}

function getStack () {
  try {
    throw new Error('foo');
  } catch (e) {
    return e.stack || e;
  }
}

这篇关于如何找到更改的对象被监视的调用点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆