--> Logical Path

Logical Path

Technical discovery and communication

0 notes &

Javascript Shorts - Function Invocation Patterns

When a function is invoked, besides the arguments passed the function, the function also receives the this parameter. The value of this depends on the invocation pattern.

Method - A function is a property of an object. this is bound to that object

Function - A function is not a property of an object. this is bound to the global object

Constructor - Created with new prefix. this is bound to the new object

Apply - The apply method on a function takes two arguments:

  • the value to bind to this
  • an array of parameters

0 notes &

Javascript Shorts - Functions

The ‘Javascript Shorts’ series is my way of outlining a topic. I use a simple mind map to show a central topic and the ideas surrounding that topic. Writing is a way for me to confirm my understanding of a topic and the map provides me with a visual for recall. I will explore each of the ideas surrounding Javascript Functions in subsequent posts.

I’m reading Douglas Crawford’s Javascript: The Good Parts and that is the inspiration and guide for these posts. I highly recommend reading the book as it’s one of the most well written texts I’ve come across.

Filed under javascript javascriptshorts

0 notes &

Javascript Shorts - Objects

Objects are passed by Reference:

var thirdbase = {
      "player" : "Pablo Sandoval"
       "nickname" : "Panda"
 };

 var favorite = thirdbase.nickname;

 > favorite
 'Panda'

Every object is linked to a Prototype object. All objects created with the Object Literal notation inherit from Object.prototype. When retrieving a property, the prototype linkage is followed if it cannot be found in the current object. The linkage is followed (delegated) back to Object.prototype if necessary.

Properties can be Deleted from an object. Objects in the prototype linkage are not touched.

Reflection provides methods to discover an object’s properties. typeof reveals a property’s type and hasOwnProperty provides a way to test for a certain type:

> typeof thirdbase.nickname
'string'

> thirdbase.hasOwnProperty('number')
false

Enumeration Provides a way to loop over properties with the for in statement (note that order is not guaranteed)

for (player in team) {
    .
    .
}

Filed under javascript javascriptshorts

0 notes &

Javascript Shorts - Types

image

This is the first post in a set of ‘Javascript Shorts’. Today a look at types. Simple types are immutable (can’t be changed) but can be combined. For example, “Hello” + “World”.

Objects contain key-value pairs. Here we use the Object Literal notation to create the object greeting which contains two key-value pairs. 

var greeting = {
“first-word” : “Hello”,
“second-word” : “World”
};

Values can be retrieved:

>greeting[“second-word’]

'World'

..and updated:

greeting[“second-word”] = “Universe”

> greeting
{ ‘first-word’: ‘Hello’,
‘second-word’: ‘Universe’ }
>

Filed under javascript javascriptshorts

0 notes &

Create a document in MongoDB from an HTML Form in Node.js

Getting Started

I am building a web application called Jobkeeper that tracks job applications to which I’ve applied. Jobkeeper tracks:  company name, position, date applied, source of the job, referrals, url of the posting, notes and status. I want to show you how to send an html post request with form data to a web application which stores that data in a document database.

Jobkeeper uses Node.js, Express middleware, the Jade template language and MongoDB. Express middleware provides a framework to quickly build a web application on top of Node. Express handles the requests from and the responses to the browser. I’ll not go into the details of Express, as that would take a book and other people explain it better than I could. Jade is a template language that inserts fields from the database into an html document. More on this later. I’m also using twitter bootstrap and Less, they make life with CSS much easier.

The HTML Form

Let’s start from the point of view of the user creating a new job application. Here is a screenshot of a list of active jobs in Jobkeeper. 

Here is the screen where you would enter information about your job application. Yes, the UI is a bit rough! I’ll fix that later.

Here is the Jade code that builds and submits the Form:

div.action
   div
     -var nowdate = Date()
   div
   form(action='/addapp', method='post')
     input(type='hidden', value=locals._csrf, name='_csrf')
     input(type='hidden', value='active', name='Status')
     input(type='date', name='Applied')
     input(type='text', name='CompanyName', placeholder='Company Name', required)
     input(type='text', name ='Position', placeholder='Position', required)
     input(type='text', name='Notes', placeholder='Notes')
     input(type='text', name='Url', placeholder='Url of add')
     input(type='text', name='ReferredBy', placeholder='Referred by')
     <br>
     | Source:
     <br>
     label
             select(name= 'Source')
               option(value='cold') Cold
               option(value='sourced') Sourced
               option(value='network') Network
               <br>
     <br>
     input(type='checkbox', name='PhoneInterview', value='X') 
     | Phone interview 
     br
     input(type='checkbox', name='InPersonInterview', value='X') 
     | In person interview  
     br
     input(type='checkbox', name='RejectionLetter', value='X') 
     | Rejection Letter 
     br
     br
     input(type='submit', class='btn btn-success btn-sm',value='Create')

I’m assuming that you have basic knowledge about HTML forms. Also, I’m using HTML5 features with no fallback - yet. I do my development and testing using Chrome which supports all of the features that I take advantage of in the code. The code is sufficient to show how form data ultimately gets stored in a database.

Notice these two lines:

form(action='/addapp', method='post')
input(type='hidden', value=locals._csrf, name='_csrf')

The action maps to what is known in Express as a route. When addapp is part of the url,  the web application creates a request handler that processes the form.

The hidden field contains a security token that prevents Cross-site request forgery. I will touch on this later.

One thing to keep in mind about Jade is that it is sensitive to space indentation similar to python. An example is div.action. Notice that it is two spaces to the left of the div underneath. This is saying that div.action contains that div (and anything else that is indented). Keep this in mind if you notice odd behavior with page rendering.

Express

Now, lets look at the server and see how it handles the form data. The node server process is running and listening for incoming requests:

$ node app.js

Express server listening on port 3003

Several things are going on inside app.js, however I wanted to point out a few things that are key to processing our Form. The database connection:

var mongoskin = require('mongoskin');
var db = mongoskin.db('mongodb://localhost:27017/jobdb? auto_reconnect', {safe:true});
var app = express();
app.use(function(req, res, next) {
   req.db = {};
   req.db.applications = db.collection('applications');
   next();
 })

The middleware that handles the CSRF security. Setting the middleware will automatically verify the token that arrives in the request object.

app.use(express.cookieParser());
app.use(express.session({secret: '59B93087-78BC-4EB9-993A-      A61FC844F6C9'}));
app.use(express.csrf());

Here we use less middleware that will automatically compile .less files into .css at runtime.

app.use(require('less-middleware')({ src: __dirname + '/public', compress: true }));

Now we pull in or ‘require’ the module that contains the request handler code.

var applications = require('./routes/applications');

Then we route the request to the add function inside the applications module or request handler:

app.post('/addapp', applications.add);

The add function lives inside ./routes.applications.js:

exports.add = function(req, res, next){

if (!req.body || !req.body.CompanyName) return next(new Error('No data provided.'));

 req.db.applications.save({
   CompanyName: req.body.CompanyName,
   Position: req.body.Position,
   Applied: new Date(req.body.Applied),
   Status: req.body.Status,
   Source: req.body.Source,
   Notes: req.body.Notes,
   Url: req.body.Url,
   ReferredBy: req.body.ReferredBy,
   PhoneInterview: req.body.PhoneInterview,
   InPersonInterview: req.body.InPersonInterview,
   RejectionLetter: req.body.RejectionLetter
   }, 

   function(error, application){
     if (error) return next(error);
   if (!application) return next(new Error('Failed to save.'));
           res.redirect('/applications'); 
   }) 
};

This function is the Request Handler. When the request arrives, node will call this function and pass it the request (req) and response (res) objects. We then call the MongoDB save function and pass the document fields populated from the fields in the request object.

We then redirect control back to the web application server with a new route. In app.js we see that this route is mapped to a new request handler that displays a list of all job applications:

app.get('/applications', applications.list);

The request handler is the list function in the applications module:

 exports.list = function(req, res, next){
   req.db.applications.find().sort({Applied:-1}).toArray(function(err,         applications){
    if (err) return next(err);
    console.log("number of applications ", applications.length);
    res.render('applications', {
    title: 'Job Applications',
    applications: applications || []
  });
 });
};

This functions reads all the documents in the applications collection from MongoDB and passes them in an array to applications.jade along with the title, using the res.render function. I want to show you the parts of the jade file that reference the applications array for display:

.list
if (applications.length === 0)
  | No applications.
each application, index in applications
  .item
    div
      -var comptxt = ""
      -var myclass = ""
      -var nxtbtn = ""
      -var nxtstat = ""
      -myclass = application.Status =='active'? 'activeClass':'expiredClass';
      -if(application.RejectionLetter == "X")
        -comptxt = 'rejected-app'
      -if(application.Status == 'active')
        -myclass = 'activeClass'
        -nxtbtn = 'Expire'
        -nxtstat = 'expire'
       -else
        -myclass = 'expiredClass'
        -nxtbtn = 'Activate'
        -nxtstat = 'active'
    div
    div.action
     form(action='/updatestat/#{application._id}', method='post')
       input(type='hidden', value=application._id.toString(), name='id')
       input(type='hidden', value=nxtstat, name='Status')
       input(type='hidden', value=locals._csrf, name='_csrf')
       input(type='submit', class='btn btn-success btn-xs task-done', value=nxtbtn) 
    div.dateapplied(class=myclass)
      div
              -var day = application.Applied.getDate() + 1
              -var m = application.Applied.getMonth() + 1
              -var y = application.Applied.getFullYear()
              -var prettydate = m + " / " + day + " / " + y
      div

      span.name=prettydate
      |&nbsp
    div.name(class=comptxt)
      span.name=application.CompanyName
    div.position
      a(href='/viewapp/#{application._id}') #{application.Position}

This is the line that loops through the array:

each application, index in applications

And this is an example of referencing a field from a document in that array:

-myclass = application.Status =='active'? 'activeClass':'expiredClass';

In this line I’m referencing the Status field of the application object. I’m using a ternary operator to determine which css class to assign to the javascript variable myclass which I use to style the application date.

The above jade code displays a list of all the job applications in the system. The page renders similarly to the first screen shot at the top of this post.

This is a powerful platform and I barely scratched the surface. I hope that I’ve provided some useful information for you so that you can build your own web applications.

Thank you.


You can find all the code for this application on github Note that I usually have a development branch that is ahead of the Main branch.

The TODO List is the project that I cloned to begin building this application. It was a great help.

Filed under node.js express.js jade mongdb

0 notes &

Be still spotlight

Terminal command to stop mds!

$ sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.metadata.mds.plist

You can turn it back on:

sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.metadata.mds.plist

Filed under os x spotlight

0 notes &

tumblrbot asked: WHAT MAKES YOU FEEL BETTER WHEN YOU ARE IN A BAD MOOD?

Exercise and working on a project.

1 note &

How to port your domain name to Tumblr

A little background.

I was motivated to move my domain name when my prior host went down one too many times. So I decided to point my domain logicalpath.com to Tumblr. One of the main reasons that I chose Tumblr is that the platform has everything I need and more for a blog and the domain name service is free!

In my case I have a registrar, a DNS hosting service and a web host. This setup gives me the freedom of more control over my domain and where I host my blog. I don’t have to worry that if my registrar is down, I can’t access my DNS records. With a DNS host, I also have complete control over my DNS record. My registrar is MyDomain.com, my DNS host is zoneedit.com and my host is now Tumblr. Thank you Tumblr. 

Point your domain name to Tumblr.

Your DNS records may be hosted separately or hosted by your registrar or perhaps all your services are hosted by one entity. See more information about DNS records. Once you have access to your DNS record, you need to change the A record. More information is available about DNS record types. However, for our purposes just know that it maps your domain name to an ip number.

Here is my DNS record. I changed the IP address to 66.6.44.4. This is Tumblr’s IP address. Note that I changed the IP address for two A records, one for the @ subdomain and one for the www subdomain. These are both set so that either http://logicalpath.com or http://www.logicalpath.com resolve to Tumblr.

image

Configure Tumblr to recognize your domain name.

Now go back to your Tumblr blog’s dashboard. Click on the gear icon for your blog to enter the settings page. Locate your Username and click the pencil icon on the right. 

image

Switch the button to Use a custom domain and enter your domain’s url in the text box below the button.image

Confirm that the domain name points to Tumblr.

Click on the Test domain link to verify that the link works. Then click the Save button. And you’re finished. 

N.B. If you click on the Test domain link and see a red error message that says ‘Something went wrong’, try again. The change may take a few minutes to percolate through the system. 

The exciting part comes when point your browser to your domain (e.g. http://logicalpath.com ) and see of the site renders correctly. 

Good luck to you and I hope that you found this useful!

Filed under dns tumblr domain name