How to correctly disassociate $firebase AngularJS binding?

牧云@^-^@ 提交于 2019-12-12 10:15:43

问题


Let the image do the talking: http://www.youtube.com/watch?v=4jgdj8LBQRs [25 sec]

Plunker: http://plnkr.co/edit/pL3z77vmYeSZzGMSL0YV?p=preview

Firebase GUI: http://syncing.firebase-demo.io/

I'm using angular 1.2.6 (fairly recent) and AngularFire 0.6 (latest).

Steps to reproduce

  • I have a list of todos that is syncing with Firebase
  • I log in and local changes are propagated to Firebase
  • I log out and I disassociate binding, clearing local scope
  • I log in again: strange things happen (see video)

Critical fragments of code below (plunker has it all)

1. Controller

    $rootScope.$watch("loginState", function() {
        $scope.loginState = $rootScope.loginState;
        if ($scope.loginState == "loggedIn") {
            $scope.$firRef = $firebase(new Firebase($scope.firebaseURL + "testuser/todos/"));
            $scope.$firRef.$bind($scope, "todos").then(function(unbind) {
              $scope.unbindFunction = unbind; // I store reference to unbinding function
            });
        } else if ($scope.loginState == "loggedOut") {
            $scope.unbindFunction(); // and call it on logout
            $scope.$firRef = null // doesn't help either
            $scope.todos = [];
        }
    });

    $scope.login = function() {
        loginService.login();
    }        

    $scope.logout = function() {
        loginService.logout();
    }

(note that I store reference to unbind function and call it on logout)

2. Service

app.factory('loginService', ['$rootScope', function($rootScope) {
    return {
        login: function() {
            $rootScope.loginState = "loggedIn";
        },
        logout: function() {
            $rootScope.loginState = "loggedOut";
        }
    }
}]);

Docs about 3-way data binding: https://www.firebase.com/docs/angular/reference.html#bind-scope-model

Related:

  • How to disassociate angularFire bound object?
  • Prevent items in scope from writing to a different user's records

I would be very keen to know how to properly synchronise collections between logging-in and logging-out.

来源:https://stackoverflow.com/questions/21963735/how-to-correctly-disassociate-firebase-angularjs-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!