gpt4 book ai didi

javascript - 当 $firebaseArray 或 $firebaseObject 返回空时确保 $watch 的绑定(bind)

转载 作者:行者123 更新时间:2023-11-28 06:56:09 25 4
gpt4 key购买 nike

我正在使用 Angularfire,并且存在一种情况:$firebaseArray$firebaseObject 首先什么也不返回。这是因为它是空的或者还不存在。但我想一直对那个对象/数组进行 $watch 。稍后再说,该节点确实存在。原来的 $firebaseArray$firebaseObject 不会触发 $watch 事件。

即使节点为空/最初不存在,如何确保 $watch 的绑定(bind)发生?当我创建一个新用户并且某个节点中没有任何内容时,就会发生这种情况。

更新1

http://plnkr.co/edit/tQur74nkRIE9ZOiJUAgf?p=preview

JS

var app = angular.module('plunker', ['firebase']);
var Ref = new Firebase('https://so32556276.firebaseio.com');

app.controller('MainCtrl', function($scope, $firebaseObject) {
$scope.data = $firebaseObject(Ref.child('user'));

$scope.data.$loaded().then(function(res) {
$scope.data.$watch(function(e) {
console.log('Something changed');
console.log(e);
});
});

$scope.changeName = function() {
$scope.data.name = "test2";
$scope.data.$save();
}

$scope.changeAge = function() {
$scope.data.age = "10";
}
});

HTML

  <body ng-controller="MainCtrl">
<p>Hello {{data.name}}!</p>
<p>Your age is {{data.age}}!</p>
<a href="" ng-click="changeName()">Change Name</a><br>
<a href="" ng-click="changeAge()">Change Age</a>
</body>

Firebase

enter image description here

如果我点击“更改名称”,您可以在此处看到日志事件:

Something changed
app.js:10 Object {event: "value", key: "user"}

如果我点击“更改年龄”,尽管前端可以检测到该变量,但 $watch 对此不可见。控制台中没有任何内容。

有什么线索可以避免这种情况吗?

最佳答案

在大多数情况下,我看到人们尝试使用 $loaded(),他们仍然陷入“首先加载数据,然后执行...”的心态。 Firebase(以及 AngularFire)是一个“同步这些数据,并且每当它发生变化时......”系统。您使用 $watch() 绝对是正确的方法,您只是在错误的时刻附加了它。

app.controller('MainCtrl', function($scope, $firebaseObject) {
$scope.data = $firebaseObject(Ref.child('user'));

$scope.data.$loaded().then(function(res) {
$scope.data.$watch(function(e) {
console.log('Something changed');
console.log(e);
});
});

从 Firebase 加载初始数据后,$loaded() promise 即得到履行;或者一个 Firebase 已确定尚无数据。您只需在加载初始数据之后注册 $watch() 处理程序,因此它只会在之后发生更改时触发。

解决方案是立即将 $watch() 处理程序附加到 $firebaseObject:

app.controller('MainCtrl', function($scope, $firebaseObject) {
$scope.data = $firebaseObject(Ref.child('user'));
$scope.data.$watch(function(e) {
console.log('Something changed');
console.log(e);
});

关于javascript - 当 $firebaseArray 或 $firebaseObject 返回空时确保 $watch 的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32556276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com