Tag Archives: JavaScript

Direct and Delegated Event Handlers in jQuery

An alternate title might be: how to bind event handlers to new, or dynamically generated, table rows. When using jQuery, we attach sets of instructions to different parts of an HTML document using selectors. Suppose you wanted to attach some functionality to some text in a table, for example, when you click on a row in a table, it brings up a new table below the first table. This is actually kind of tricky, it turns out that there is a distinction between direct and delegated event handlers.

Continue reading

Handle EADDRINUSE Error in Node

When a node application crashes unexpectedly, you might get a EADDRINUSE, Address already in use error when you try to restart it. This means that the port you’re using is already being used by the crashed application. What you need to do is fun the PID of that process, and then kill it. There’s more than one way to skin that cat, but I like to use netstat. N.B. You’ll need to run this as sudo for it to work.

Continue reading

Open a Text File with Angular

I had some trouble this weekend figuring out how to open a text file in Angular. My luck turned around when I found this StackOverflow question. The question addressed loading an image, but I was able to fiddle with this Plunker example until I was able to load text files. (Basically, I replaced every instance of “readAsDataURL” in the upload.js file with “readAsText”.)

Continue reading

How to Import Your Own Modules in Node

In order to create your own modules in Node, you attach your own classes or functions to an exports or module.exports object. Then you can access those items in the required module. Suppose we have a file named classes.js. If we wanted to import the ClassX and ClassY classes from that module, then we would add the following lines at the end of the classes.js file:

module.exports.ClassX = ClassX ;
module.exports.ClassY = ClassY ;

Then, in another file we would access these classes as:

var classes = require("./classes.js") ;
var ClassX = classes.ClassX ;
var ClassY = classes.ClassY ;

Preserve JS Object Methods Over HTTP via JSON

I had the problem this week of sending Javascript objects over HTTP; although you can easily send objects using JSON, you cannot transmit the object methods. I had intended to build a data structure on the server, send it over to the client where different attributes would be changed, and then send the object back to the server where I had hoped to use the object methods, except the methods did not exist any longer.

Continue reading

Coordinate Reference System Transformations in Javascript

Yes, you can do coordinate reference system transformations in Javascript. (I know, I’m shocked also.) I found proj4js on GitHub, which is a port of an older project, PROJ.4. The proj4js library is very easy to use. All you need to do is find the specification strings at spatialrerefence.org of the two projections/datums you are interested in and you’re ready to go.

Continue reading

General Tree Data Structure in Javascript

In this post I’ll provide some code for a general tree data structure in Javascript. I found a lot of packages on npm that provided binary trees, red-black trees, and tries [sic], but nothing that provided a general tree data structure. As with most implementations of data structures that I’ve seen, this implementation defines a Node object, and the large scale structure that we’re interested in, a Tree object. The Node object knows about other Node objects, specifically it’s parent and children. The Tree object is responsible for connecting these nodes in a tree structure. We could use a very, very similar Node object to build a different kind of tree, or a linked list, or a stack, or whatever.

Continue reading

Using Node and Mongo to Collect Data from Reddit

I am taking a course on MongoDB development with Node.js from Mongo University. In the second week we covered a thing that I thought was very interesting. They walked you through how to grab the JSON data out of a Reddit page. Reddit apparently offers its data up as a JSON if you pass it a .json path. Here is the coffeescript that produces the code provided in the development course.

Continue reading

Blum Mental Hash with Node and Angular

In this post I’ll walk through building a simple Blum Mental Hash application using Node and Angular. I’ll write my Node and Angular code using CoffeeScript, and I’ll build my HTML templates with Jade.

Writing the Application in CoffeeScript

I really enjoy CoffeeScript. I get that real programmers don’t use CoffeeScript, but I don’t care. Javascript makes me crazy. This is my CoffeeScript code–I require a bunch of stuff: express, http, jade. Then I define an express object named app and set some settings on it. Then I tell the root path, '/', to use the './static' subdirectory on the server. Then I tell any GET requests to '/' to return HTML that’s been rendered by jade using my index.jade template.

#!/usr/bin/env node
# app.coffee

express = require "express"
http = require "http"
jade = require "jade"

app = express()

app.set( 'views', './static' )
app.set( 'view engine', 'jade' )
app.engine( 'jade', jade.__express )

app.use '/', express.static('./static')

app.get '/', ( req, res ) ->
    res.render( 'index.jade' )

server = app.listen 8000, ->
    host = server.address().address
    port = server.address().port
    console.log 'Example at http://%s%s', host, port

We can compile this guy at the command line by calling,

coffee -c app.coffee

This will create an app.js file in your working directory.

The Controller

The file contoller.coffee sits in the subdirectory ./static/js/. The first items, mapping and perm, should ideally be picked by the user. In this example I’ve hard coded them for convenience. The convert() function brings everything together; it combines mapping and perm in such a way as to hash a string of capital letters. From there myapp.controller can compute the hash for the user.

#!/usr/bin/env node
# ./static/js/controller.coffee

mapping =
    A: 4,   B: 9,   C: 4
    D: 5,   E: 8,   F: 5
    G: 7,   H: 1,   I: 8
    J: 3,   K: 6,   L: 8
    M: 9,   N: 0,   O: 9
    P: 0,   Q: 6,   R: 1
    S: 9,   T: 6,   U: 4
    V: 7,   W: 5,   X: 0
    Y: 9,   Z: 3

f = ( x, mapping ) ->
    Maps a string `x` to an array of digits
    a = []
    for i in x
        a.push( mapping[i] )
    return a

perm = [ 8, 2, 5, 4, 9, 0, 3, 7, 1, 6 ]

permute = ( i, perm ) ->
    Returns the next value in the permutation
    idx = perm.indexOf( i )
    idx = ( idx + 1 ) % 10
    return perm[ idx ]

g = ( a, perm ) ->
    Hashes a list of digits into a string of digits
    b = [ permute( ( a[0] + a[ a.length-1 ] ) % 10, perm ) ]
    for i in [1...a.length]
        b.push( permute( ( b[i-1] + a[i] ) % 10, perm ) )
    return b.join("")

convert = ( x ) ->
    Convert a string of characters to a hashed string of digits
    a = f( x, mapping )
    return g( a, perm )

myapp = angular.module( "myapp", [] )

myapp.controller "controller", ($scope) ->
    $scope.plain = ""
    $scope.b = ""
    $scope.update = ( plain ) ->
        $scope.b = convert( plain )

This CoffeeScript file should also be compiled into a Javascript file.

The View

The index.jade file lives in ./static. This prompts a user for a password, and then returns a hash of that password below. That’s it.

doctype html
    h1 Manuel Blum's Mental Hash (BMH)
      input(name="Password: ",type="text",ng-model="plain")
      button(ng-click="update(plain)") Convert
      p Hash: {{ b }}

We can serve the page by calling

node app.js

from the command line, and then navigating to localhost:5000.