node.js modules - EventEmitter - javascript

I'm trying to create my own module for the GPIO-Pins of a Raspberry Pi but I want to receive .on('something', function() { }) events, if something changed (like a button is pressed/released).
The python script sends every 0.01 Seconds a value like true or false.
module.js
var PythonShell = require('python-shell');
module.exports = {
switch_live: function(pin) {
var status = false;
this.get = (function(){
return status;
});
var options = {
mode: 'text',
args: [pin],
pythonOptions: ['-u']
};
var pyshell = new PythonShell('./data/switch_loop.py', options);
pyshell.on('message', function(message) {
if (message == 'false') {
if (status) {
// EMIT: button released
}
status = false;
} else {
if (!status) {
// EMIT: button pressed
}
status = true;
}
});
return this.status;
},
some_other_funcs: function(pin) {
// ...
}
}
app.js
var module = require('./module.js');
var button = new module.switch_live(10);
The module can show you the status of the button:
// get status of button
var status = button.get(); // returns "true" or "false"
But I want something like this:
button.on('pressed', function() {
// call this function every time when button is pressed
});
button.on('released', function() {
// call this function every time when button is released
});
Thank you :)
EDIT: I didn't find a solution, because I need the functions inside the "module.exports".

My Solution
It is a module for a Linkerkit-Board.
app.js
var linkerkit = require('./linkerkit.js');
var button = new linkerkit.switch_live(20);
button.on('pressed', function() {
// call this function every time when button is pressed
console.log('press');
});
button.on('released', function() {
// call this function every time when button is released
console.log('release');
});
linkerkit.js
var PythonShell = require('python-shell');
var EventEmitter = require('events');
var util = require('util');
var linkerkit = {
switch_live: function(pin) {
var self = this;
this.status = false;
this.pin = pin;
EventEmitter.call(this);
this.get = function() {
return this.status;
}
this._pyshell = new PythonShell('./data/switch_loop.py', {
mode: 'text',
args: [this.pin],
pythonOptions: ['-u']
});
this._pyshell.on("message", function(message) {
if (message === "false") {
if (this.status === true) {
// EMIT: button released
self.emit("released");
}
this.status = false;
}
else {
if (this.status === false) {
// EMIT: button pressed
self.emit("pressed");
}
this.status = true;
}
});
}
}
for (var key in linkerkit) {
util.inherits(linkerkit[key], EventEmitter);
}
module.exports = linkerkit;
I edited the code because it should be able to do things like that:
var button = linkerkit.switch(20);
button.get() // get status of button once, has no python loop
var button_live = linkerkit.switch_live(20);
button.get() // get status of button once, has a python loop
button.on('pressed', callback);
button.on('released', callback);
var led = linkerkit.led(10);
led.on();
led.off();
led.brightness(255); // digitalOutput - brightness
led.blink(200); // 100ms on, 100ms off
var ledcolor = linkerkit.led_rgb(12);
ledcolor.on(); // on -> color: white
ledcolor.off();
ledcolor.rgb([255, 0, 0]); // on -> color: red
And many more functions...

You should be able to use Node's built-in EventEmitter class to create your own "button emitter":
module.js
var PythonShell = require('python-shell');
var util = require('util');
var EventEmitter = require('events');
function ButtonEmitter(pinNumber) {
this.status = false;
this.pinNumber = pinNumber;
EventEmitter.call(this);
}
util.inherits(ButtonEmitter, EventEmitter);
ButtonEmitter.prototype.get = function() {
return this.status;
};
ButtonEmitter.prototype.switch_live = function() {
var options = {
mode: 'text',
args: [this.pinNumber],
pythonOptions: ['-u']
};
this._pyshell = new PythonShell('./data/switch_loop.py', options);
this._pyshell.on("message", this._handleMessage.bind(this));
return this.status;
};
ButtonEmitter.prototype._handleMessage = function(message) {
if (message === "false") {
if (this.status === true) {
// EMIT: button released
this.emit("pressed");
}
this.status = false;
} else {
if (this.status === false) {
// EMIT: button pressed
this.emit("released");
}
this.status = true;
}
};
module.exports = ButtonEmitter;
app.js
var ButtonTrigger = require('./module.js');
var button = new ButtonTrigger(10);
button.on('pressed', function() {
// call this function every time when button is pressed
});
button.on('released', function() {
// call this function every time when button is released
});
button.swith_live();
Explanation
The above code leverages Node's util.inherits to "subclass" EventEmitter, so that anyone using your class has access to .on(), .off() and other event methods. (Note: you could use ES6 class and extends syntax too, if you're Node version supports it)
Then, using your "subclass", you add your own switch_live method that starts the "listening" process, passing it the _handleMessage callback.
When the _handleMessage callback runs, it will compare the current status to the incoming one, and trigger a .emit() using the event names you posted in your question. Again, the .emit() is available because you a "subclassing" EventEmitter.

Related

WebRTC-Problem: Cannot create answer in stable (no Chrome but AJAX signalizing involved)

can somebody help me out a little? I am a little stuck.
I am trying to write a signaling process with ajax and a database involved (this is just for learning the basics of WebRTC for now).
I am receiving the SDP fine from the JSON-object as it seems, but then I always get an error "Cannot create answer in stable" when I try to create an answer in get_remote_offer() for pc_partner.
I am pretty sure it is something obvious, but I am pretty new to WebRTC and just can't see what.
I am using Firefox here and just trying to connect two instances of it (one in private mode, one in "normal" mode, but I am trying to make it work for remote users.
This is my code:
var opt;
var video_el_partner;
var video_el_local;
var pc_partner;
var pc_local;
var interval_gro;
var remote_offer_available = false;
var service_url = "https://xyz.de/webrtc";
var pwd = "xxx";
var signaling_url = "https://xyz.de/webrtc/sdp_transfer.php";
function init_stream(video_partner_id, video_local_id, allow_video, allow_audio){
if (location.protocol === 'https:') { // only possible for https!
pc_local = new RTCPeerConnection();
pc_partner = new RTCPeerConnection();
if(document.getElementById(video_partner_id) != null){
video_el_partner = document.getElementById(video_partner_id);
video_el_local = document.getElementById(video_local_id);
if(allow_video == null){
allow_video = true;
}
if(allow_audio == null){
allow_audio = true;
}
opt = { audio: allow_audio, video: allow_video };
if(typeof navigator != 'undefined' && typeof navigator.mediaDevices != 'undefined' && navigator.mediaDevices.getUserMedia != null){
navigator.mediaDevices.getUserMedia(opt).then (
function (this_stream){
// local video directly into video element:
video_el_local.srcObject = this_stream;
// remote one is more insteresting:
pc_local.addStream(this_stream);
pc_local.createOffer().then(
function (this_sdp) {
// sdp (session dependend protocol object) is now available... this would need to go to a server somehow now.
// they use socket.io for that... maybe I can use my own thing to do that?
pc_local.setLocalDescription(this_sdp);
var this_sdp_json = JSON.stringify(this_sdp)
var params_ins = "mode=insert_offer&sdp_con=" + this_sdp_json + "&pass=" + pwd + "&service_url=" + service_url;
ajax_request_simple (
signaling_url,
params_ins,
function (res_ins) {
// insert done. Lets read for another candidate.
console.log('Set Interval!');
interval_gro = window.setInterval('get_remote_offer();', 5000);
}
);
}
);
}
).catch(
function (error) {
console.log('Problem: ');
console.log(error);
}
);
} else {
console.log("navgiator or navigator.mediaDevices is not defined.");
}
}
} else {
console.log('init_stream(): We can only do anything like that on https-connections! Http is not supported by the browser!');
}
}
window.onload = function () {
document.getElementById('button_start_stream').onclick = function () {
init_stream('video_partner', 'video_local', true, false);
}
}
function is_json_str(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
function get_remote_offer() {
var params_read = "mode=get_offer&pass=" + pwd + "&service_url=" + service_url;
ajax_request_simple (
signaling_url,
params_read,
function (res_read) {
// done.
if(is_json_str(res_read)){
// seems like we get one now.
// lets use that to connect and stream the video to the remote view.
var partner_offer = res_read;
partner_offer = JSON.parse(partner_offer);
// clear interval if found.
window.clearInterval(interval_gro);
console.log('Cleared Interval. Found!');
pc_local.setRemoteDescription(
new RTCSessionDescription(partner_offer), function(){
// video_el_partner.srcObject = event.stream;
pc_local.onicecandidate = function (e) {
if ( e.candidate != null ) {
pc_partner.addIceCandidate( new RTCIceCandidate(e.candidate) );
}
};
pc_partner.onicecandidate = function (e) {
if ( e.candidate != null ) {
pc_local.addIceCandidate( new RTCIceCandidate(e.candidate) );
}
};
pc_partner.createAnswer(
function (offer) {
pc_local.setRemoteDescription(offer);
pc_partner.setLocalDescription(offer);
}
);
// pc_local.ontrack = function (evt) {
// video_el_local.srcObject = evt.stream;
// };
pc_partner.ontrack = function (evt) {
video_el_partner.srcObject = evt.stream;
};
},
function(e) {
console.log("Problem while doing client-answer: ", e);
}
);
} else {
console.log("Can not parse: ");
console.log(res_read);
}
}
);
}
Sorry for the mix of promises and callbacks... I tried a couple of things out just in case... when it is working I will rewrite the callback parts.
Thank you very much in advance for any hint you can give me :).
Best regards and thanks for reading till now ;).
Fuchur

Javascript--Breeze Manager Not Detecting Changes

I'm using the EntityManager from Breeze for the API portion of data-binding. However, the EntityManager fails to track the changes. It will execute the code like it's supposed to but it never recognizes the changes. What's the issue? Please, refrain from saying anything that is not constructive or any personal attacks. We're here as professionals and scientists(i know i am). Here is my code:
Service:
(function () {
var serviceId = 'UWRLService';
angular.module('myApp')
.factory(serviceId, ['$q', 'breeze', 'logger', 'appSettings', UWRLService]);
// console.log('Initialized UWRL Service.js');
function UWRLService($q, breeze, logger, appSettings) {
// console.log('inside datacontext -- UWRLService');
// configure logging for this service
logger = logger.forSource(serviceId);
var logError = logger.logError;
var logSuccess = logger.logSuccess;
var logWarning = logger.logWarning;
//Setup variables with common Breeze query classes
var entityQuery = breeze.EntityQuery;
// setup breeze entity manager
var serviceName = appSettings.apiUrl + '/breeze/Uwrl/';//Where the entire service is pointing to
var manager = new breeze.EntityManager(serviceName);
var entityStateChangeAction = breeze.EntityAction.EntityStateChange;
// expose methods
var service = {
getChangesCount: getChangesCount,
saveChanges: saveChanges,
rejectChanges: rejectChanges,
getDivisions: getDivisions,
getPools: getPools,
getRandomCust: getRandomCust
//createChangeFactorEntity: createChangeFactorEntity,
};
return service;
// FUNCTION DECLARATIONS
//Attaches a new entity to the Breeze repository
//Passes the name and an array of values to seed the entity with
//function createChangeFactorEntity(entityName, initialValues) {
// var newFactor = manager.createEntity(entityName, initialValues);
// return newFactor;
//}
function getRandomCust()
{
var query = breeze.EntityQuery.from('alpha')
.where('customerNumber', '==', 1);
return executeQuery(query, 'Alpha found!');
}
function getDivisions()
{
var query = breeze.EntityQuery
.from('Divisions');
//executeQuery([query name], [query title])
return executeQuery(query, 'Divisions Found');
}
function getPools()
{
var query = breeze.EntityQuery
.from('Pools');
return executeQuery(query, 'Pools Found');
}
//Saves changes and logs exceptions
function saveChanges() {
var hasChanges = manager.hasChanges();
console.log(hasChanges);
console.log(manager.getChanges());
return manager.saveChanges()
.then(saveSucceeded)
.catch(saveFailed);
function saveSucceeded(saveResult) {
logSuccess("# of items saved = " + saveResult.entities.length, null, true);
logger.log(saveResult);
}
function saveFailed(error) {
var reason = error.message;
var detail = error.detail;
if (error.entityErrors) {
//Do nothing
} else if (detail && detail.ExceptionType &&
detail.ExceptionType.indexOf('OptimisticConcurrencyException') !== -1) {
// Concurrency error
reason =
"Another user, perhaps the server, " +
"may have deleted one or all of the todos." +
" You may have to restart the app.";
} else {
reason = "Failed to save changes: " + reason +
" You may have to restart the app.";
}
logError(reason, error, true);
throw error; //Downstream: users know it has failed
}
}
//Discards changes in Breeze Manager
function rejectChanges() {
if (manager.hasChanges()) {
count = getChangesCount();
manager.rejectChanges();
logWarning('Discarded ' + count + ' pending changes(s)', null, true);
}
}
//Returns (Nth-1) index of Breeze manager getChanges array
function getChangesCount() {
var ents = manager.getEntities();
var changes = manager.getChanges();
if (changes.length > 0)
{
alert("Changes made: " + manager.getChanges().length);
}
return manager.getChanges().length;
}
//Query Execution w/ toasters(logger)
function executeQuery(query, entityType) {
var promise = manager.executeQuery(query).then(querySucceeded, queryFailed);
return promise;
function querySucceeded(response) {
logSuccess(entityType + " query was successful", null, true);
return response.results;
}
function queryFailed(response) {
var message = response.message || entityType + " query failed";
logError(message, response, true);
throw error;
}
}
};
})()
Controller (javascript):
(function () {
'use strict';
var controllerId = 'UWRLController';
// console.log('Initialized UWRLController');
//Last item in passed array is the Controller (specific)
angular.module('myApp').controller(controllerId,
['$scope', 'UWRLService', 'logger',
'$routeParams', 'allStatesService', UWRLController]);
function UWRLController($scope, UWRLService, logger, $routeParams, allStatesService) {
// console.log('inside UWRLController');
//Loggin Initialization
logger = logger.forSource(controllerId);
var logError = logger.logError;
var logSuccess = logger.logSuccess;
var logWarning = logger.logWarning;
var uwrl = {};
$scope.uwrl = uwrl;
//Parameters we pass from Renewal Group Maintenance screen
//uwrl.PlanCode = $routeParams.PlanCode;
//uwrl.Contract = $routeParams.ContractNumber;
//uwrl.Mch = $routeParams.Mch;
//Functions in Javascript Controller
//[scope].[property] = [function name]
uwrl.saveChanges = save;
uwrl.discardChanges = discardChanges;
uwrl.changesCount = changesCount();
//uwrl.select = select;
init();//Initialize all customer related data for page
function init()
{
gettingDivisions();//Initialze getting data from Division's table through UWRL-service.js
getAllFiftyStates();
gettingPools();
gettingRandom();
}
function gettingRandom()
{
UWRLService.getRandomCust()
.then(function(alpha)
{
uwrl.alpha = alpha;
uwrl.beta = uwrl.alpha[0].customerName;
});
}
function gettingDivisions()
{
UWRLService.getDivisions()
.then(function (divisionNumber) {
uwrl.divisionNumber = divisionNumber;
});
}
function getAllFiftyStates()
{
allStatesService.getStates()
.then(function (allStates)
{
uwrl.allStates = allStates;
});
}
function gettingPools()
{
UWRLService.getPools()
.then(function (poolNumber)
{
uwrl.poolNumber = poolNumber;
});
}
//Clicking the Drop-down Button
//function select(change) {
// this.MchMcpPlanDesignId = change.MchMcpPlanDesign.MchMcpPlanDesignId;
// change.expanded = !change.expanded; //toggle back and forth
//}
////.then = [if] success
////.fail = failure
////.finally = always executed despite evaluated conditionals
//function getPlans() {//returns a promise
// uwrl.loadingPlans = true;
// UWRLService.getChangeFactors(uwrl.Mch, uwrl.Contract, uwrl.PlanCode)
// .then(function (deltaChangeFactor) {
// uwrl.deltaChangeFactor = deltaChangeFactor;
// }).finally(function () { uwrl.loadingPlans = false; });
//}
////Returns all data in ChangeFactorType table
//function getChangeFactorTypes() {
// UWRLService.getTypes().then(function (changeFactorTypes) {
// uwrl.changeFactorTypes = changeFactorTypes;
// });
//}
//Clicking on Save Button
function save() {
console.log('Save Button Clicked!');
//Validation -- checks for empty values
//if (uwrl.changeFactorType != null && uwrl.effectiveDate != null &&
// uwrl.changeFactorAmount != null) {
// //Adds a new Breeze Entity for ChangeFactor table in SQL database
// UWRLService.createChangeFactorEntity('ChangeFactor',
// {
// MchMcpPlanDesignId: this.MchMcpPlanDesignId,
// ChangeFactorType: uwrl.changeFactorType,
// EffectiveDate: uwrl.effectiveDate,
// ChangeFactorAmount: uwrl.changeFactorAmount
// });
//}
//Saves to Breeze Manager
//Must hit Art's ESB service -- to be researched
UWRLService.saveChanges();
}
//Gets rid of changes and logs it
function discardChanges() {
console.log('Discard Button Clicked!');
UWRLService.rejectChanges();
}
//Notifies user(s) of changes made that are
//either: savable, discardable
function changesCount() {
// console.log("Changes Made: " + UWRLService.getChangesCount)//for debugging purposes
return UWRLService.getChangesCount;
}
};
})();
The answer is to make sure to effect the model. For example: uwrl.alpha[0].customerName instead of urwl.beta

Synchronous Call in JavaScript is not working

I am creating a hotel page which contains all the details of hotels including its reviews. For the reviews of the hotel, i want to do pagination.
In my code, init() function contain all the code for performing initial calculations like calculating no of pages etc.
As you can see init() is calling a function getReviewList which will return list of reviews. In getReviewList(), making a synchronous call to receive lists of reviews(i.e. reviewList.json).
The goal is once i receive the list of reviews, i can perform all the calculations. Even i am using setTimeout function so that this action get delayed by some time and in this mean time, the response get stored in the global variable "reviewList".
But the problem is that the calculation part gets executed before the response is stored in the global variable "reviewList". Please guide me where i am going wrong.
Javascript (fiddle : http://jsfiddle.net/n28SS/) fiddle contains incomplete code
getReviewList: function () {
var myReq, reqJSON,
oThis = this;
if(window.XMLHttpRequest) {
myReq = new XMLHttpRequest();
} else {
myReq = new ActiveXObject("Microsoft.XMLHTTP");
}
myReq.open("GET", "reviewList.json", true);
myReq.send();
myReq.onreadystatechange = function() {
if (myReq.readyState == 4) {
if (myReq.status == 200) {
oThis.reviewList = JSON.parse(myReq.responseText);
}
}
}
},
init: function() {
var oThis = this,
records;
records = oThis.getReviewList();
setTimeout(function () {
records = oThis.reviewList.length;
}, 1000);
oThis.pages = Math.ceil(records / oThis.itemsPerPage);
oThis.inited = true;
oThis.attachEventListener();
},
This doesn't work because
setTimeout(function () {
records = oThis.reviewList.length;
}, 1000);
returns immediately and performs the records=... operation in the background after 1000 ms.
The following line executes immediately and hence doesn't have access to records variable
oThis.pages=Math.ceil(records/...)
which will become available 1sec later. You can either move all the code into the set timeout block, or better yet make everything asynchronous:
getReviewList: function (callback) {//pass the function that needs to act on list
var myReq, reqJSON,
oThis = this;
if(window.XMLHttpRequest) {
myReq = new XMLHttpRequest();
} else {
myReq = new ActiveXObject("Microsoft.XMLHTTP");
}
myReq.open("GET", "reviewList.json", true);
myReq.send();
myReq.onreadystatechange = function() {
if (myReq.readyState == 4) {
if (myReq.status == 200) {
oThis.reviewList = JSON.parse(myReq.responseText);
callback(oThis.reviewList);
}
}
}
},
init: function() {
var oThis = this,
records;
records = oThis.getReviewList(function (reviewList) { //Pass the function as a parameter
records = reviewList.length;
oThis.pages = Math.ceil(records / oThis.itemsPerPage);
oThis.inited = true;
oThis.attachEventListener();
});
},
I haven't tested the code but it should demonstrate the basic concept.

Start object from setInterval?

I have the following reconnect method for Sockjs which almost is fully working:
(function() {
// Initialize the socket & handlers
var connectToServer = function() {
var warbleSocket = new SockJS('http://url.com:5555/warble');
warbleSocket.onopen = function() {
clearInterval(connectRetry);
$('.connect-status')
.removeClass('disconnected')
.addClass('connected')
.text('Connected');
};
warbleSocket.onmessage = function(e) {
$('#warble-msg').text(e.data);
};
warbleSocket.onclose = function() {
clearInterval(connectRetry);
connectRetry = setInterval(connectToServer, 1000);
$('.connect-status')
.removeClass('connected')
.addClass('disconnected')
.text('Disconnected');
};
// Connect the text field to the socket
$('.msg-sender').off('input').on('input', function() {
warbleSocket.send($('.msg-sender input').val());
});
function send(a) {
warbleSocket.send(a);
}
return {
send: send
};
}();
var connectRetry = setInterval(connectToServer, 1000);
})();
The error i am getting is when its trying to reconnect.
Error is:
SyntaxError: missing ] after element list
at this line:
connectRetry = setInterval(connectToServer, 1000);
Any ideas what im doing wrong here?
Your connectToServer variable is not a function, it's an object with a property send that is a function, so it doesn't make sense to say setInterval(connectToServer, 1000). Try this instead:
setInterval(connectToServer.send, 1000);
Why don't you simplify things a bit?
I would put connection stuff inside a specific function and call it from setInterval().
Something like this (use with care since I'm not testing this code, ok?):
(function() {
// Initialize the socket & handlers
var connectToServer = function() {
var warbleSocket;
function connect() {
warbleSocket = new SockJS('http://url.com:5555/warble');
warbleSocket.onopen = function() {
// ...
};
warbleSocket.onmessage = function(e) {
// ...
};
warbleSocket.onclose = function() {
// ...
}
// Connect the text field to the socket
$('.msg-sender').off('input').on('input', function() {
warbleSocket.send($('.msg-sender input').val());
});
function send(a) {
warbleSocket.send(a);
}
return {
send: send
};
}();
// you probably will need to call the first connection
connectToServer();
// and than set connection retry
var connectRetry = setInterval(connectToServer.connect, 1000);
})();
I hope it helps you.
Regards,
Heleno

Functions are undefined

I am trying to create a data management application, but instead of a Windows-based solution or using WebSQL, i am using IndexedDB. I am pretty new to it but I believe I have covered the basis in this draft of code.
Anyway, my problem is, anytime I run the code, my openDB() function and the addeventListener() function both run and show on the console log at runtime but all other functions are said to be undefined when I try to run the code. What could the problem be?
In the HTML file, the jQuery script file is referenced.
(function () {
var DB_NAME = 'shodex';
var DB_VERSION = 1;
var DB_STORE_NAME = 'visitors';
var db;
var current_view_pub_key;
//opens the IndexedDB database
function openDb() {
console.log("open Database......");
var req = indexedDB.open(DB_NAME, DB_VERSION);
req.onsuccess = function (evt) {
db = this.result;
console.log("Database Opened");
};
req.onerror = function (evt) {
console.error("openDb:", evt.target.errorCode);
};
req.onupgradeneeded = function (evt) {
console.log("Event fired when DB is needed to be upgraded");
var store = evt.currentTarget.result.createObjectStore(
DB_STORE_NAME, { keyPath: 'id', autoIncrement: true });
store.createIndex('name', 'name', { unique: false });
store.createIndex('date', 'date', { unique: false });
store.createIndex('whom_to_see', 'whom_to_see', { unique: false });
store.createIndex('arrival_time', 'arrival_time', { unique: false });
store.createIndex('reason', 'reason', { unique: false });
store.createIndex('departure_time', 'departure_time', { unique: false });
};
}
//used to create a transaction
function getObjectStore(store_name, mode) {
var tx = db.transaction(store_name, mode);
return tx.objectStore(store_name);
}
//adds a Visitor to the IndexedDB
function addVisitor(name, date, to_see, arrival_time, reason, departure_time) {
console.log("Adding the following data to IndexedDB: ", arguments);
var obj = { name: name, date: date, whom_to_see: to_see, arrival_time: arrival_time, reason: reason, departure_time: departure_time };
if(typeof blob != undefined)
{
obj.blob = blob;
}
var store = getObjectStore(DB_STORE_NAME, 'readwrite');
var req;
try
{
req = store.add(obj);
}
catch(e)
{
if(e.name == 'DataCloneError')
displayActionFailure("This engine does not know how to clone a Blob, use Firefox!");
throw(e);
}
req.onsuccess = function (evt) {
console.log("Insertion into DB was successful. You can heave a huge sigh of relief!");
displayActionSuccess();
};
req.onerror = function () {
console.error("Insertion into DB failed!");
displayActionFailure(this.error);
};
}
function displayActionSuccess() {
alert("Whatever the heck you were doing was successful. Congrats!");
}
function displayActionFailure() {
alert("Oh Oh! System Failure! System Failure!");
}
// listens for the submit button event
function addEventListeners() {
console.log("Event Listeners");
$('#addVisitor').click(function(evt) {
console.log("Add Visitors Submit button");
var name = document.getElementsByName("txtName").value;
var date = document.getElementsByName("txtDate").value;
var whom_to_see = document.getElementsByName("txtToSee").value;
var time_of_arrival = document.getElementsByName("txtArrivalTime").value;
var reason_for_visit = document.getElementsByName("txtReason").value;
var time_of_departure = document.getElementsByName("timeOfDep");
addVisitor(name, date, whom_to_see, time_of_arrival, reason_for_visit, time_of_departure);
});
}
//makes the database open at runtime
openDb();
addEventListeners();
})
();
syntax error - you need a closing round bracket at end.
i.e add
);
I think the problem is the fact that when your anonymous function is run the browser doesn't not know about the '#addVisitor' element, so the click event handler for that element is not created.
You should put your code inside "$(function() {" or "$(document).ready(function() {":
$(function() {
(function () {
var DB_NAME = 'shodex';
var DB_VERSION = 1;
...
Instead of referencing the javascript code like before...
I removed all other functions from the javascript file leaving the openDB() function and placed them in the main html file. it worked automatically.

Categories

Resources