vendredi 4 août 2017

Javascript function that checks textbox and other functions.... always returns False

The main function where the problem resides... the IF condition is never TRUE

FriendlyChat.prototype.issueParts = function() {
  if(this.engineerText.value && this.checkSignedIn() && this.checkEngTrue()) {
    var inputs = document.getElementsByClassName( 'part-no' );
    var names = [].map.call(inputs, function(input){
      if(input.value != ""){
        firebase.database().ref('PartInfo/CurrentPart/' + $('engineer-text').value).push({
            partNo: input.value,
            issueDate: firebase.database.ServerValue.TIMESTAMP,
            ackDate: '',
            returnDate: '',
            usedDate: ''
        });
      }
    });
    this.bootstrap_alert_success("Engineer Part Added");
  } else {
    this.bootstrap_alert_warning("Engineer Not Available / No Part / Not Signed In");
  }
}

All the Sub functions used in the Main function

FriendlyChat.prototype.checkSignedIn = function(){
  // Return true if the user is signed in Firebase
  if (this.auth.currentUser) {
    console.log("signed-in");
    return true;
  }
  console.log("not signed in");
  return false;
};

check engineer true

FriendlyChat.prototype.checkEngTrue = function(){

this.messagesRefEngineerId.orderByChild("id").equalTo(this.engineerText.value).once("value", function(snapshot) {
        var userData = snapshot.val();
        if(userData){
          console.log("engineer available");
          return true;
        }
        console.log("engineer not avilable");
        return false;
      });
    };

Screenshot telling that even if all functions return true the function is not executed Screenshot

Full Main.js Code

'use strict';

// Initializes FriendlyChat.
function FriendlyChat() {
  this.checkSetup();

  // Shortcuts to DOM Elements.
  this.engineerElement = document.getElementById('engineer-list');
  this.partArray = document.getElementById('part-array');
  this.engineerText=document.getElementById('engineer-text');
  this.issueButton = document.getElementById('issue-part-btn');
  this.userPic = document.getElementById('user-pic');
  this.userName = document.getElementById('user-name');
  this.signInButton = document.getElementById('sign-in');
  this.signOutButton = document.getElementById('sign-out');

  this.engineerName = document.getElementById('engineer-name');
  this.engineerId = document.getElementById('engineer-id');
  this.engineerAddButton = document.getElementById('add-engineer-btn');
  this.engineerAddButton.addEventListener('click', this.engineerAdd.bind(this));

  // Saves message on form submit.
  this.signOutButton.addEventListener('click', this.signOut.bind(this));
  this.signInButton.addEventListener('click', this.signIn.bind(this));
  this.issueButton.addEventListener('click', this.issueParts.bind(this));

  // $('ul li a').on('click', function(){
  //   console.log("clicked");
  //   $('#engineer-text').val($('#engineer-list li a').text().substr($('#engineer-list li a').text().lastIndexOf(" ") + 1));
  //   $('#engineer-list-btn').text($('#engineer-list li a').text().substr(0,$('#engineer-list li a').text().lastIndexOf(" ")));
  // });

  // $('#add-part-btn').on('click',function(){
  //   var div = document.createElement('div');
  //   var container = document.createElement('div');
  //   container.innerHTML = FriendlyChat.PART_NO_TEMPLATE;
  //   div = container.firstChild;
  //   this.partArray.appendChild(div);
  // });

  this.initFirebase();
}

// Sets up shortcuts to Firebase features and initiate firebase auth.
FriendlyChat.prototype.initFirebase = function() {
  // Shortcuts to Firebase SDK features.
  this.auth = firebase.auth();
  this.database = firebase.database();
  this.messagesRefEngineerId = this.database.ref('PartInfo/Engineer');
  this.messagesRefCurrentPart = this.database.ref('PartInfo/CurrentPart');
  this.storage = firebase.storage();
  // Initiates Firebase auth and listen to auth state changes.
  this.auth.onAuthStateChanged(this.onAuthStateChanged.bind(this));
};

FriendlyChat.prototype.checkEngTrue = function(){
  this.messagesRefEngineerId.orderByChild("id").equalTo(this.engineerText.value).once("value", function(snapshot) {
    var userData = snapshot.val();
    if(userData){
      console.log("engineer available");
      return true;
    }
    console.log("engineer not avilable");
    return false;
  });
};

FriendlyChat.prototype.checkSignedIn = function(){
  // Return true if the user is signed in Firebase
  if (this.auth.currentUser) {
    console.log("signed-in");
    return true;
  }
  console.log("not signed in");
  return false;
};

FriendlyChat.prototype.issueParts = function() {
  if(this.engineerText.value && this.checkSignedIn() && this.checkEngTrue()) {
    var inputs = document.getElementsByClassName( 'part-no' );
    var names = [].map.call(inputs, function(input){
      if(input.value != ""){
        firebase.database().ref('PartInfo/CurrentPart/' + $('engineer-text').value).push({
            partNo: input.value,
            issueDate: firebase.database.ServerValue.TIMESTAMP,
            ackDate: '',
            returnDate: '',
            usedDate: ''
        });
      }
    });
    this.bootstrap_alert_success("Engineer Part Added");
  } else {
    this.bootstrap_alert_warning("Engineer Not Available / No Part / Not Signed In");
  }
}

// Signs-in Friendly Chat.
FriendlyChat.prototype.signIn = function() {
  // Sign in Firebase using popup auth and Google as the identity provider.
  var provider = new firebase.auth.GoogleAuthProvider();
  this.auth.signInWithPopup(provider);
};

// Signs-out of Friendly Chat.
FriendlyChat.prototype.signOut = function() {
  // Sign out of Firebase.
  this.auth.signOut();
};

FriendlyChat.prototype.engineerAdd = function(e) {
  e.preventDefault();

  if(this.engineerName.value && this.engineerId.value && this.checkSignedIn()) {
    var currentUser = this.auth.currentUser;
    // Add a new message entry to the Firebase Database.
    this.messagesRefEngineerId.push({
      name: this.engineerName.value,
      id: this.engineerId.value
    }).then(function() {
      // Alert Engineer Added ----------------------------------------------------------------------------------------
      this.engineerName.value='';
      this.engineerId.value='';
      this.bootstrap_alert_success('Engineer Added');
    }.bind(this)).catch(function(error) {
      this.bootstrap_alert_error('Engineer Adding Failed');
      console.error('Error writing new message to Firebase Database', error);
    });
  } else {
    this.bootstrap_alert_warning('Make sure that Fields are not Empty and you are Signed-In');
  }
};

FriendlyChat.prototype.bootstrap_alert_error = function(message){
  $('#alert_placeholder').html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>'+message+'</span></div>')
}; 

FriendlyChat.prototype.bootstrap_alert_warning = function(message){
  $('#alert_placeholder').html('<div class="alert alert-warning alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>'+message+'</span></div>')
  setTimeout(function() { // this will automatically close the alert and remove this if the users doesnt close it in 5 secs
    $(".alert").remove();
  }, 3000);
}; 

FriendlyChat.prototype.bootstrap_alert_success = function(message){
  $('#alert_placeholder').html('<div class="alert alert-success alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>'+message+'</span></div>')
  setTimeout(function() { // this will automatically close the alert and remove this if the users doesnt close it in 5 secs
    $(".alert").remove();
  }, 1000);
}; 

FriendlyChat.prototype.loadEngineerList = function() {
  // Make sure we remove all previous listeners.
  this.messagesRefEngineerId.off();

  // Loads the last 12 messages and listen for new ones.
  var setEngineer = function(data) {
    var val = data.val();
    this.updateEngineerList(data.key, val.name, val.id);
  }.bind(this);
  this.messagesRefEngineerId.on('child_added', setEngineer);
  this.messagesRefEngineerId.on('child_changed', setEngineer);
};

FriendlyChat.prototype.updateEngineerList = function(key, name, id) {
  var li = document.getElementById(key);
  // If an element for that message does not exists yet we create it.
  if (!li) {
    var container = document.createElement('li');
    container.innerHTML = FriendlyChat.MESSAGE_TEMPLATE;
    li = container.firstChild;
    li.setAttribute('id', key);
    this.engineerElement.appendChild(li);
  }
  var messageElement = li.querySelector('a');
  if (name || id) { // If the message is text.
    messageElement.textContent = name + " " + id;
  }
}

FriendlyChat.MESSAGE_TEMPLATE =
    '<li><a href="#"></a></li>';

// Triggers when the auth state change for instance when the user signs-in or signs-out.
FriendlyChat.prototype.onAuthStateChanged = function(user) {
  if (user) { // User is signed in!
    // Get profile pic and user's name from the Firebase user object.
    var profilePicUrl = user.photoURL;
    var userName = user.displayName;

    // Set the user's profile pic and name.
    this.userPic.style.backgroundImage = 'url(' + (profilePicUrl || '/images/profile_placeholder.png') + ')';
    this.userName.textContent = userName;

    // Show user's profile and sign-out button.
    this.userName.removeAttribute('hidden');
    this.userPic.removeAttribute('hidden');
    this.signOutButton.classList.remove('hidden');

    // Hide sign-in button.
    this.signInButton.classList.add('hidden');

    //Update engineer list and keep informed.
    this.loadEngineerList();

  } else { // User is signed out!
    // Hide user's profile and sign-out button.
    this.userName.setAttribute('hidden', 'true');
    this.userPic.setAttribute('hidden', 'true');
    this.signOutButton.classList.add('hidden');

    // Show sign-in button.
    this.signInButton.classList.remove('hidden');
  }
};

FriendlyChat.prototype.addPartNoTextBox = function() {
  var div = document.createElement('div');
  var container = document.createElement('div');
  container.innerHTML = FriendlyChat.PART_NO_TEMPLATE;
  div = container.firstChild;
  $('#part-array').appendChild(div);
};

// Checks that the Firebase SDK has been correctly setup and configured.
FriendlyChat.prototype.checkSetup = function() {
  if (!window.firebase || !(firebase.app instanceof Function) || !firebase.app().options) {
    window.alert('You have not configured and imported the Firebase SDK. ' +
        'Make sure you go through the codelab setup instructions and make ' +
        'sure you are running the codelab using `firebase serve`');
  }
};

window.onload = function() {
  window.friendlyChat = new FriendlyChat();
};

Full Index.html

<!doctype html>
<!--
  Copyright 2015 Google Inc. All rights reserved.
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
      http://ift.tt/1zEcmP2
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License
-->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="description" content="Learn how to use the Firebase platform on the Web">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Friendly Chat</title>

  <!-- Disable tap highlight on IE -->
  <meta name="msapplication-tap-highlight" content="no">

  <!-- Web Application Manifest -->
  <link rel="manifest" href="manifest.json">

  <!-- Add to homescreen for Chrome on Android -->
  <meta name="mobile-web-app-capable" content="yes">
  <meta name="application-name" content="Friendly Chat">
  <meta name="theme-color" content="#303F9F">

  <!-- Add to homescreen for Safari on iOS -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="apple-mobile-web-app-title" content="Friendly Chat">
  <meta name="apple-mobile-web-app-status-bar-style" content="#303F9F">

  <!-- Tile icon for Win8 -->
  <meta name="msapplication-TileColor" content="#3372DF">
  <meta name="msapplication-navbutton-color" content="#303F9F">

  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="http://ift.tt/2apRjw3" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <!-- jQuery library -->
  <script src="http://ift.tt/2nYZfvi"></script>

  <!-- Latest compiled and minified JavaScript -->
  <script src="http://ift.tt/2aHTozy" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  <!-- Material Design Lite -->
<!--   <link rel="stylesheet" href="http://ift.tt/1I7E37E">
  <link rel="stylesheet" href="http://ift.tt/2v6wQoe">
  <script defer src="http://ift.tt/29mKKM4"></script>
 -->
  <!-- App Styling -->
  <link rel="stylesheet" href="http://ift.tt/1PtpYU3">
  <link rel="stylesheet" href="styles/main.css">
</head>
<body>
  <!-- Header section containing logo -->
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <a class="navbar-brand" href="#">PRS SERVICES</a> 
      <ul class="nav navbar-nav navbar-right">
        <li><div hidden id="user-pic" class="navbar-btn"></div></li>
        <li><div hidden id="user-name" class="navbar-text"></div></li>
        <li><button id="sign-out" type="button" class="btn btn-primary navbar-btn hidden">Sign-out</button></li>
        <li><button id="sign-in" type="button" class="btn btn-primary navbar-btn hidden">Sign-in with Google</button></li>
      </ul>
    </div>
  </nav>

  <div id = "alert_placeholder"></div>

  <div class="form-group">
    <div class="row">
      <div class="col-md-6">
        <div class="input-group">
          <div class="input-group-btn">
            <button id="engineer-list-btn" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Engineer <span class="caret"></span></button>
            <ul id="engineer-list" class="dropdown-menu">

            </ul>
          </div><!-- /btn-group -->
          <input type="text" id="engineer-text" name="engineer-text" class="form-control" aria-label="..." placeholder="Engineer Code">
        </div><!-- /input-group -->
      </div><!-- /.col-lg-6 -->
    </div><!-- /.row -->

    <div id="part-array">
      <div class="row">
        <div class="col-md-6">
          <input type="text" class="form-control part-no" placeholder="Part No.">
        </div>
      </div>

      <div class="row">
        <div class="col-md-6">
          <input type="text" class="form-control part-no" placeholder="Part No.">
        </div>
      </div>

      <div class="row">
        <div class="col-md-6">
          <input type="text" class="form-control part-no" placeholder="Part No.">
        </div>
      </div>

      <div class="row">
        <div class="col-md-6">
          <input type="text" class="form-control part-no" placeholder="Part No.">
        </div>
      </div>

      <div class="row">
        <div class="col-md-6">
          <input type="text" class="form-control part-no" placeholder="Part No.">
        </div>
      </div>

      <div class="row">
        <div class="col-md-6">
          <input type="text" class="form-control part-no" placeholder="Part No.">
        </div>
      </div>

      <div class="row">
        <div class="col-md-6">
          <input type="text" class="form-control part-no" placeholder="Part No.">
        </div>
      </div>
    </div>
    <button id="add-part-btn" type="button" class="btn btn-primary">Add More Parts</button>
    <button id="issue-part-btn" type="button" class="btn btn-primary">Issue Parts</button>
  </div>

  <hr>

<h2>Add Engineer</h2>
<div class="input-group">
  <input id="engineer-name" type="text" name="engineer-name" class="form-control" placeholder="Engineer Name">
  <input id="engineer-id" type="text" name="engineer-id" class="form-control" placeholder="Engineer Id">
  <button id="add-engineer-btn" type="button" class="btn btn-primary">Add Engineer</button>
</div>

<!-- Import and configure the Firebase SDK -->
<!-- These scripts are made available when the app is served or deployed on Firebase Hosting -->
<!-- If you do not want to serve/host your project using Firebase Hosting see http://ift.tt/29zkUUb -->
<script src="/__/firebase/4.1.3/firebase.js"></script>
<script src="/__/firebase/init.js"></script>

<script src="scripts/main.js"></script>
</body>
</html>

Aucun commentaire:

Enregistrer un commentaire