关于Swift观察者的Firebase文档要么有点过时,要么对我来说不太清楚。我仍然不明白什么时候完全删除观察者。在observeSingleEvent的情况下怎么样?另外,删除这些观察者的正确方法在哪里?
答案 0 :(得分:2)
Firebase's documentation没有指明这一点,但它似乎含蓄,所以我不会删除它:
一次读取数据
在某些情况下,您可能希望调用一次回调,然后立即将其删除,例如在初始化您不希望更改的UI元素时。您可以使用observeSingleEventOfType方法来简化此方案:事件回调添加触发器一次,然后不再触发。
要删除观察者,请先将其附加到句柄,然后使用该句柄作为参考:
// Add observer
let handle = ref.observeSingleEvent(of: .value, with: { value in
// ...
})
// Then remove it
ref.removeObserver(withHandle: handle);
// Or just remove all of them
ref.removeAllObservers()
答案 1 :(得分:0)
这是一次读取数据的示例:
/*global window, document, alert, Vector, Moth, Matrix, Plane, SceneGraphNode*/
function onLoad() {
var mainCanvas, mainContext, planePosition, plane;
// this function will initialise our variables
function initialiseCanvasContext() {
// Find the canvas element using its id attribute.
mainCanvas = document.getElementById('mainCanvas');
// if it couldn't be found
if (!mainCanvas) {
// make a message box pop up with the error.
alert('Error: I cannot find the canvas element!');
return;
}
// Get the 2D canvas context.
mainContext = mainCanvas.getContext('2d');
if (!mainContext) {
alert('Error: failed to get context!');
return;
}
planePosition = new Vector(0, 0, 0);
plane = new Plane(planePosition);
}
function translate(pPosition) {
var matrix = Matrix.createTranslation(pPosition);
matrix.transform(mainContext);
}
function scale(pPosition) {
var matrix = Matrix.createScale(pPosition);
matrix.transform(mainContext);
}
function rotate(pPosition) {
var matrix = Matrix.createRotation(pPosition);
matrix.transform(mainContext);
}
function drawPlane() {
scaleVector = new Vector(0.25, 0.25, 0);
scale(scaleVector);
translate(new Vector(0, 0));
rotate(0);
plane.draw(mainContext);
}
function drawMoth() {
var moth, mothPosition;
mothPosition = new Vector(mainCanvas.width / 2, mainCanvas.height / 2, 0);
moth = new Moth(mothPosition);
moth.draw(mainContext);
}
function drawPlane() {
plane = new Plane(planePosition);
scale(new Vector(0.25, 0.25, 0));
plane.draw(mainContext);
}
function animatePlane() {
translate(planePosition.add(new Vector(100, 100, 0)));
drawPlane();
window.requestAnimationFrame(animatePlane);
}
initialiseCanvasContext();
drawMoth();
animatePlane();
}
window.addEventListener('load', onLoad, false);
回答您的具体问题: 删除观察者应该不是问题,因为观察者只观察一次,你基本上只是确认观察者已经消失了。