2013-03-14 4 views
12

라고 말하면 person은 복수 cars을 가질 수 있으며 car은 복수 accidents을 가질 수 있습니다. 그래서 우리는 할 수 :Firebase에서 빈 배열을 처리하는 방법은 무엇입니까?

# Person with no cars 
person: 
    name: "Misha" 
    cars: [] 

# Person with free-accident car 
person: 
    name "Arlen" 
    cars: 
    0: 
     name: "Toyota" 
     accidents: [] 

중포 기지 매장이 사람들로 :

person: 
    name: "Misha" 

person: 
    name "Arlen" 
    cars: 
    0: 
     name: "Toyota" 

그래서 자바 스크립트에서 나는 빈 배열을 복원하려면 다음을 수행해야한다 : (커피 스크립트를)

if person.cars? 
    for car in person.cars 
    car.accidents = [] unless car.accidents? 
else 
    person.cars = [] 

이 불필요한 JavaScript 코드를 작성하지 않고 Firebase의 빈 배열을 처리하는 더 좋은 방법이 있습니까?

답변

13

필자가 핵심 질문을 이해한다면 짧은 대답은 Firebase에 빈 배열을 강제 적용 할 방법이 없다는 것입니다. 그러나 위에있는 것보다 더 잘 작동 할 수있는 패러다임이 있습니다.

Firebase는 실시간 환경입니다. 자동차 및 사고의 수는 언제든지 바뀔 수 있습니다. 모든 것을 실시간으로 도착하는 새로운 데이터로 취급하고 존재에 대해 생각조차 없게하거나 존재하지 않는 것이 가장 좋습니다.

// fetch all the people in real-time 
rootRef.child('people').on('child_added', function(personSnapshot) { 

    // monitor their cars 
    personSnapshot.ref().child('cars', 'child_added', function(carSnapshot) { 

     // monitor accidents 
     carSnapshot.ref().child('accidents', 'child_added', function(accidentSnapshot) { 
      // here is where you invoke your code related to accidents 
     }); 
    }); 
}); 

if exists/unless 유형 논리가 필요하지 않습니다. child_removedcarspeople으로 모니터링하고 ref.off()으로 전화하여 특정 자녀의 청취를 중단하고 싶을 수도 있습니다.

어떤 이유로 정적 모델을 고수 할 경우, forEach 친구 될 것입니다 : 심지어 대해 forEach에 대한 필요가 "존재하거나하지 않는 한"일종의없는 방법

// fetch all the people as one object, asynchronously 
// this won't work well with many thousands of records 
rootRef.child('people').once('value', function(everyoneSnap) { 

    // get each user (this is synchronous!) 
    everyoneSnap.forEach(function(personSnap) { 

     // get all cars (this is asynchronous) 
     personSnap.ref().child('cars').once('value', function(allCars) { 

      // iterate cars (this is synchronous) 
      allCars.forEach(function(carSnap) { /* and so on */ }); 

     }); 

    }); 
}); 

주 논리. 그렇지 않은 빈의 경우

+0

멋진 대답 카토처럼 볼 수 DataSnapshot 기능 NUMCHILDREN()를 사용! –

4

나는 보통이

var fire = new Firebase("https://example.firebaseio.com/"); 
fire.once('value', function(data){if (data.numChildren() > 0){ /*Do something*/ }); 
관련 문제