factoring out client side code in socket.io - javascript

So, I know node.js, but I'm learning how to socket.io and express.js, (just started express/socket a few hours ago).
This isn't a huge issue, but I like my code to be clean, and I'm trying to factor out my client side code so it's just in a script tag as a src. For example, on my index.html page I have the following:
..
<head>
<title>Example Title</title>
<link href="./styles/index.css" rel="stylesheet" type="text/css" />
<script src="./scripts/index.js" type="text/javascript"></script>
<script src="/socket.io/socket.io.js" type="text/javascript"></script>
</head>
Where ./scripts/index.js is the javascript code for index.html. It looks like
var socket = io.connect("http://localhost:8000");
document.getElementById("sendBox").submit = function() {
var msg = document.getElementById("m");socket.emit("chat message", msg.value);
msg.value = "";
return false;
};
All the routing is working, but now the problem is that I'm getting the error "ReferenceError: io is not defined" when I try to use the code. On socket.io's website, their example always just has a script tag with all of their page specific code embedded within it. I think that's ugly and means I have to edit an html page to edit my js for a page. This is especially annoying when the highlighting and autocorrects in my editor align to html on an html file, not js. It's not a catastrophic thing, I COULD embed my code like socket.io shows in their examples, but I'd prefer not to.
for those confused by what i mean, Socket.io's beginner example code:
<head>
<title>Socket.IO Chat</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script> // This is the code i want to look more like ^
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
</script> // End of the code I'd like to factor out.
To sum up, how can i make the variable "io" available to my index.js script?
Thanks

try swapping the js script tags
<head>
<title>Example Title</title>
<link href="./styles/index.css" rel="stylesheet" type="text/css" />
<script src="/socket.io/socket.io.js" type="text/javascript"></script>
<script src="./scripts/index.js" type="text/javascript"></script>
</head>
the way you had it, it would try to run io before it was loaded

Related

Docusaurus: Adding Coveo Search code. Where should these pieces go

I'm working through a Coveo Atomic tutorial here: https://levelup.coveo.com/learn/courses/atomic/lessons/lesson-0-setup-and-initializing-the-search-interface In their example they show setting up the initialization code in your index.html file like the following:
<!DOCTYPE html>
<html>
<head>
<script
type="module"
src="https://static.cloud.coveo.com/atomic/v2/atomic.esm.js"
></script>
<link
rel="stylesheet"
href="https://static.cloud.coveo.com/atomic/v2/themes/coveo.css"
/>
<link
rel="stylesheet"
href="style.css"
/>
<script>
(async () => {
await customElements.whenDefined("atomic-search-interface");
const searchInterface = document.querySelector("#search");
await searchInterface.initialize({
accessToken: "xx29e62e9b-f739-4886-b433-c9326cc1b492",
organizationId: "docsdemoslhkhaxyy",
});
searchInterface.executeFirstSearch();
})();
</script>
</head>
<body>
<atomic-search-interface id="search">
<atomic-search-layout>
<!-- all Atomic components will go in here -->
</atomic-search-layout>
</atomic-search-interface>
</body>
</html>
For the code that goes in the head element, should i put that in the head element of the index.js file in the pages directory? For the code that goes into the body element, where should i put that, in the Docusaurus files? Is there an overall best practices when implementing something like this in Docusaurus? This is the first time I've tried this so I apologize up front for even more newbie questions than usual.
I would have thought that putting this code in the index.js file would be correct?

Accessing iframe contents - code works in the console, but not when the page loads

When I run my code in console it works fine, but when I load the page it gives me an error - TypeError: undefined is not an object (evaluating 'rowInfo.textContent')
I have two webpages one that is the parent and the other that is the child. They are both on the same local server using the same protocol and port. I have a third file that holds the javascript. Here is the relevant code:
Parent Page
<html>
<head>
<title>Broker's Lead List</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="https://c1eru548.caspio.com/scripts/embed.js"></script>
</head>
<body>
<div id="callback"></div>
<script type="text/javascript" src="scripts.js"></script>
<script type="text/javascript">
autoRefresh_div();
window.frames['DueDateCounter'].addEventListener("load", alert("loaded"));
popUpWindow();
</body>
</html>
Javascript code
function autoRefresh_div() {
$("#callback").empty()
.html('<iframe name="DueDateCounter" title="DueDateCounter" ' +
'style="width: 1px; height: 1px" ' +
'src="https://192.168.0.50/CRM/CalanderCountDown.html">Sorry, but// your browser does not support frames.//</iframe>');
}
var f, doc, rowInfo, minutesUntilCallBack, calenderItem, calenderItemId;
function popUpWindow() {
f = $('iframe')[0];
doc = f.contentDocument? f.contentDocument: f.contentWindow.document;
rowInfo = doc.getElementsByTagName('td')[0];
minutesUntilCallBack = rowInfo.textContent;
calendarItem = f.contentDocument.getElementsByTagName('td')[1];
calendarItemId = calendarItem.textContent;
alert(minutesUntilCallBack);
alert(calendarItemId);
}
After the page has loaded and I go to the console, I can see that the variable f is defined, but nothing else is defined. Now if I use the console and put the code in everything works fine. The minutesUntilCallBack alerts and so does the correct calendarItemId.
I thought it might have been a problem with the iframe not being loaded properly, so I put a listening event in, that I have to OK before I run the function popUpWindow() that looks into the iframe.
I've read lots of posts about similar issues across many sites, but can't seem to get to the correct answer.
Any help much appreciated.
You need to put the popUpWindow() function inside of the onload event listener for the iframe. It is currently running before the iframe has loaded. addEventListener is asynchronous.
window.frames['DueDateCounter'].addEventListener("load", function() { popUpWindow(); });

Properly use custom angularjs service, function not defined error

I created my own service for some util methods. The idea was to simply inject the utilsservice into the modules where I need the methods. The Problem is I get an ReferrenceError: myFunction is not defined.
I think it has to do with the wrong injecting of the service, but i can't figute out myself what's wrong with my approach.
The service i made:
angular.module('utils',[]).service('UtilsService',function(){
this.myFunction = function(){};
});
In my app.js file i have following structure:
(function(){
angular.module('utils',[]);
angular.module('translation',[]);
var app = angular.module('myApp',['translation','utils']);
app.controller('myController',['$http',function($http,UtilsService){
UtilsService.myFunction();
}]);
});
The order I included the scripts in my .html file:
<script type="text/javascript" src="../Libraries/angular.min.js"></script>
<script type="text/javascript" src="../js/angular-js/services/utilService.js"></script>
<script type="text/javascript" src="../js/angular-js/app.js"></script>
<script type="text/javascript" src="../js/angular-js/translate.js"></script>
I already tried to change the order but it doesn't make any difference.
I am thankfull for any advice you may have!
Please try the below. You will need to change the script references to point to the files where you have them. Once the index.html file has loaded, you should see the output "you called myFunction()" in the console window. That is being printed from within the service which shows it's being called correctly. I've also created a fiddle
index.html:
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Directives</title>
</head>
<body>
<div ng-controller="myController"></div>
<script src="angular.js"></script>
<script src="app.js"></script>
<script src="utilsService.js"></script>
</body>
</html>
app.js (I have moved the code out of the function you created since it wasn't working. Also, you had a typo for spelling anguar on the line that begins with var app. I have also removed the dependency for translation in my code since I didn't create any module by that name):
(function(){
//angular.module('utils',[]);
//angular.module('translation',[]);
});
var app = angular.module('myApp',['utils']);
app.controller('myController',['$scope', 'UtilsService',function($scope,UtilsService){
UtilsService.myFunction();
}]);
utilsService.js:
angular.module('utils',[])
.service('UtilsService',function(){
this.myFunction = function(){ console.log ('you called myFunction()')};
});

Simple comet application "org is not defined"

I am trying to update an old cometd javascript wrapper and test client (was 1.3.x) that I have to the newer comet 2.5.1 javascript implementation. I have all of the dependencies and the browser can find them all, yet I am getting errors in Firebug's console (see below)
The head of my HTML is as below:
<head>
<title>CometD Tester</title>
<link rel="stylesheet" type="text/css"href="style/style.css" />
<script type="text/javascript" src="org/cometd/Cometd.js"></script>
<script type="text/javascript" src="org/cometd/AckExtension.js"></script>
<script type="text/javascript" src="org/cometd/ReloadExtension.js"></script>
<script type="text/javascript" src="jquery/jquery-1.9.0.js"></script>
<script type="text/javascript" src="jquery/jquery.cookie.js"></script>
<script type="text/javascript" src="jquery/jquery.cometd.js"></script>
<script type="text/javascript" src="jquery/jquery.cometd-reload.js"></script>
<script type="text/javascript" src="js/myCometd.js"></script>
</head>
All of these are found by the browser. Looking at Cometd.js I see the following:
org.cometd.Cometd = function(name)
{
....
}
So is that not defining org? Note that none of the errors in the Console are from Cometd.js. Otherwise I see no other definition of "org.cometd". I would really appreciate it if anyone can help me out. I am using Tomcat 7 and below is the dir structure:
Thanks.
UPDATE - Further testing
I reduced the header to:
<head>
<title>CometD Tester</title>
<link rel="stylesheet" type="text/css"href="style/style.css" />
<script type="text/javascript" src="org/cometd/Cometd.js"></script>
</head>
And removed ALL JS from the index.html. The only JS now included is the Cometd.js from the comet.org. There is still the same error... coming from the very first line in that script:
org.cometd.Cometd = function(name)
Not sure what I have missed here.
EDIT - Add jquery.cometd-reload.js
This is the contents of the file. It looks like it is "re-binding" functionality from the cometd library to use the jquery one instead (?). I'm not up to speed enough in JS to debug this (I'm a C++ dev really).
(function($)
{
function bind(org_cometd, cookie, ReloadExtension, cometd)
{
// Remap cometd COOKIE functions to jquery cookie functions
// Avoid to set to undefined if the jquery cookie plugin is not present
if (cookie)
{
org_cometd.COOKIE.set = cookie;
org_cometd.COOKIE.get = cookie;
}
var result = new ReloadExtension();
cometd.registerExtension('reload', result);
return result;
}
if (typeof define === 'function' && define.amd)
{
define(['org/cometd', 'jquery.cookie', 'org/cometd/ReloadExtension', 'jquery.cometd'], bind);
}
else
{
bind(org.cometd, $.cookie, org.cometd.ReloadExtension, $.cometd);
}
})(jQuery);
So the problem was that I misunderstood the project layout from the Comet.org site. I should have followed the direction posted at cometd primer for non-maven setups a lot more closely. Basically when you are setting up the project you download the distribution, and then you need to take the code from the war files bundled inside the tarball.
SO, once you have extracted the tarball...
Take the org folder from cometd-javascript-common-2.5.1.war (located in \cometd-2.5.1\cometd-javascript\jquery\target) or cometd-javascript-jquery-2.5.1.war (located in \cometd-2.5.1\cometd-javascript\common\target)
Take the jquery folder from cometd-javascript-jquery-2.5.1.war
The org namespace definition was in the file org/cometd.js which I did not have before, as I wrongly assumed that it had been replace by the org/cometd/Cometd.js file. The namespaces org and comet are defined as below starting on line 17 of that file:
// Namespaces for the cometd implementation
this.org = this.org || {};
org.cometd = {};
org.cometd.JSON = {};
The functions are working correctly now.
Try loading jQuery before any of the other JavaScript files -
<head>
<title>CometD Tester</title>
<link rel="stylesheet" type="text/css"href="style/style.css" />
<script type="text/javascript" src="jquery/jquery-1.9.0.js"></script> <!-- load first -->
<script type="text/javascript" src="org/cometd/Cometd.js"></script>
<script type="text/javascript" src="org/cometd/AckExtension.js"></script>
<script type="text/javascript" src="org/cometd/ReloadExtension.js"></script>
<script type="text/javascript" src="jquery/jquery.cookie.js"></script>
<script type="text/javascript" src="jquery/jquery.cometd.js"></script>
<script type="text/javascript" src="jquery/jquery.cometd-reload.js"></script>
<script type="text/javascript" src="js/myCometd.js"></script>
</head>

Uncaught ReferenceError when accessing an object from another JS file

I have various JS libraries in my web application, which are loaded before my main JS file (main.js). One of these libraries is jshashtable, but when I try to create a new Hashtable object in main.js, Google Chrome and Firefox throw a ReferenceError, complaining that the variable does not exist.
Here is the <head> of the application:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="/static/jquery-1.4.4.min.js"></script>
<script type="text/javacsript" src="/static/jshashtable-2.1.js"></script>
<script type="text/javascript" src="/static/main.js"></script>
Here is the problem line in main.js:
posts = new Hashtable();
This line is inside a function called init which is called when the page has finished loading (using the jquery $(document).ready() function).
Any reason why Hashtable is not global? Google maps and jquery objects work with no such problem. The source of jshashtable can be seen on Google code.
Updated answer: The problem is that you've got a typo in the script tag:
<script type="text/javacsript" src="/static/jshashtable-2.1.js"></script>
<!-- ^^---- here (the letters are transposed) -->
I couldn't understand why you would be running into a problem and decided to actually copy-and-paste your script tags and replicate the structure exactly on my machine. And things stopped working and my world tilted 3° counter-clockwise until I finally stared at them long enough to see it.
Provided that the jshashtable code really is at /static/jshashtable-2.1.js and your server is serving it up correctly (double-check on Chrome's resources tab in the dev tools), I can't see any reason for that. Your scripts are in the right order, and jshashtable's docs show using a global Hashtable (and the code link you gave clearly shows it creating one).
Edit: I've just replicated that same structure (same scripts, same order, using jQuery(document).ready(function() { ... });) on my own server, and am not having that problem. I can create a Hashtable and use its functions.
My HTML:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Test Page</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type='text/javascript' src='jquery-1.4.4.js'></script>
<script type='text/javascript' src='jshashtable-2.1.js'></script>
<script type='text/javascript' src='main.js'></script>
</head>
<body>
</body>
</html>
My main.js:
jQuery(document).ready(function() {
try {
var ht = new Hashtable();
display("typeof ht = " + typeof ht);
display("ht.size() = " + ht.size());
}
catch (e) {
display("Exception: " + e);
}
function display(msg)
{
$("<p>").html(msg).appendTo(document.body);
}
});
Only difference is I'm not using a /static prefix, and I'm absolutely certain that makes no difference.

Categories