FireBase 提供实时数据云服务 Doc
直接上示例:
(下面示例使用的firebase结构)
直接使用firebase库
> npm install firebase --save
//或前端使用,直接从CDN获取
<script src="https://cdn.firebase.com/js/client/2.4.0/firebase.js"></script>
var Firebase=require("firebase");
var DB_URL="https://<YOUR-FIREBASE-APP>.firebaseio.com/";
var Fb=new Firebase(DB_URL);
/*
设置数据,可参考:https://www.firebase.com/docs/web/guide/saving-data.html
set(),update(),push(),transaction( )
push() function that generates a unique ID, or key, for each new child
*/
//username is key
Fb.child("users").child(username).set({username:xxx,password:xxx});
Fb.child("users").child(username).update({password:xxx});
//generate a uniqueID as key
var usersRef=Fb.child("users").push();
var id=usersRef.key();
//uniqueID is key
usersRef.push({username:xxx,password:xxx});
usersRef.push().set({username:xxxx,password:xxx});
/*
获取数据,可参考https://www.firebase.com/docs/web/guide/retrieving-data.html
Get: (callback to read the data)
on('value',function(snapshot){xxxx})
once('value',function(snapshot){xxxx})
Query:
orderByChild("xxx"),orderByKey(),orderByValue(),orderByPriority()
limitToLast(count),limitToFirst(count)
startAt(xxx),endAt(xxx),equalTo(xxx)
*/
Fb.child("users").child(username).once('value',function(snapshot){
console.log(snapshot.key());
console.log(snapshot.val());
if(snapshot.exists())
console.log(snapshot.child("password").val());
});
通过reactFire使用firebase (在React中)
var ReactFire=require("reactfire");
var Firebase=require("firebase");
// Component中:
mixins:[ReactFire],
getInitialState:function(){
return {
showForm:false,
newQuestion:null,
questions:[]
}
},
componentWillMount:function(){
console.log("Question Will Mount...");
this.fb=new Firebase(rootUrl+"questions/");
this.bindAsArray(this.fb,"questions"); // => this.state.questions(当有变化时自动转换为数组,且调用this.setState({questions:xxx}); )
this.fb.on("value",this.loadDataHandler);
},
loadDataHandler:function(){
console.log("Data Loaded");
},
addNewQuestion:function(newQuestion){
//this.firebaseRefs.questions.push(newQuestion);
this.fb.push(newQuestion);
this.setState({newQuestion:newQuestion});
},
voteUpdate:function(questionId,voteCount){
this.fb.child(questionId).update({voteCount:voteCount});
},
removeItem:function(question){
this.fb.child(question[".key"]).remove();
}