Creating your own JavaScript Library – part 2 – Event Handling

write-your-own-javascript-libraryIn Part 1 of Creating your own JavaScript library, we cover the library essentials: library design, creating a solid object constructor, and adding functions by extending the object prototype. This post focuses on extending our basic library with event handling.

Out of the box event handling can be accessed  through Javascript and DOM apis, shown in the first 3 examples:

Simple event handling:

Assigning functions to events this way can be problematic, as only one function can be assigned at any given time. Mozilla Developer Network recommends that the addEventListener method be used instead, because of its flexibility.

Better Event handling

The addEventListener method accepts three parameters:

Assigning an anonymous function:

We can easily wrap this built in functionality with our library by creating a click function with a parameter that is passed to this native DOM event. This parameter will be an anonymous function (like the previous example) that will then bound to the element’s handler.

Handler wrapped by our library:

This pattern can be applied to any event natively exposed, such as:

  • onclick
  • onmouseover
  • blur
  • keydown

Non-standard or browser specific events

In the case where one browsers event api differs, it is simple to account for this in our event handler:

Optimizing our code

Instead of duplicating the addEventListener code in each event wrapper, we can optimize by creating an internal addListener(event, callback) function which will be called by other exposed functions, such as click, onMouseOver, etc

This separates the public wrapper from the internal event binding, allowing us to easily modify or expand the actual event binding code without modifying it in numerous places

 

Software Engineering principles applied to CSS

Some of my thoughts about CSS developent. Think of more? Share in the comments and I’ll add them to this page!

Low Coupling

The principle of low coupling suggests that distinct parts of an application be as “stand-alone” as possible.

To illustrate: A very decoupled program could be available from the command-line first, then a GUI is built using that programs API’s. This ensures that the logic of the program is decoupled from the presentation. A developer can change the internal workings of the program without affecting the other aspects of the architecture.

Targeting elements based on their DOM order tangles up the visual presentation (CSS) with the structured content (HTML) – Highly coupling the presentation with the content.

Changing the name of your parent container shouldn’t detach your horizontal menu from its style.

Separate the presentation from the structure with the use of classes:

High Cohesion

Separating the concerns of CSS into different files allows you to create highly cohesive classes that, once in place, allow a great deal of flexibility in development. Areas of concern are:

  • Layout: positioning of elements, geometric dimensions
  • Style: colors, borders, backgrounds
  • Normalization: typography, element defaults

Separating the CSS into separate areas allows you to create highly cohesive “modularized” rules that have the bonus of being easily swappable:

  • Layout-full.css, layout-compact.css
  • Blue.css, green.css, red.css
  • Normalize.css

Any combination of the above files could be used to alter the presentation of the application without changing the content architecture.

Inheritance

If elements are targeted by semantic classes, instead of their order in the DOM, it is easy to modularize classes using the principle of inheritance:

This is a popular technique in many rapid development frameworks, such as Bootstrap, Zurb, and others.

Additionally, CSS may use the principle of multiple inheritance by using styles from multiple sources – such as a horizontal navigation getting its form and function from layout.css, and its color and branding from color.css files.

Generalization

In software engineering, the most general use-case is often sought, as it will eliminate redundant future work. Nathanial Borenstien, inventor of the MIME type once said,

“It should be noted that no ethically-trained software engineer would ever consent to write a DestroyBaghdad procedure. Basic professional ethics would instead require him to write a DestroyCity procedure, to which Baghdad could be given as a parameter.”

Name classes based on their general use-case, rather than on their appearance, position, or other attribute.

If not, ‘The boss’ might ask you to change the submit button to green, but the in-code class will stay .button-blue  forever, because it is already in hundreds of places.

Naming classes on their general case avoids this problem, and also makes for easy discovery and maintenance by future programmers, or your future self.

Additionally, duplication of elements becomes easier. If not, you might need to duplicate the element somewhere other than the original place, and you end up with navigation in the footer called  .sidebar-nav

Abstraction

If using the principle of generalization, there may be some base class that is never intended to be used on an element on its own. To provide some level of abstraction, only declare universal attributes on parent classes.

Encapsulation (private styles)

By using the principle of inheritance, we can make some classes essentially private by namespacing their selector rules:

This ensures our style definitions don’t ‘leak’ into other elements, and can only be used within a specified parent element.

Custom events system in JavaScript – LightEvents.js

Needing an event subscription and publishing system for a HTML5/canvas game I’m creating, I wrote a very light event system.

Anything than can call JavaScript (link, button, etc) can raise an event:

LightEvents.publishEvent('event name', data);

Subscribing to events is equally easy:

Here is the LightEvents object, demo is embedded below

JS Bin

Quick and reliable ad-rotator

In the course of my work, I’ve created and refined a simple ad rotator. It is built in JavaScript, and does not rely on any library, like jQuery, to function.  In my experience, it defeats ad-block, and loads easily on all mobile, tablet, and desktop browsers.

The rotator can be included multiple places on one page without any conflicts or collisions, so just drop-in where needed. Some coding is required to customize — basically copying and pasting your links and image urls, but nothing too heavy.

 

asp.net – getting user confirmation before a postback

In asp.net web applications, it is common to have dozens — if not hundreds — of user controls that perform postbacks to the server, actions initiated by a user such as a button click. Often before a save, delete, or other critical action is performed, it is desirable to ask the user if they are sure.

In Asp.net web applications, buttons and other controls have two event properties that we are concerned with: onClick , and onClientClick .

The onClick event calls a specified function in the code-behind file. At this point, the postback has occurred, and any confirmation would have to take place with another rendered page — meaning lots of wasted time and wasted resources.  With the onClientClick event, we can interrupt the onClick event with our own javascript function or inline statement.

Using jQuery, we can bind function to all of these “confirm-able” user controls, which will interrupt the default post-back behavior  presenting users with a confirmation dialog box:

Using this method, we can target all user controls with the CSS class confirm. Additionally, if we wanted a broader reach, we could modify the jQuery selector to  input[type=button] or for all buttons, or all links.

The confirm box  var response = confirm("Are you sure?"); used in this example is a default JavaScript confirmation dialog box — which will be rendered differently per browser or platform — but you could easily swap this for any other confirmation script or function that returns a boolean value.

Creating a microformat / richsnippits resume

What are microformats?

Microformats are small patterns of HTML to represent commonly published things like peopleeventsblog postsreviewsand tags in web pages.

Microformats are the quickest & simplest way to provide an API to the information on your website. See what else you can do with microformats.

Have you ever searched for a recipe on Google, and wondered how the highlight data like ingredients or cook time on the search results? Microformats. Or, wondered how they can aggregate reviews, locations, and prices for a restaurant search? Microformats.

Make your resume semantically searchable and available by implementing microformats.

There are several types we will implement from the microformat standard, schema.org, for fields on our resume:

  • http://schema.org/Person
  • http://schema.org/PostalAddress
  • http://schema.org/CollegeOrUniversity
  • http://schema.org/Organization

Resume Sample

View the resume here, and a Google’s report on extracted data here.

 

Full-adders, 32-bit adders in JavaScript

Full-Adder circuit diagram
A Full-Adder, courtesy of the Wikimedia Commons

Fascinated by a lecture as part of my CS degree pursuits (there is light at the end of the tunnel!), I  decided to build some digital circuitry beginning with logic gates and ending with a full 32-bit adder. LIVE DEMO

So here’s my question: I’ve got a 32-bit adder… What now?

Beginning with basic AND, and OR functions, (&& and || operators are native to JavaScript), I built a simple XOR function — which is the first building block not built in to JavaScript:

I wanted each gate/function to work with simple Boolean values, as in JavaScript 1==True, 0==False can get a bit messy. For formatting reasons, I return each value + 0, so they results of higher order circuits are displayed numerically in   binary, rather than a series of True, False’s

After implementing, these foundational gates, I coded up a full adder:

 Within the returned object, “c” represents the carry, and “s” represents the sum. Information about how adders function can be found at this great Wikipedia article.

While there are more complex versions, a simple 4-bit adder is just 4 full-adders daisy chained together which each carry leading into the next adder. The final carry is returned from the 4-bit adder:

16, and 32 bit adders function in the same way: several smaller units daisy chained together, returning the final carry along with the sum:

The functions can be used like so:

So here’s where you come in: What do I do with a 32-bit adder, other than build a 64-bit adder?

Horizontal vs. Vertical button groups

Button groups are an important part of user interface design, but choosing their orientation can often be difficult. I’d advocate that horizontal groupings are better in most cases — consider this:

Imagine that each element on the page is assigned a “Danger Zone” — and area where within one unit of margin of error,  an undesirable action will occur. In mobile interfaces, this unit is the width of a finger, or the accuracy of a touch on the device.

Horizontal vs Vertical button groups
The orange area represents the “Danger Zone”

The danger zone in button groups extends along the edge of the button that is touching another item. As represented above in orange, the danger zone for a vertical button group extends across the width of each button — covering nearly 50% of the surface. This reduces the touch-safe portion of the button to a slim area, greatly diminishing the effect of “friendliness” in the minds of the users. Clicks to these buttons must be precise, and the consequence is not just the inconvenience of a missed button, but the danger of a click on the wrong one.

Consider the horizontal button group: the danger zone only extends over a small percent of each button. Users can click or touch imprecisely and without stress. Additionally, horizontal button groups easily convey a “forward” and “backward” action, which lends itself well to buttons like Save or Cancel.

One major offender is jQuery Mobile — arguably the defacto  standard framework for mobile development. By default, button groups in jQuery Mobile are vertically oriented. Although it is simple to switch the grouping to horizontal, some are under the false impression that the default option is the best choice.

jQuery Button Groups
How easy is that to “Fat Finger”?

Interesting interview question #1

During an interview (for a software developer position) with a major employer in the state of Utah, I was asked an interesting programming question:

Create a function that, given an integer parameter, will return the middle three digits

I mentally wiped the sweat away from my forehead: whew — not computing bigO notation,  inventing a new search algorithm, or performing my favorite song!

I verbally walked through my thought process:

There will be a need for some looping to trim off the first and last digit of the integer each iteration — perhaps a while loop with the condition that the value is greater than 99? No, there is a better way: I’ll trim the digits recursively.

I asked for some feedback on my thought process, then set out writing some code. I came up with something like this:

“Nice solution,” the interviewer replied. “How will your function handle 4501?” Uh-oh: It will trim 4 and 1, and return 50. “Hmm… What about 40251?” Darn: It will trim 4 and 5, recursing on 025, which will be interpreted as 25 and fail.

So, as it turns out, programming questions in interviews might not be about creating the elegant, recursive solution — but about asking the right questions. Thorough requirements gathering.  Lesson learned.

After the interview, I couldn’t get the question out of my mind, and spent some time giving it a proper solution: handling input less than 999, error-ing on even values (finding the middle three of an even digit value is a somewhat undefined behavior), and polishing it off with some unit testing.

See a live version here

 

From College Publisher to WordPress: My own daily WTF

Up until June 2011, The Signpost (Weber State University’s student news organization), was hosted by College Publisher — A content management system designed for university newspapers like The Signpost. In June 2011, the paper made the jump to WordPress.

The first order of business was to import past stories from College Publisher into our new WordPress hosted site. Easy right? Get a SQL dump from CP, format the columns for the WP database, upload the new SQL file. Bada-boom bada-bing. If only…

After waiting nearly two weeks for a response from College Publisher, they provided us with a temporary FTP site which contained the archived file export:

Oh, Jupiter! Why?!
Oh, Jupiter! Why?!

 

Working with large Excel files can be difficult, working with nearly 4 GB excel files can be damn near impossible — especially when working on a office computer with 4 GB of of memory. After closing all non-essential processes, I was able to open up the file — only to find 60,00 rows — many of which contained classified ads that were stored with stories, incomplete records, and other corrupted gobbledygook.

Sorting by story size, and filtering my some key words, allowed me to filter out 20,000 bogus records — bringing the Excel file down to about 40k. Upon further inspection, nearly all of these remaining stories contained duplicate headlines. A typical duplicate set contained 4 records, one of which being the whole correct story.

40k records, with 4 duplicates per unique story leaves 10k unique stories — more stories than would be feasible for one individual to sort through in a reasonable amount of time.

The eventual solution? I created SQL insert scripts from the Excel file and imported them into a MySql database. Then I whipped up a PHP  application that allows searching by article title, author, and body content. Duplicates are displayed to the user, along with a Reddit-esque voting mechanism for voting correct stories up, and bad ones down. As prior authors search for their old work, they improve the system — “crowd sourcing” the work or filtering out bad data. To date, 7,810 records have been voted up or down — 18%.

Thanks, College Publisher!

Oh, and as far as importing the stories into WordPress? I guess we can tackle that in another few years when the archives have been filtered.