tns plugin add nativescript-plugin-firebase
"nativescript-plugin-firebase": "^1.2.0"
module.exports = { apiUrl: "https://incandescent-fire-8397.firebaseio.com/" };
viewModel.init = function(){ firebase.init({ url: config.apiUrl }).then( function (instance) { console.log("firebase.init done"); }, function (error) { console.log("firebase.init error: " + error); } ); };
var fetchModule = require("fetch");
var firebase = require("nativescript-plugin-firebase");
login()
register()
app/shared/view-models/user-view-model.js
viewModel.login = function() { return firebase.login({ type: firebase.loginType.PASSWORD, email: viewModel.get("email"), password: viewModel.get("password") }).then( function (response) { config.uid = response.uid return response; }); }; viewModel.register = function() { return firebase.createUser({ email: viewModel.get("email"), password: viewModel.get("password") }).then( function (response) { console.log(response); return response; } ); };
handleErrors()
app/views/register/register.js
exports.register = function() { user.register() .then(function() { dialogsModule .alert("Your account was successfully created.") .then(function() { frameModule.topmost().navigate("views/login/login"); }); }).catch(function(error) { dialogsModule.alert({ message: error, okButtonText: "OK" }); }); }
load()
app/shared/view-models/grocery-list-view-model.js
//to get the index of an item to be deleted and handle the deletion on the frontend function indexOf(item) { var match = -1; this.forEach(function(loopItem, index) { if (loopItem.id === item.key) { match = index; } }); return match; } function GroceryListViewModel(items) { var viewModel = new observableArrayModule.ObservableArray(items); viewModel.indexOf = indexOf; viewModel.load = function() { var onChildEvent = function(result) { var matches = []; if (result.type === "ChildAdded") { if (result.value.UID === config.uid) { viewModel.push({ name: result.value.Name, id: result.key }); } } else if (result.type === "ChildRemoved") { matches.push(result); matches.forEach(function(match) { var index = viewModel.indexOf(match); viewModel.splice(index, 1); }); } }; return firebase.addChildEventListener(onChildEvent, "/Groceries").then( function() { console.log("firebase.addChildEventListener added"); }, function(error) { console.log("firebase.addChildEventListener error: " + error); } ) };
/Groceries
UID
add()
viewModel.add = function(grocery) { return firebase.push( '/Groceries', { 'Name': grocery, 'UID': config.uid }); };
delete()
viewModel.delete = function(index) { var id = viewModel.getItem(index).id; return firebase.remove("/Groceries/"+id+""); };