问题来源
最近在学习Cesium,在学习动态编辑点线面,网上查找学习资料时有幸看到了这篇文章使用Cesium动态绘制点、线、面、圆、矩形
阅读这篇文章收获不少,但是有一处疑问文中没有解释
//鼠标左键
handler.setInputAction(function (event) {
// We use `viewer.scene.pickPosition` here instead of `viewer.camera.pickEllipsoid` so that
// we get the correct point when mousing over terrain.
var earthPosition = viewer.scene.pickPosition(event.position);
// `earthPosition` will be undefined if our mouse is not over the globe.
if (Cesium.defined(earthPosition)) {
if (activeShapePoints.length === 0) {
floatingPoint = createPoint(earthPosition);
activeShapePoints.push(earthPosition);
var dynamicPositions = new Cesium.CallbackProperty(function () {
if (drawingMode === 'polygon') {
return new Cesium.PolygonHierarchy(activeShapePoints);
}
return activeShapePoints;
}, false);
activeShape = drawShape(dynamicPositions);//绘制动态图
}
activeShapePoints.push(earthPosition);
createPoint(earthPosition);
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
该处功能中有一处,
if (activeShapePoints.length === 0)
该处仅当activeShapePoints.length=0时才执行,整个绘图函数
activeShape = drawShape(dynamicPositions);//绘制动态图
仅在该条件判断体中执行,而此后的绘制过程中显然不断有点加入,显然activeShapePoints.length!=0,条件不成立,为何整个绘图功能仍能正确执行呢?
这就是我当时的疑惑。这个问题有网友也指出了,但是作者并未回复。
猜想与实验
我暂时还未找到相关解释,但是我有个猜想:CallbackProperty函数一经执行便不断进行自我调用对需要监测的属性进行监测,若被监测属性发生改变,整个程序中有关于该属性的相关代码就会被执行进行更新。
于是简单做了个实验进行印证。
对该处代码稍作更改,如下:
//鼠标左键
var dynamicPositions;
let i=0;
handler.setInputAction(function (event) {
// We use `viewer.scene.pickPosition` here instead of `viewer.camera.pickEllipsoid` so that
// we get the correct point when mousing over terrain.
// scene.pickPosition只有在开启地形深度检测,且不使用默认地形时是准确的。
var earthPosition = viewer.scene.pickPosition(event.position);
// `earthPosition` will be undefined if our mouse is not over the globe.
if (Cesium.defined(earthPosition)) {
if (activeShapePoints.length === 0) {
i++;
console.log(i+'次调用');
floatingPoint = createPoint(earthPosition);
activeShapePoints.push(earthPosition);
dynamicPositions = new Cesium.CallbackProperty(function () {
if (drawingMode === 'polygon') {
return new Cesium.PolygonHierarchy(activeShapePoints);
}
console.log(i+"***********************");
console.log(activeShapePoints.length+activeShapePoints);
return activeShapePoints;
}, false);
// activeShape = drawShape(dynamicPositions); //绘制动态图
}
// console.log(activeShapePoints.length+activeShapePoints);
activeShape = drawShape(dynamicPositions); //绘制动态图
activeShapePoints.push(earthPosition);
createPoint(earthPosition);
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
画了一个Z,结果如下:
可以看到,该条件体确实只调用了一次,但是有关于监测的 activeShapePoints的相关函数和变量都不断执行了相关语句。我将绘图函数放到条件判断体之外,仍能正常绘图。因此该猜想在一定程度上得到了印证。
结论
因此,为了便于理解,不严谨地得到一个结论:
CallbackProperty函数一经执行便不断进行自我调用对需要监测的属性进行监测,若被监测属性发生改变,整个程序中有关于该属性的相关代码就会被执行进行更新。
这类似于Vue中的监视属性。