zoukankan      html  css  js  c++  java
  • [Firebase] 2. Firebase Event Handling

    /**
     * Created by Answer1215 on 11/9/2014.
     */
    
    var app = angular.module('app', ['firebase']);
    
    app.constant('FIREBASE_URI', 'https://zhentiw-angular-fire.firebaseio.com/');
    
    app.controller('MainCtrl', ['$scope', 'ItemsService', function ($scope, ItemsService) {
        $scope.newItem = { name: '', description: '', count: 0 };
        $scope.currentItem = null;
        $scope.isUpdated = false;
    
        $scope.items = ItemsService.getItems();
    
        $scope.items.$on('change', function(){
            if(!$scope.isUpdated){return;}
            console.log("ITEMS CHANGE");
        });
    
        $scope.items.$on('loaded', function(){
            console.log("ITEMS LOADED");
        });
    
        //Deattach the change event from the items
        //$scope.items.$off('change');
    
    
        $scope.addItem = function () {
            ItemsService.addItem(angular.copy($scope.newItem));
            $scope.newItem = { name: '', description: '', count: 0 };
        };
    
        $scope.updateItem = function (id){
            $scope.isUpdated = true;
            ItemsService.updateItem(id);
        };
    
        $scope.removeItem = function (id) {
            ItemsService.removeItem(id);
        };
    }]);
    
    app.factory('ItemsService', ['$firebase', 'FIREBASE_URI', function ($firebase, FIREBASE_URI) {
        var ref = new Firebase(FIREBASE_URI);
        var items = $firebase(ref);
    
        var getItems = function () {
            return items;
        };
    
        var addItem = function (item) {
            items.$add(item);
        };
    
        var updateItem = function (id) {
            items.$save(id);
        };
    
        var removeItem = function (id) {
            items.$remove(id);
        };
    
        return {
            getItems: getItems,
            addItem: addItem,
            updateItem: updateItem,
            removeItem: removeItem
        }
    }]);

    You can lisisten to the 'loaded', 'chane' events by using

      $on('loaded', function(){...}).

    You can deattache the events by using 

      $off()  //unattach all events

      $off('loaded') //unattach only loaded event

  • 相关阅读:
    题解 CF171G 【Mysterious numbers
    题解 P1157 【组合的输出】
    题解 P3955 【图书管理员】
    题解 P2036 【Perket】
    题解 CF837A 【Text Volume】
    题解 CF791A 【Bear and Big Brother】
    题解 CF747A 【Display Size】
    题解 P1332 【血色先锋队】
    题解 P2660 【zzc 种田】
    题解 P4470 【[BJWC2018]售票】
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4088164.html
Copyright © 2011-2022 走看看