Monthly Archives: August 2015

block, inline, and inline-block

block

start new line, takes up 100% of width. In other words, begins on a “new line”, and has an “carriage return” at the end. Notice how the last div with inline starts at new line:

inline

Gets appended to the left, and lines up towards the right.

They don’t have a definable height and width and will not create new rows in a layout (thus they appear “inline”).

If inline contains a block, the effect is negated. For example, in the example, the span has no effect. The testing 1 2 3 will all act like blocks.

inline-block

ref – http://designshack.net/articles/css/whats-the-deal-with-display-inline-block/

Historically, we use floats to align blocks of content, we would use a container with a width to make sure they stay in place. However, a quirky behavior is that when we float the children content, it would collapse the parent div because the parent div was not floated. You can resolve this by floating the parent div, however.

In other situations, if you do not float the parent div, your next div will be awkwardly lined up to the parent’s div. What you do in that case is to clear:both for the next div, and it would notice that the parent’s div are floating left, and thus would float below them. If you don’t do this, it would float below the collapsed parent’s div.

If you were to use inline-block, you wouldn’t need a parent div at all. it would work as expected. There would be no clear hacks. However you may need to use the vertical-align because due to inline-block starting text from bottom up, rather than top down.

DOM

ref – http://www.w3schools.com/js/js_htmldom.asp
https://javascript.info/dom-navigation

When a web page is loaded, the browser creates a Document Object Model of the page.

The HTML DOM model is constructed as a tree of Objects:

html = document.documentElement
The topmost document node is document.documentElement. That’s DOM node of tag.
body = document.body
Another widely used DOM node is the element – document.body.
head = document.head
The head tag is available as document.head.

A script cannot access an element that doesn’t exist at the moment of running.

In particular, if a script is inside , then document.body is unavailable, because the browser did not read it yet.

So, in the example below the first alert shows null:

What is the HTML DOM?

The HTML DOM is a standard object model and programming interface for HTML. It defines:

  • The HTML elements as objects
  • The properties of all HTML elements
  • The methods to access all HTML elements
  • The events for all HTML elements

In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

HTML DOM methods are actions you can perform (on HTML Elements)

HTML DOM properties are values (of HTML Elements) that you can set or change

for example:

In the example above, getElementById is a method, while innerHTML is a property.

The getElementById Method

The most common way to access an HTML element is to use the id of the element.

In the example above the getElementById method used id=”demo” to find the element.

The innerHTML Property

The easiest way to get the content of an element is by using the innerHTML property.

The innerHTML property is useful for getting or replacing the content of HTML elements.

The HTML DOM Document

In the HTML DOM object model, the document object represents your web page.

The document object is the owner of all other objects in your web page.

If you want to access objects in an HTML page, you always start with accessing the document object.

Below are some examples of how you can use the document object to access and manipulate HTML.

Event for Elements

Reacting to Events

A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.

To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:
onclick=JavaScript

Examples of HTML events:

When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
When an input field is changed
When an HTML form is submitted
When a user strokes a key

HTML Event Attributes

Assign Events Using the HTML DOM

DOM collections are read-only

DOM collections, and even more – all navigation properties listed in this chapter are read-only.

We can’t replace a child by something else assigning childNodes[i] = ….
Changing DOM needs other methods, we’ll see them in the next chapter.

DOM collections are live

Almost all DOM collections with minor exceptions are live. In other words, they reflect the current state of DOM.

If we keep a reference to elem.childNodes, and add/remove nodes into DOM, then they appear in the collection automatically.

Siblings are nodes that are children of the same parent. For instance, and are siblings:

body is said to be the “next” or “right” sibling of head,
head is said to be the “previous” or “left” sibling of body
The parent is available as parentNode.

The next node in the same parent (next sibling) is nextSibling, and the previous one is previousSibling.

For instance:

Access the div DOM node, ul DOM node, and 2nd li node

output:

Using console.dir to view objects

We want to color the cells in the table diagonally. In order to do this, we must get the rows object from the table first. The rows property is an array with rows.

For each row object, we see that there is an array of td objects. We color 0th td object for the first row, 1st td object for 2nd row…and so forth.

loading a js script without blocking

ref – http://www.nczonline.net/blog/2010/08/10/what-is-a-non-blocking-script/

JavaScript is single-threaded

Js is single threaded, meaning only 1 operation can be done at a time. This single thread is shared with browser rendering tasks. Due to javascript manipulating the DOM and doing drawing, its natural that its tasks is shared on the UI thread of the browser.

“The browser can only be executing JavaScript or rendering UI at any particular point in time (it can’t be doing both). This makes sense logically, because JavaScript may affect the UI by moving elements around or otherwise altering content, and the next time the UI is updated the browser wants to be sure the latest information is used.

With this knowledge, think of what happens as a page downloads to the browser. The page has started to render as it was downloaded, and then a “script” tag is encountered. At that point, the browser can no longer continue rendering because the JavaScript may affect the UI, and so it waits. The HTTP connection is made, the file is downloaded, parsed, and executed. Only once that is complete can the browser continue to render the rest of the page in full confidence that the output is up-to-date.”

Parallel downloading of scripts only means that two scripts are downloaded at the same time. Meaning the thread downloads parts of script 1, then download parts of script 2, then come back to script 1, and back to script 2…etc until both scripts are downloaded.

asynchronous execution means the current thread working on a task does not block other threads..and allows another thread to execute another task. Thus, this deals with multiple threads.

A blocking script means that the page cannot continue rendering until the script has been:

  • Completely downloaded
  • Parsed
  • Executed

ref – http://www.nczonline.net/blog/2009/06/23/loading-javascript-without-blocking/

The basic approach to downloading JavaScript without blocking is quite straightforward:

This is about as easy as it gets, you just create a new DOM element, assign its properties and add it to the page. There are two things to note about this code. First, the download doesn’t actually begin until the script node is added to the document. This is different from dynamically creating an element, for which assigning the src automatically begins the download even before the node is added to the document.

The second thing to note is that you can add the script node either to the or ; it really doesn’t matter. That’s all it takes to dynamically load a JavaScript file without blocking the page.

Of course, you may also want to be notified when the JavaScript file is fully downloaded and executed, and that’s where things get a bit tricky. Most modern browsers (Firefox, Safari, Opera, Chrome) support a load event on “script” elements. This is an easy way to determine if the script is loaded:

Javascript scope

ref – http://www.w3schools.com/js/js_scope.asp
ref – https://stackoverflow.com/questions/17279437/lexical-scope-closures-in-javascript
ref – http://adripofjavascript.com/blog/drips/emulating-block-scope-in-javascript.html
ref – https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/

JavaScript has two scopes: global and local.

variables declared outside of your function…

Any variable declared outside of a function belongs to the global scope, and is therefore accessible from anywhere in your code.

variables declared inside of your function…

Each function has its own scope, and any variable declared within that function is only accessible from that function and any nested functions.

Because local scope in JavaScript is created by functions, it’s also called function scope. When we put a function inside another function, then we create nested scope.

Currently, JavaScript, unlike many other languages, does not support block level scoping. This means that declaring a variable inside of a block structure (like a for loop), does not restrict that variable to the loop. Instead, the variable will be accessible from the entire function.

It’s worth noting that the upcoming ECMAScript 6 will support block level scopes via the let keyword.

Lexical Scope

In Paris, I want to print “myFriend”. So I start my searching from there. When I can’t find her in Paris I go one level up and expand my searching in all of France. But again, she is not there. Next, I expand my searching again by going another level up. Finally, I found her in Italy, which in our case is the local scope of Europe.

In the previous example my friend Monique is represented by the variable myFriend. In the last line we call the europe() function, which calls france(), and finally when the paris() function is called, the searching begins. The JavaScript interpreter works from the currently executing scope and works it way out until it finds the variable in question. If the variable is not found in any scope, then an exception is thrown.

This type of look up is called lexical (static) scope.

The static structure of a program determines the variable scope. The scope of a variable is defined by its location within the source code, and nested functions have access to variables declared in their outer scope. No matter where a function is called from, or even how it’s called, its lexical scope depends only by where the function was declared.

Shadowing

If you declare a local variable and a global variable with the same name, the local variable will take precedence when you use it inside a function. This type of behavior is called shadowing. Simply put, the inner variable shadows the outer.

That’s the exact mechanism used when a JavaScript interpreter is trying to find a particular variable. It starts at the innermost scope being executed at the time, and continue until the first match is found, no matter whether there are other variables with the same name in the outer levels or not.

Additional Material

To put it simply, a scope is the lifespan of a variable. You see, every variable is born, lives and dies. The beginning of a scope marks the time the variable is born and the end of the scope marks the time it dies.

The scope in the previous example was a block scope. It’s just a block of code. Hence the name. Block scopes are immediately executed.

Function scopes on the other hand are templates of block scopes. As the name suggests a function scope belongs to a function. However, more precisely, it belongs to a function call. Function scopes do not exist until a function is called.

Using var, JavaScript only has function scopes. Using let, it has block scopes.

If we are not using let, we can use IIFE to emulate block scoping.
Let’s take a look at an example.

Simulating block scoping with IIFE (Implicit Invoked Function Expression)

In the global scope, we have variables avatar, element, and an array elements.

Then we have a for loop, which is a block. However, before ‘let’, JS do not have block scoping.
Any variables declared inside a block, is scoped to the nearest function.

In JavaScript, variables declared with var are scoped to the nearest parent function.

Hence in our case, when we declare “var element”, it gets scoped to the nearest parent function.
Since element was already declared, the element in the for loop block reference the element in its parent scope. That’s why after the for loop,
var element will have “Water”.

And the output would be: “Ang’s primary element is Water”.

Solution

What we expect is element to be “Air”. Hence, in order for this to happen, we must imitate block scope by using
IIFE like so:

So what we did here is that in the for loop. We first defined an anonymous function.

When the function is defined, a closure is created. It can reference its own scope, parent’s scope, and global scope.

For example, the elements array can be accessed as it is its parent’s scope.

Notice the anonymous function has () at the end. This is executing the anonymous function. We we execute the function, scope is created. This means at the start of the function execution, variables is alive, and when the function exists, the variable die.

Since variables declared with var are scoped to the nearest parent function.

The var “element” is scoped to our anonymous function.

That’s why var element only exists here. For every pass of the loop, we have a scope with its own variable element.

That element references global scope var “elements”.
It logs it, then exits.

When we are done with the for loop, our scope is global, where element still has data “Air”.

The Lifetime of JavaScript Variables

The lifetime of a JavaScript variable starts when it is declared.

Local variables are deleted when the function is completed.

Global variables are deleted when you close the page.

local scope

Variables declared within a JavaScript function, become LOCAL to the function.
Local variables have local scope: They can only be accessed within the function.

Local variables are created when a function starts, and deleted when the function is completed.

global scope

A variable declared outside a function, becomes GLOBAL.
A global variable has global scope: All scripts and functions on a web page can access it.

auto global

Automatically Global

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.

This code example will declare carName as a global variable, even if it is executed inside a function.

Global Variables in HTML

With JavaScript, the global scope is the complete JavaScript environment.
In HTML, the global scope is the window object: All global variables belong to the window object.

self invoking anonymous functions

ref – https://sarfraznawaz.wordpress.com/2012/01/26/javascript-self-invoking-functions/

Self-Invoking Anonymous Function

A self-invoking anonymous runs automatically/immediately when you create it and has no name, hence called anonymous. Here is the format of self-executing anonymous function:

You must be aware of the fact that javascript functions run immediately when you put () after their names eg:

doStuff(); // this will run immediately
And:

doStuff; // this will not run immediately and can be used as callback

Now because () exist at the end of self-executing anonymous function above, it will run immediately.

How do they run automatically?

This can be best explained through an example. Let’s say in your webpage you have this javascript code:

When you visit the page, the showUp function will not get triggered unless you do so by calling the function:

However, you can make the function auto-run by making it self-executing function like this:

Where to use self-executing functions?

One obvious situation is when you want to auto-run a function like I showed in above example but that is trivial. If you are in a situation where you want to run a piece of code repeatedly like updating something in the database based on user interaction or fetching records from database every 10 seconds or you want to load new stories via ajax similar to how facebook does on its homepage or some other similar situation, one would normally go for setInterval function something like this:

Above, doStuff function will get called every 10 seconds. That is the normal approach most developers seem to go with. However, there is a huge problem with that. The setInterval will call doStuff function exactly at specified time of 10 seconds again and again irrespective of whether doStuff function actually finished doing what it is supposed to do. That is bad and will certainly get you into unexpected results.

That is one example of where setInterval is ^bad^ and should be avoided.

This is exactly where self-executing functions come in handy. We can do the same task with the help of self-executing function along with setTimeout like this:

This code will also repeat itself again and again with one difference. setTimeout will never get triggered unless doStuff is finished. A much better approach than using setInterval in this situation.

Closures example

ref – https://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/

Every JavaScript function forms a closure on creation.

Thus, the add variable takes on a function closure. A closure is a function to which the variables of the surrounding context are bound by reference.

In our example, variable counter is declared within the function. And this variable is accessed via reference inside of our return function where counter is incremented.

Keep in mind that the return function acts as a template. When we press the button, the onClick event is passed and it calls add(). The add() then calls the return function. Therefore, the counter references the counter variable within the scope of the function definition.

Problem Example

Let’s take this example.

When the function definition is declared, it runs the variable i in its scope as it is assigning the array to the functions like this:

fns[1] = (function(n)…
fns[2] = (function(n)…
fns[3] = (function(n)…
fns[4] = (function(n)…

When we do call the adder function, the inner function acts as a template:

fns[1](7),

But here’s the problem. fns[1] = i+n, where n is 7 that we pass in.
But the i here is referencing its scope’s i, which is actually 4 now. Because previously, when the for loop is assignin fns[i] to the function definitions, the i loops out at i = 4. Thus, when we call it later, the i is referenced as 4.

Hence fns[1](7) = 4 + 7 = 11.

Possible Solution

Since every function invocation takes place in a unique execution context, what we can do to fix the problem so that adders[1][7] = 8, is to wrap a funcition around it like so:

This still assigns the function definitions to fns[i] from 1 to 3, but the difference is that in the return i + n, the i references the function’s scope i.

This means that which at the time of assignment, whatever number is being used in the parameter of the function closure, is whatever i will be used in the return i + n.

thus, fns[1](7) = 1 + 7.

Node: Passing client side data to server side (Async)

req.query is the query string sent to the server, example:

req.query will return a JS object after the query string is parsed.
for example:
/user?name=tom&age=55 – req.query would yield {name:”tom”, age: “55”}

req.param is the parameters passed to the handler.

app.get(‘/user/:id’, handler);, going to /user/blah,
req.param.id would return blah;

In the example, we have a contact form where there are textfields and a button.

The button id is #send_email, which we bind a click event to it.
Once that button is clicked, we come to the ‘click’ event handler for #send_email and then get all the value from the textfields by using val().

Once that’s done, we want to give the contact data to the server and GET us a response saying the data has been sent to an email box. Hence we use jQuery’s GET function where:

1) we give it the URL we want to access
2) the object with the data
3) completion function definition

We check to see if the result says ‘sent’. If it does, we know that the server have successfully sent it. If not, we know something went wrong and it has not been sent.

.html file

Once the $.get method fires in the .html file, we come to the ‘GET’ handler in our server code.
From there you access the object data that’s been sent by the client’s jQuery $.get method by using req.query.—-, where —- is the key.

server.js

….
….
somewhere after you do your processing, you need to send back a confirmation. We do this using res.end() and whatever object you use will be checked by your client’s jQuery’s $.get completion function definition(3), as listed above.

Note req.end:

With http.request() one must always call req.end() to signify that you’re done with the request – even if there is no data being written to the request body.

Using HTML template in Node JS

If you want to use the standard HTML templates in your Node JS app without Jade, you use path to get the location of where you are located.

Then use __dirname to get your root directory name, the one where your project resides. Then we simply append our folder locations.

Also be sure to use express.static to append folder so that you can access them. They are public.

Prototype Pattern js

ref – https://carldanley.com/js-prototype-pattern/

when to use dispatch_sync

reference
http://stackoverflow.com/questions/4607125/using-dispatch-sync-in-grand-central-dispatch
http://stackoverflow.com/questions/9471420/whats-the-benefit-of-using-dispatch-sync-if-it-has-to-wait-until-the-main-threa?lq=1

First, let’s look at dispatch_async

You use dispatch_async to create a new thread. When you do that, the current thread will not stop.

That means:

Do More Stuff may be executed before Do something else finish.

What happens if you want the current thread to stop

You do not use dispatch at all. Just write the code normally

//Do something
//Do something else
//Do More Stuff

Now, say you want to do something on a DIFFERENT thread and yet wait as if and ensure that stuffs are done consecutively.

There are many reason to do this. UI update, for example, is done on main thread.

That’s where you use dispatch_sync

//Do something
dispatch_sync(queue, ^{
//Do something else
});
//Do More Stuff

Here you got

  1. Do something
  2. Do something else
  3. Do More stuff done consecutively

…..even though //Do something else is done on a different thread.

Usually, when people use different thread, the whole purpose is so that something can get executed without waiting.

An Example of using Dispatch_Sync

Say we have a mutable array.

We then create a custom queue q in order to take tasks to execute.

We throw some blocks on this custom queue q and process it via asynchronously via dispatch_async.

Now, say, we want to pull the first item off of the array. Then shift all the items over 1 spot to fill in the empty space. Hence, we’re rearranging all this data on the array….we can’t be letting other threads touch this array (i.e adding, deleting, updating…etc)

We gotta stop all activities on the queue that’s adding stuff to our array. That queue is q so we gotta synchronous on it.

We take off the 1st item like so:

We sync our taking off the 1st item with the other tasks in the queue. In other words, we make other tasks wait, execute taking off the 1st item, and let others continue.

Thus, this is an example of why we use dispatch_sync. We when we use sync, we block all other tasks on that queue. Let us finish our block. Then let the other tasks on that queue continue.

One More!

dispatch_sync does what you think — it posts the block to the nominated queue and blocks the current queue until the block has been performed. The main queue/thread isn’t specifically involved unless you’re either dispatching to it or from it.

So, you’d generally use it if an operation had to be performed on a different queue/thread — such as a SQLite or OpenGL operation — but you either needed the result of the operation or simply needed to know that the operation was complete for functionality terms.

The pattern:

is better practice but isn’t really something you can just glue on at the end.