5

我将 Firebase (AngularFire) 与他们的 PHP API 一起使用,并且正在构建在线状态系统。 https://www.firebase.com/docs/managing-presence.html

我开始得到很多参考资料,这感觉不对。

firebase refs 应该存储在 vanilla vars 还是对象中?

controllers.controller('SocialCtrl', function($scope, angularFire) {
    var onlineRef = new Firebase($scope.main.firebaseUrl + "/users/" + $scope.main.userId + "/online");
    $scope.online = {};
    angularFire(onlineRef, $scope, "online");

    var usersRef = new Firebase($scope.main.firebaseUrl + "/users");
    $scope.users = {};
    angularFire(usersRef, $scope, "users");

    var productRef = new Firebase($scope.main.firebaseUrl + "/products/" + $scope.main.serieId);
    $scope.product = {};
    angularFire(productRef, $scope, "product");

    var connectedRef = new Firebase($scope.main.firebaseUrl + "/.info/connected");
    connectedRef.on("value", function(snap) {
        if (snap.val() === true) {
            onlineRef.onDisconnect().set(Firebase.ServerValue.TIMESTAMP);
            onlineRef.set(true);
        }
    });
});

或者

$scope.fire = {
    refs: {
        online: new Firebase($scope.main.firebaseUrl + "/users/" + $scope.main.userId + "/online"),
        users: new Firebase($scope.main.firebaseUrl + "/users"),
        product: new Firebase($scope.main.firebaseUrl + "/products/" + $scope.main.serieId),
        connected: new Firebase($scope.main.firebaseUrl + "/.info/connected")
    }
};

angularFire($scope.fire.refs.online, $scope, "fire.online");
angularFire($scope.fire.refs.users, $scope, "fire.users");
angularFire($scope.fire.refs.product, $scope, "fire.product");
angularFire($scope.fire.refs.connected, $scope, "fire.connected");

$scope.fire.refs.connected.on("value", function(snap) {
    if (snap.val() === true) {
        $scope.fire.refs.online.onDisconnect().set(Firebase.ServerValue.TIMESTAMP);
        $scope.fire.refs.online.set(true);
    }
});

我并不是要将此作为最佳实践问题。Firebase 太新了,我不想破坏任何我可能还不知道的东西。

4

1 回答 1

9

创建多个 Firebase 引用或 angularFire 对象绝对没有问题(事实上,这是鼓励的)。您可以使用该child函数稍微清理一下代码:

angular.module("myapp", ["firebase"]).
value("URL", "https://my-firebase.firebaseio.com/").
controller("SocialCtrl", function($scope, URL, angularFire) {
  var ref = new Firebase(URL);
  angularFire(ref.child("users"), $scope, "users");
  angularFire(ref.child("users/" + $scope.main.userId + "/online", $scope, "online");
  angularFire(ref.child("products/" + $scope.main.serieId, $scope, "products");
  ref.child(".info/connected").on("value", ...);
}
于 2013-09-07T19:41:02.210 回答