• Shortcuts : 'n' next unread feed - 'p' previous unread feed • Styles : 1 2

» Publishers, Monetize your RSS feeds with FeedShow:  More infos  (Show/Hide Ads)


Date: Thursday, 23 May 2013 04:37

SenchaCon 2013

There are a handful of outstanding front-end development organizations and Sencha is right at the top of them.  Sencha has done some incredible work, all the way back to the ExtJS days to the modern day Sencha Touch library.  Sencha continues to push the limits of front-end web development and performance, as evidenced by last year’s revelation FastBook.  Mark Zuckerburg claimed HTML5 wasn’t ready so Sencha shocked the industry with a world class, performant Facebook app.  In short:  Sencha doesn’t mess around.

SenchaCon 2013 is coming up in Orlando, Florida on July 16-19 at Walt Disney World Swan & Dolphin.  This epic conference is a front-end developer’s dream, covering HTML5, mobile, JavaScript, performant practices, and more.  Sencha promises:

  • Get the inside track on Sencha’s New technologies
  • Spend 3 days in 60+ sessions on Sencha tools & frameworks
  • Interact with HTML5 experts, Sencha engineers & fellow developers
  • Show off your coding skills during our full-day hackathon
  • Network and enjoy yourself with your peers at SenchaCon’s kickass parties

SenchaCon is a premier front-end event, and it’s exactly what you’d expect from a Sencha.  If you love front-end development and can make it to Sencha Con, be sure to get there!

Read the full article at: SenchaCon 2013: Live Like a Rock Star

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "Events"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 22 May 2013 15:42

CSS is becoming more and more powerful but in the sense that it allows us to do the little things easily.  There have been larger features added like transitions, animations, and transforms, but one feature that goes under the radar is generated content.  You saw a bit of this with CSS counters, where we used the counter and counters expressions to set the content of a given element.  There’s another expression, attr, that allows for CSS-based content creation as well. Let me show you how attr an content can work together!

Basic content Usage

The content property allows the developer to statically or (somewhat) dynamically set the content of a pseudo-element:

.myDiv:after { content: "I am hardcoded text from the *content* property";  }

Remember to make the element (not the pseudo-element) position: relative if you plan to absolutely position the pseudo-element.

content and attr

In the case that you’d like to use an element attribute as content (this being the dynamic usage of content), you may do so with the attr expression:

/* <div data-line="1"></div> */

div[data-line]:after { 
	content: attr(data-line); /* no quotes around attribute name! */
}

attr is typically used with custom data- attributes since traditional element attributes are good for functionality but not so much or text presentation.

content Concatenation

Concatenating strings is done via simple spacing:

/* <div data-line="1"></div> */

div[data-line]:after { 
	content: "[line " attr(data-line) "]"; 
}

Trying to concatenate via JavaScript “+” or any other symbol will bomb … not that I found that out the hard way or anything…

The ability to use generated content with an attr expression is quite exciting.  You can see this used within PrismJS’ line-highlighting plugin and a line-number plugin I’ll release soon.  These generated content tactics make pseudo-elements all the more valuable too!

Read the full article at: CSS content and attr

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "CSS"
Comments Send by mail Print  Save  Delicious 
Date: Monday, 20 May 2013 12:57
Mighty Deals - WordPress Shortcodes

A while back I wrote a post about WordPress Shortcode creation.  Shortcodes are convenient and useful on so many levels and for so many levels of skilled WordPress users.  A basic user can quickly learn shortcodes, as can an expert-level developer.  In short, shortcodes are an invaluable tool for all levels of WordPress user.  Mighty Deals is offering a WordPress plugin containing 5,000 WordPress shortcodes plus three bonus themes for less than $20.  Shortcodes include:

Buttons
Hate the same old buttons you have on your site? No worries. Choose from literally hundreds of CSS3 button variations to add to your page. You can even alter the icon, color and size of each one.

Tooltips
Want to convey a lot of crucial information without busying up your page? Tooltips let you do just that with a small layer that pops up when moused over. Choose from a large variety of CSS3 tooltips and customize the color, pick the direction, and even embed images and videos right in there.

Image Shadows
You can add a touch of oomph to all your photos by putting an extra 3D shadow on each image. Quick and easy to implement on any images within your blog.

Content Info Boxes
You want boxes? You’ve got boxes! Choose from a huge selection of content info boxes that can include icons, pictures, links, and even a video.

Pricing Tables
Looking to show off prices for your product or service? The sleek pricing table will fit any blog design no matter if your site is a corporate or personal one.

Quotes
Display huge pull quotes easily to make important content truly stand out. Justify your text with left, right, and full alignments.

Highlights
Colorful highlights can display key words or phrases throughout your page. Customize each highlight with any color you can imagine.

Accordion
Organize large blocks of text into smaller pieces of content with toggable sections that slide open to reveal text when users click on each section.

Tabbed Content
Go ahead and add vertical or horizontal tabs to your content to further organize things for your users.

Custom Lists
Choose from a variety of fresh icons to spice up your unordered lists.

Columns
Want to break you content into columns for better flow? Choose from a variety of column options to suit your needs.

If you run a WordPress-powered website, you may want to consider this package; it may contain dozens and dozens of shortcodes that make your job much easier!

Read the full article at: Mighty Deals: WordPress Shortcodes Plugin + 3 Premium WP Themes

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "Sponsored"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 16 May 2013 20:18

Windows 8 allows for adding websites as apps (or maybe “bookmarks” is a better term) to the home screen, much in the vein that iOS allows users to do the same.  Like iOS devices, Windows 8 allows  users to accomplish this same task using custom META tags embedded within the page HTML:

<meta name="msapplication-TileColor" content="#FF0000" />
<meta name="msapplication-TileImage" content="/windows8-icon.png" />

The image size should be 144×144 and you’ll want to define a custom background color with the META tag above.  Tags like these are invaluable — very little HTML to add but a giant convenience to users.  Remember that the easier it is to get to your site, the more likely they will come back often!

Read the full article at: Windows 8 Pin METAs

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "Markup, Microsoft, Mobile"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 16 May 2013 14:53

One problem I’ve seen on occasion is that button heights in Firefox are a few pixels larger than in other browsers.  This can be a nightmare when trying to unify the size of buttons with an A elements, as we found out when implementing a new feature on MDN:

Firefox Button Bug

The middle element is an INPUT and the others are your basic A element.  You can see that the INPUT element is just slightly bigger — enough that it annoys anyone with a sharp eye.  This StackOverflow post mentions a solution that includes ::-moz-focus-inner:

input::-moz-focus-inner { 
	border: 0; 
	padding: 0; 
}

This snippet helps but doesn’t completely fix the problem — the INPUT is still just a tad too big.  The Stackoverflow post mentions box-sizing but that doesn’t help.  After trying a few different solutions, I finally found one that works:

input::-moz-focus-inner { 
	border: 0; 
	padding: 0; 
	margin-top:-2px; 
	margin-bottom: -2px; 
}

Setting negative margins within the ::-moz-focus-inner brings the buttons down to correct height, and as a bonus, the text sits the proper position:

Firefox Button Bug Fix

The ultimate solution is a bit vomit-inducing, and you may need to adjust the negative margins to your specific use case, but the solution works and doesn’t cause problems for other browsers!

Read the full article at: Firefox Button Height Fix

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "CSS, Quick Tips"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 15 May 2013 12:01

Counters.  They were a staple of the Geocities / early web scene that many of us “older” developers grew up with;  a feature then, the butt of web jokes now.  CSS has implemented its own type of counter, one more sane and straight-forward than the ole “hit counter.”  CSS counters allow for simple CSS-based incrementing and display of a number for generated content.  Let’s have a quick look at how CSS counters work!

Initializing the CSS Counter

For the sake of semantics, let’s displays a series of slides using <OL> and <LI> elements for our counter example.  The first step is resetting the counter, providing the specific counter a name initializing it to 0:

ol.slides {
	counter-reset: slideNum;
}

The counter name slideNum will be used throughout the example.

Incrementing the CSS Counter

To increment the counter, use the counter-increment property and the counter name created in the first step:

ol.slides > li {
	counter-increment: slideNum;
}

Each counter-increment call continues to increment the counter.  Be aware that you must use > in your selector if you have nested lists so that your list numbering doesn’t get incremented at the wrong points.

Using the Counter Value

Counters aren’t much good if you can’t display them (just like in 1995!), so the counter() command will output the counter value when used with the content property:

ol.slides li:after {
	content: "[" counter(slideNum) "]";
}

Oddly enough, counters can also be nested by using a second argument to counter, which will act as a separater:

/* assume this HTML:

<ol class="toc">
	<li>Intro</li>
	<li>Topic
		<ol>
			<li>Subtopic</li>
			<li>Subtopic</li>
			<li>Subtopic</li>
		</ol>
	</li>
	<li>Topic
		<ol>
			<li>Subtopic</li>
			<li>Subtopic</li>
			<li>Subtopic</li>
		</ol>
	</li>
	<li>Closing</li>		
</ol>
*/

ol.toc, ol.toc ol {
	counter-reset: toc;
}
ol li {
	counter-increment: toc;
}
.toc li:before {
	content: "(Item " counters(toc, ".") ")";
}

/* visible page "output"

<ol class="toc">
	<li>(Item 1)Intro</li>
	<li>(Item 2)Topic
		<ol>
			<li>(Item 2.1)Subtopic</li>
			<li>(Item 2.2)Subtopic</li>
			<li>(Item 2.3)Subtopic</li>
		</ol>
	</li>
	<li>(Item 3)Topic
		<ol>
			<li>(Item 3.1)Subtopic</li>
			<li>(Item 3.2)Subtopic</li>
			<li>(Item 3.3)Subtopic</li>
		</ol>
	</li>
	<li>(Item 4)Closing</li>		
</ol>
*/

As you can probably tell, counters could be incredibly helpful when it comes to basic count display up to a table of contents display.

After you get over the initial giggle of the the word counter, you start to realize that they can be quite useful.  In most cases, you’ll use counters with :after and :before pseudo-elements, unless you dedicate empty elements to their contents.  I’ve seen counters used in broadcast slides, slideshows, and documentation.  Do you use counters for anything else?

Read the full article at: CSS Counters

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "CSS"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 14 May 2013 14:51

Using utilities likes SASS and Compass have made me me think a lot about how we can improve CSS in the short term.  Of course all CSS proposals should go through the W3C standardization process, but the problem is that those processes take a long time.  We also know that there are a lot of things we know we need in CSS:

  • CSS Variables
  • Nested style blocks (a la SASS, LESS, etc.)
  • Macros / routines

We know we need these things but still don’t have them yet, and likely wont for years.  That got me to thinking about another problem:  the constant need to do the prefixing of properties for every browser, like this mess:

#someElement {
	-moz-animation-name: myAnimation;
	-webkit-animation-name: myAnimation;
	-ms-animation-name: myAnimation;
	animation-name: myAnimation;
}

Firefox has un-prefixed a majority of previously prefixed properties, but we still can’t get away from this mess for other browsers.  So how can we fix this in the short term, besides making browser vendors unprefix?  One idea is doing something kind of like JavaScript’s use strict;  we start our CSS file with something like this comment:

/*autoprefix*/



/* and then somewhere in the CSS file */
#someElement {
	animation-name: myAnimation;
}

If a CSS file started with this CSS comment, the browser would automatically prefix properties that required prefixing.  Since browsers know which properties need prefixing, and they only need to account for their prefix, this type of system would reduce code (and thus smaller/quicker file downloads) and, in theory, be much faster to implement.

Now this isn’t a perfect solution by any means.  It should still be standardized at some point and unfortunately some prefixed properties act differently than unprefixed.  Just a thought that I wanted to share, get some feedback on.  Let me know if you think something like this would work!

Read the full article at: CSS Idea: /*autoprefix*/

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "CSS, Theory / Ideas"
Comments Send by mail Print  Save  Delicious 
Date: Monday, 13 May 2013 14:29

CSS background animation has been a hot topic for a long time, mostly because they look pretty sweet and don’t require additional elements.  I was recently asked if it was possible to have multiple background animations on a given element and the answer is yes…with concessions.  Let’s take a look at how it’s done!

The CSS

So multiple background images on an element is something we’ve been able to do for quite a while now, simply separate them with commas:

.animate-area	{ 
	background-image: url(twitter-logo-bird.png), url(treehouseFrog.png), url(bg-clouds.png);
	background-position: 20px -90px, 30px 80px, 0px 0px;
	background-repeat: no-repeat, no-repeat, repeat-x;
}

Note that the background image that you want at the top of the stack should go first in the image list.  Animating the backgrounds requires moving the background-position, also separated by commas:

@keyframes animatedBird {
	from { background-position: 20px 20px, 30px 80px, 0 0; }
	to { background-position: 300px -90px, 30px 20px, 100% 0; }
}
		
.animate-area	{ 
	animation: animatedBird 4s linear infinite;
}

The result is three moving pieces inside one element!

Of course this isn’t an ideal case because you can’t separately change background-positions and thus you need to work with the same duration for each background image.  Multiple animations can be set on selectors with CSS, but since it’s the one property being changed, we’re just out of luck!

Read the full article at: Multiple Background CSS Animations

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "CSS, CSS Animations, Markup"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 08 May 2013 13:06

There are times when the contents of an external script may want to reference its own SCRIPT tag.  There are times that developers may want to detect attributes of the script tag which act as options for the script; this is a practice that’s been done by the Dojo Toolkit for years.  Lea Verou’s Prism syntax highlighter also uses this practice:

<!-- Traditional Dojo config -->
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.8.3/dojo/dojo.js"
               data-dojo-config="async: true"></script>

<!-- Sample Prism config -->
<script src="prism.js" data-default-language="markup" data-manual></script>

So how are these projects getting the correct SCRIPT tag with which to look for attributes?  Assuming a top-down (not async) load of scripts, the following will get a script its own tag:

/* From in side the script.... */

// Reliably grab my script tag
var script = document.getElementsByTagName("script");
script = script[script.length - 1];

// Check for an attribute/config
if(script.hasAttribute('data-something')) {
	// Do something!
}

Collect the SCRIPT elements up to that point and reference the last one — that’s all you need to do.  Of course we’re living in a mostly async world right now, so to accommodate for those cases, you may need to stick an ID on the SCRIPT element, take a chance matching the SCRIPT by path (a really bad idea), or use a different type of configuration system.

Read the full article at: Referencing a Script’s Own Tag

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "JavaScript, Markup"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 07 May 2013 11:53

Nicholas Zakas sent out a call to Twitter asking developers who use GitHub as a primary CVS to share their working process.  Mozilla uses GitHub for many (if not most, but I can’t confirm that) mission critical web applications so I chimed in on how the Mozilla Developer Network team uses GitHub.  I got many questions about the process from different sources so I thought I would document our process here.

Working Setup

The working process starts with each developer cloning Mozilla’s kuma repository.  The kuma repository includes developer instructions for getting setup with vagrant (recommended) or without.  Kuma is a Python/Django app with a MySQL database backend.  The kuma repository doesn’t include all of MDN’s documentation but that can be provided to developers who ask for it.  The MDN team resides in the #mdn IRC room for questions and planning.  Filed bugs for MDN can be found on Bugzilla.  This information is all you need to know to get started.

Working on Bugs/Enhancements

Let’s say you’re set up and it’s time to work on a bug or enhancement.  The first step is to create a separate feature branch for working on the bug:

# Ensure we're on master
git checkout master

# Create and check out feature branch
git checkout -b bug-title-123456

Putting the bug number in the branch name is especially useful if there are long periods between working on the bug.  With the branch created and checked out, make your updates, additions, and removals.  It’s also important to run tests as you work on the bug.

Submitting Pull Requests

Before submitting a pull request, it’s important to squash commits and rebase on master branch:

# Ensure master is up to date with Mozilla's remote
git checkout master
git pull mozilla master

# Go back to feature branch, squash commits
git checkout bug-title-123456
git merge master
git rebase -i master
git push origin bug-123456

(Note:  I’m not a git legend so there’s a good possibility I’m taking the long route to accomplish this task — if so, let me know)

The code above turns all commits into one commit, so it’s easier to back out if necessary.  We also start commit messages with “fix bug {bug number}” — this allows out post-merge hook to automatically RESOLVED:FIXED the bug in Bugzilla.  If all looks good, submit the pull request via GitHub.

PR and Code Review

Upon submission of the pull request, the code is automatically run through Mozilla’s Jenkins test suite.  If the tests pass, the pull request is technically able to be merged.  At this point, however, a different member or members of the team review the submitted code, making comments on possible improvements or problems that may be come up along the way.  If the submitter needs to make more changes, they should make their commits, squash and rebase again, and push:

git push -f

So that’s the MDN team’s process for managing code on GitHub.  It all seems pretty standard and straight-forward but let me know if you have suggestions or questions.  I like the way things work and the rest of the team seems to as well!

Read the full article at: GitHub and Mozilla Work Process

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "Blog"
Comments Send by mail Print  Save  Delicious 
Date: Monday, 06 May 2013 11:54
Jackson London Walsh

When little Jackson London Walsh was born, I pondered whether we should give him his own Facebook account or simply have my wife and I post to our personal accounts.  We decided to get Jack his own account because:

  1. we want to be able to have photos all go to the same account
  2. we want all of his stuff to be private
  3. we didn’t want to add a bunch of noise to our private accounts for those heartless bastards who don’t care about seeing baby photos all the time
  4. we hope to hand the account over to him one day

Facebook is now baked into iOS’ settings but iOS presently only allows for one Facebook account to be stored.  This initially presented a problem, as we had hoped to quickly take photos and upload to Facebook.  I did, however, find a method to manage multiple Facebook accounts within the app itself.

The key is opening the Facebook app and swiping to the main menu on the left.  Scroll down to the bottom and there’s a “Log Out” item.

Facebook Multiple Accounts

Tap that, confirm, and you’ll be presented with a screen that has a “Continue” button (to log in as the Facebook account tied to your iOS install) an a “(Not You?)” link;  tap that.

Facebook Multiple Accounts

You can then sign in with a different email address and password:

Facebook Multiple Accounts

What a relief that signing in with multiple accounts is possible.  Now we get to post photos of our little prince whenever we’d like!

Read the full article at: Multiple Facebook Accounts on iOS

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "Mobile"
Comments Send by mail Print  Save  Delicious 
Date: Friday, 03 May 2013 12:10

One of the lessor known and used capabilities of .htaccess files is the ability to prepend and append includes to every page request.  Doing so avoids needing to code <?php require('footer.php'); ?> in every template file you wat to use them in.  Here’s the .htaccess code:

# Prepend the file
php_value auto_prepend_file "/dir/path/utilities.php"

# Append file to bottom of page
php_value auto_append_file "/dir/path/templates/footer.php"

Now don’t mistake this post as me telling you to use this strategy;  using this functionality creates a layer of indirection that could confuse a team of developers if they don’t all have a grasp of where automatically included files are coming from.  Just wanted to let you know this was possible!

Read the full article at: Prepend and Append Files with .htaccess

Treehouse

Sencha Conference

Author: "David Walsh" Tags: ".htaccess, Apache / Server, PHP, Quick T..."
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 01 May 2013 23:12
Kyle Simpson getify

If you didn’t already know, I’m a massive fan of Kyle Simpson, also known as @getify.  He’s one of those JavaScript legends you don’t hear nearly enough about.  He’s a pioneer of JavaScript loaders and all around JavaScript badass.  He recently did a series of guest posts for me, centered around JavaScript objects, prototypes, and inheritance:

His posts got loads of attention, feedback, and praise, and that can be nailed down to one reason:  Kyle knows his shit.  Like…he’s really, really good.  Like…if he were a doctor, he could do that can’t-breathe-poke-a-hole-in-their-neck-with-a-hollow-pen-casing thing. Anyways, Kyle has started a You Don’t Know JS Kickstarter project in which he’ll create a series of awesome JavaScript books.  Let him explain:

“You Don’t Know JS” is an exploration of the mysterious, confusing, complex, and controversial parts of JavaScript.

If you write JavaScript for your primary job, odds are, you’re pretty good at it. But honestly, how well do you really know the language? Most of us, myself included, spend years writing JS and never really going beyond a surface understanding. And then we blame our WTF moments on “the bad parts”.

This book series will examine the things that trip up or confound even the most seasoned of JS devs. And I was one of them until (recently) I spent enough time poking at the tough parts to understand them. Now I want to help others see the light, too.

What if you could really deeply know how JS works? Would that change how you view the language? I think so. Really, I do. A big part of why I love JS is that I finally “get it”.

If you liked his awesome JS Objects posts, consider backing his Kickstarter.  You’re guaranteed to learn a lot and every bit helps toward making his books a reality!

Read the full article at: Kickstart Kyle Simpson

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "JavaScript"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 01 May 2013 16:36

We all get a kick out of unicode symbols, as we all saw in my Unicode CSS Classes post, and just as we can use them for CSS classes, we can use them for JavaScript variables and functions as well!  Let’s say you want to shave a few bytes of post-minified JavaScript byes by setting false equal to a variable.  Why not do so by using a unicode variable?

var ಠ_ಠ = false;

if(someVar === ಠ_ಠ) { // If someVar is false...
	// ...
}

Hilarious.  The evil eyes signal a negative result.  What about saving a few byes on true?  The Beatles once said that “All You Need is Love”, so let’s use a heart:

var ❤ = true;

if(someVar === ❤) {
	// ...
}

You can do the same with function names.  Functions can be named after unicode symbols:

function ಠ(arg) {
	// ...
}

Of course all of this is a bit … insane, and you should never use unicode symbols, but nonetheless it’s possible.  Imagine starting a new job and seeing those symbols as meaningful variables — you’d quit immediately!  Hilarious!

Read the full article at: Unicode JavaScript Variables and Functions

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "JavaScript"
Comments Send by mail Print  Save  Delicious 
Date: Monday, 29 Apr 2013 12:34

One of the promises that comes with HTML5 mobile apps, especially those to be featured on Firefox OS, is that your existing web applications, if created properly (feature detection, responsive design, etc.), can be turned into a working mobile application in relatively little time.  And that’s the way it should be, right?  If my app works in the device’s browser, shouldn’t it work perfectly as a standalone app?  Let’s say you have a responsive, well-written website/app and you want to let Firefox OS users experience your work as a first class app;  the following few steps will help you make those Firefox OS app dreams a reality.

Step 1:  App Manifest

The manifest.webapp file is arguably the only real step you need to turn your website into a Firefox OS app.  This manifest should be placed at domain root level:


{
	"version": "0.1",
	"name": "Your App",
	"description": "Your new awesome Open Web App",
	"launch_path": "/index.html",
	"appcache_path": "/offline.appcache",
	"icons": {
		"16": "/img/icons/appicon-16.png",
		"48": "/img/icons/appicon-48.png",
		"128": "/img/icons/appicon-128.png"
	},
	"developer": {
		"name": "Your Name",
		"url": "http://yourawesomeapp.com"
	},
	"installs_allowed_from": ["*"],
	"locales": {
		"es": {
			"description": "Su nueva aplicación impresionante Open Web",
			"developer": {
				"url": "http://yourawesomeapp.com"
			}
		},
		"it": {
			"description": "Il vostro nuovo fantastico Open Web App",
			"developer": {
				"url": "http://yourawesomeapp.com"
			}
		}
	},
	"default_locale": "en",
	"permissions": {
		"systemXHR": {}
	}
}

And make sure to pronounce it properly within your .htaccess file:

AddType application/x-web-app-manifest+json .manifest

This manifest serves as the real app glue — add this manifest and your app is mostly complete.

Step 2:  Offline Cache

The ignorant press has sometimes laughed at Firefox OS because they believe Firefox OS apps need a connection to properly function — not so.  The (admittedly ugly) offline cache API works beautifully on Firefox OS.  Add the following to your HTML:

<html manifest="offline.appcache">

With the pointer in place, you can create your offline.appcache with the list of files to download:

CACHE MANIFEST
# v0.1
/index.html
/css/app.css
/css/install-button.css
/img/offline.png
/img/online.png
/img/glyphicons-halflings-white.png
/img/glyphicons-halflings.png
/img/gradient.png
/js/app.js
/js/init.js
/js/install-button.js
/js/lib/install.js
/js/lib/require.js
/js/lib/zepto.js

Allowing app files to download to the device allow portions of the app to work even when the device is not connected to the internet.

Step 3:  Submit to Marketplace

As Paris Hilton can attest to, overexposure is 90% of success.  Submitting an app to the Firefox Marketplace showcases the app to millions of users around the world!

Stop the clock — that’s all you need to do to make your web application a Firefox OS mobile app.  There’s a Twitter account, “Always Bet on JS”, that makes me think “Always Bet on the Web.”  During every talk I give, I ask attendees “If it works in the device’s browser, why shouldn’t it be a first class app?”  No one is able to tell me otherwise…and they’re right.  We’ve built careers and billion dollar websites for thing long, and they work so incredibly well, why should that change now?  Mobile is a place to extend the traditional model  and Firefox OS makes that easier than ever before!

Read the full article at: Turn Your Web Application into a Firefox OS App in 5 Minutes

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "Firefox OS, Mobile"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 25 Apr 2013 21:17

Background animations are an awesome touch when used correctly.  In the past, I used MooTools to animate a background position.  Luckily these days CSS animations are widely supported enough to rely on them to take over JavaScript-based animation tasks.  The following simple CSS snippet animates the background image (via background position) of a given element.

The CSS

We’ll use CSS animations instead of transitions for this effect:

@keyframes animatedBackground {
	from { background-position: 0 0; }
	to { background-position: 100% 0; }
}

With the animation code in place, now it’s time to apply it to an element with a background image:

#animate-area	{ 
	width: 560px; 
	height: 400px; 
	background-image: url(bg-clouds.png);
	background-position: 0px 0px;
	background-repeat: repeat-x;

	animation: animatedBackground 40s linear infinite;
}

The cloud background image within the sample element will elegantly scroll from left to right over a duration of 40 seconds, seamlessly repeating an infinite number of times.

How epic is it that we don’t need to use JavaScript to manage these animations anymore?  Of course the mess of vendor prefixes to accomplish the animation sucks, but at least the animations are much more efficient and more easily configurable!

Read the full article at: CSS Background Animations

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "CSS, CSS Animations"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 24 Apr 2013 16:18

CSS class name structure and consistency is really important; some developers camelcase classnames, others use dashes, and others use underscores.  One thing I’ve learned when toying around by HTML and CSS class names is that you can actually use unicode symbols and icons as classnames.  Check this out!

The HTML and CSS

There’s only one way to add a classname with HTML so you’ll do it that way, of course:

<-- place this within the document head -->
<meta charset="UTF-8" />

<-- error message -->
<div class="ಠ_ಠ">You do not have access to this page.</div>

<-- success message -->
<div class="❤">Your changes have been saved successfully!</div>

…and there’s only one way to declare styles for a given class:

.ಠ_ಠ {
	border: 1px solid #f00;
	background: pink;
}

.❤ {
	background: lightgreen;
	border: 1px solid green;
}

Wild that you can use unicode classnames for elements, right?  Of course I don’t recommend doing so, but you can if you’d like to!

Read the full article at: Unicode CSS Classes

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "CSS, Markup"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 24 Apr 2013 15:58
Treehouse Free

There are quite a few tech video tutorial websites on the internet but Treehouse is the web’s best.  Of course it’s easy to make that claim but here are some of the numerous reasons why that can only be true.

Trying Treehouse is FREE

Treehouse’s sponsorship of this site provides developers a free month of Treehouse.  A free month with access to all that Treehouse has to offer:  video tutorials, quizzes, code challenges, and more.  There’s no real reason not to try Treehouse — give it a shot!

Expansive Topic Library

Treehouse doesn’t specialize in one or two topics;  Treehouse offers courses in HTML, CSS, jQuery, JavaScript, Ruby, Ruby on Rails, WordPress, PHP, Business, iOS, and Android.  These topics cover servers side, client side, and mobile.  In essence, Treehouse provides a complete development stack experience so the barrier of entry is as low as possible.  You don’t even need to be a Developer to sign up — start from scratch and become a Developer!

Quality Picture

The quality of Treehouse videos is outstanding.  No pixelated capture and no wonky feeds — Treehouse videos are shot in glorious HD.  Even code samples presented within videos are crystal clear.  Essentially there is no detail missed regardless of current video focus.  Consistency in quality is what Treehouse provides.

Relatable, Expert Instructors

Treehouse’s instructors and presenters aren’t simply actors or relics from programming past — they’re knowledgable, engaging hosts that present with the enthusiasm that every developer has.  That simple difference in host keeps you learning.  Even when I’m focused on developing, I’ll play a Treehouse video in the background to catch a few tips on whichever language I choose.

Interactive Quizzes and Code Challenges

It’s easy to read a tutorial or watch an instructional video and say “Yeah, I got it.”  But until you get put into the position to need to know it, you can’t say you know it.  Treehouse provides loads of interactive quizzes and code challenges to help you remember aspects of a given language, or simply jog your memory about important concepts.  That reinforcement will come in handy even when you already have a job and good knowledge of a topic.

Job Search Assistance

Many sites provide the basic tech training but don’t tell you where to go afterward.  Treehouse bucks that trend, providing job placement assistance after you’ve completed a given program.  You aren’t simply left looking in the rearview to see Treehouse waving — Treehouse helps you get to your desired destination.  What a comfort it is to not be seen off, but rather helped to your dream job.

There’s no tech video tutorial service quite like Treehouse.  Treehouse truly takes you from your first day learning a new technology to helping you land that dream job you’ve been working so hard for.  Give Treehouse a try — it’s free to start, cheaper and more convenient than college, and its expansive library will teach you just about everything you need to know.  You really can’t lose with Treehouse — go for it!

Treehouse is a sponsor of this blog. I’ve written this post on my own volition and without the request of Treehouse.

Read the full article at: 6 Reasons to Go Treehouse

Treehouse

Sencha Conference

Author: "David Walsh" Tags: "Blog"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 24 Apr 2013 13:45

JS Objects: TL;DR

JavaScript has been plagued since the beginning with misunderstanding and awkwardness around its “prototypal inheritance” system, mostly due to the fact that “inheritance” isn’t how JS works at all, and trying to do that only leads to gotchas and confusions that we have to pave over with user-land helper libs. Instead, embracing that JS has “behavior delegation” (merely delegation links between objects) fits naturally with how JS syntax works, which creates more sensible code without the need of helpers.

When you set aside distractions like mixins, polymorphism, composition, classes, constructors, and instances, and only focus on the objects that link to each other, you gain a powerful tool in behavior delegation that is easier to write, reason about, explain, and code-maintain. Simpler is better. JS is “objects-only” (OO). Leave the classes to those other languages!

Due Thanks

I’d like to thank the following amazing devs for their generous time in feedback/tech review of this article series: David Bruant, Hugh Wood, Mark Trostler, and Mark McDonnell. I am also honored that David Walsh wanted to publish these articles on his fantastic blog.

Complete Series

In part 1 of this article series (which you should totally go read if you haven’t yet!), I revisited an idea not original to me: JS doesn’t have “inheritance” in the traditional sense, and what it does have is more appropriately labeled “behavior delegation” — the ability of one object to delegate a method or property access which it cannot handle over to another object which can handle it.

Then, in part 2, I addressed several distractions which I think obfuscate JS’s true object-oriented identity, including “custom types”, “mixins”, “polymorphism” (which we’ll come back to again later), and even the new “class syntax” coming in ES6. I suggested that to understand (and leverage) better the [[Prototype]], we needed to strip away the cruft. Here, I will attempt to do that.

Turtles Objects all the way down up

The key realization, the punchline to this entire article series, is that [[Prototype]] is really only about linking one object to another object, for the purposes of delegating, if the first object cannot handle a property or method access but the second can. In other words, it’s only objects, linked to other objects. That’s really all JS has.

In a sense, JS is the purest essence of a “object-oriented (OO)” language, in that it really is all about objects. In contrast to most other languages, JS is somewhat unique that you can actually create objects directly without the notion of classes or other abstractions. That’s a powerful and brilliant feature!

People often bash JavaScript, but it’s one of the few prog languages that let you directly create objects. Others: Lua, Dylan, Cecil.

— Axel Rauschmayer (@rauschma) April 9, 2013

JavaScript legitimately is ”object-oriented”, and perhaps we shouldn’t have used that term for the other languages which imply a lot more than just ”objects”. Maybe “class-oriented” would have been more accurate, which would have freed us up to use “object-oriented” for JS. Of course, as I argued in part 1, what everybody means when they use some term, matters, so it’s far too late to redefine or bend the commonly accepted “object-oriented” to my own purposes, much as I’d like to.

I’m mildly tempted, however, to just hijack the abbreviation of “OO” to mean “objects-only” instead of “object-oriented”, but I bet that probably wouldn’t get anywhere, either. So, for our purposes here, let’s just sayJavaScript is “object-based (OB)” to clarify against “object-oriented (OO)”.

Whatever we call it, we normally tap into this object mechanism by following the “OO way”: we create a function which we use as a “constructor”, and we call that function with new so that we can “instantiate” our “class”, which we specify with the constructor function together with its subsequent .prototype additions… but all that is like a magician’s sleight of hand that dazzles you over here to distract you from what’s really going on over there.

What really matters, at the end of the trick, is that two objects end up linked to each other via the[[Prototype]] chain.

Codez Plz

Before we can derive and understand that simpler view of “objects-only” or “object-based”, we need to understand what actually gets created and linked when we build up some “inherited” objects in JavaScript. Not only are we going to see what happens by default, but what doesn’t happen.

Take this code for our main example:

function Foo(who) {
    this.me = who;
}

Foo.prototype.identify = function() {
    return "I am " + this.me;
};

function Bar(who) {
    Foo.call(this,who);
}

Bar.prototype = Object.create(Foo.prototype);
// NOTE: .constructor is borked here, need to fix

Bar.prototype.speak = function() {
    alert("Hello, " + this.identify() + ".");
};

var b1 = new Bar("b1");
var b2 = new Bar("b2");

b1.speak(); // alerts: "Hello, I am b1."
b2.speak(); // alerts: "Hello, I am b2."

Note: Some people write Bar.prototype = Object.create(Foo.prototype); as Bar.prototype = new Foo();. Both approaches end up with the same linked objects, where Bar.prototype is an object linked via its[[Prototype]] to Foo.prototype. The only real difference is whether or not the Foo function is called during the creation of Bar.prototype. Depending on your circumstances and intent, you may or may not want that to happen, so let’s consider them roughly interchangable but with different purposes.

What we have is an object labeled Foo.prototype with an identify() method, and another object calledBar.prototype with a speak() method. Bar.prototype is a new empty object that is [[Prototype]]-linked to Foo.prototype. Then we have two objects b1 and b2, who each are each respectively linked via their own [[Prototype]] to Bar.prototypeb1 and b2 also have an “owned property” directly on each of them called me, which respectively holds the values “b1″ and “b2″.

Let’s take a visual look at the relationships implied by the above code snippet:

Note: All the [[Prototype]] links in the diagram also mention a “.__proto__” property__proto__ is a formerly non-standard property (which exists in most but not all JS environments) to expose the internal [[Prototype]]chain. As of ES6, however, it will be standardized.

I left a whole bunch of detail out of that diagram, intentionally, so it was even remotely digestable. But of course, since JS is all objects, all the linkages and ancestry of each item can be fully traced. We’ll come back to all the omitted parts of this diagram in a little bit.

Note in this diagram that the function constructors all have a .prototype property pointing at an object. As we’ve been suggesting, the object is what we really care about, and in this way of viewing the JS object mechanism, the way we get that object is to look at a constructor function’s .prototype. The function doesn’t really serve any particularly important role.

I know a whole bunch of you just screamed out, “sure it does! it runs constructor code to initialize the new object!” OK, you’re technically right. Foo() has some code in it which is ultimately run against b1 and b2.

But the devil’s always in the details. First, we don’t need a constructor function to run such code. That’s just one way of getting that outcome. And I’m going to suggest it’s a more distracting approach.

Secondly, unlike C++, the base-class/superclass Foo() ”constructor” doesn’t automatically get called when you run the child-class Bar() ”constructor” to make b1 and b2. So, like Java, we have to manually call theFoo() function from Bar(), but unlike Java, we have to do so with a variation of the explicit “mixin” pattern (I’d probably call it “implicit mixin” here) to make it work like we expect. That’s an ugly detail that is very easy to forget or get wrong.

So, where you’d probably argue with me that “constructor” functions are useful being automatically called at the construction of an object, I’d point out that this is true for only the immediate level, not for the entire “chain of inheritance”, which means that automatic behavior is pretty limited/shallow in utility.

Polymorphism redux

Moreover, we see here the first hint of the problems with relative polymorphism in JS: you can’t do it! I can’t tellBar() to automatically and relatively call his ancestor constructor(s), via a relative reference. I have to manually call (aka, “borrow”) the Foo() function (it’s not a constructor here, just a normal function call!) from inside ofBar(), and to make sure the this is bound correctly, I have to do the slightly more awkward .call(this)style of code. Ugh.

What may not be obvious until you go back and look closer at the diagram above is that the Foo() function isnot related in any useful/practical way to the Bar() function. The Foo() function does not even appear in the “inheritance” (aka “delegation”) chain of Bar.prototype object. The fact that there are some lines you can follow on the graph for indirect relationships doesn’t mean that those relationships are what you’d want to rely on in your code.

The problem with polymorphism we’re seeing here is not only for “constructor” functions. Any function at one level of the [[Prototype]] chain that wants to call up to an ancestor with the same name must do so via this manual implicit mixin approach just like we did inside of Bar() above. We have no effective way of making relative references up the chain.

Importantly, this means that not only do we establish the link between Bar and Foo once at “class” definition, but every single polymorphic reference also has to be hardcoded with the direct relationship. This significantly decreases the flexibility and maintainability of your code. As soon as you make a function hard-coded with implicit mixin to an “ancestor”, now your function can’t be “borrowed” as easily by other objects without those possible unintended side effects.

OK, so let’s say you agree with me at this point that polymoprhism in JS is more trouble than it’s worth. Using constructor-based coding to wire JS objects to each other forces you into the problems of polymorphism.

.constructor

Another detail that’s easy to miss is that an object’s .constructor property really doesn’t behave like we’d probably expect. It’s correct at the Foo() level of the graph, but below that, at Bar() and b1 / b2, notice that the implied linkage there shows .constructor references, strangely, still pointing at Foo.

Actually, what this means is that the only time a .constructor property is added to an object is when that object is the default .prototype attached to a declared function, as is the case of Foo(). When objects are created via new Fn() or Object.create(..) calls, those objects don’t get a .constructor added to them.

Let me say that again: an object created by a constructor doesn’t actually get a .constructor property to point to which constructor it was created by. This is an extremely common misconception.

So if you reference b1.constructor for instance, then you’re actually going to delegate up the chain a few links, to Foo.prototype. Of course, Foo.prototype has a .constructor property and it’s pointing at Foo like you’d expect.

What’s that mean? In the above snippet, right after you perform Bar.prototype = Object.create(Foo) (or even if you’d done Bar.prototype = new Foo()), if you plan to rely on the .constructor property (which many do), you need to perform an extra step, right where I put the JS “Note:” comment:

//...
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.constructor = Bar; // <-- add this line!
//...

Then b1.constructor references will delegate to that Bar.prototype level, and will “correctly” point at Bar()as you’d probably have expected. Ugh…**more syntax gotchas** that user-land libs always have to “fix” for us.

Furthermore, the fact that Foo.prototype has a .constructor property pointing at Foo is strange, when you think about “constructor” the way most people do. It’s nice that it gives objects created by new Foo() a way to delegate to a .constructor property access and find Foo(), but it’s bizarre where .constructor actually lives.

It implies that Foo() constructed Foo.prototype, but that’s nonsense. Foo() had nothing to do with creating the default Foo.prototypeFoo.prototype defaults to an empty object that was actually constructed by the built-in Object() constructor.

So we have to change how we think of what the .constructor property means. It does not mean “the constructor this object was created by”. It actually means “the constructor which creates any objects that end up getting [[Prototype]] linked to this object.” Subtle but super important difference to get straight.

Point? These confusions only happen/matter if you’re using constructor-style code, so it’s the choice of this style of code that opts you into the problems. You don’t have to live with that pain. There’s a better, simpler way!

The Whole Pie

Now let’s look at everything that’s actually implied by the above snippet of code. Ready for the whole messy thing?

Take a few minutes to just take all that in. Why show you such a complex diagram?

This diagram actually shows you where some of JavaScript’s functionality comes from, where before you might have just never considered how it all worked. For instance, have you wondered how all functions are able to use behavior such as call()apply()bind(), etc? You may have assumed each function has that behavior built-in, but as you can see from this diagram, functions delegate up their [[Prototype]] chain to handle those behaviors.

While the behavior delegation part is sensible and useful, consider all the implied complexity of constructor-style coding as visualized here. It’s pretty tough to trace all the different entities and diagrams and make much sense of it all. A lot of that complexity comes from the function constructors. (here’s the same complete graph but with the implied relationship lines omitted, if that helps to digest)

If you take that diagram, and remove all the functions and any associated arrows (which we’ll see in just a moment), you’re left with “objects-only”, and you’ll have a much more simplified view of the JS objects world.

Simpler: Object -> Object

Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away. –Antoine de Saint-Exupery

For refresher, the same prototype-style code from above:

function Foo(who) {
    this.me = who;
}

Foo.prototype.identify = function() {
    return "I am " + this.me;
};

function Bar(who) {
    Foo.call(this,who);
}

Bar.prototype = Object.create(Foo.prototype);
// NOTE: .constructor is borked here, need to fix

Bar.prototype.speak = function() {
    alert("Hello, " + this.identify() + ".");
};

var b1 = new Bar("b1");
var b2 = new Bar("b2");

b1.speak(); // alerts: "Hello, I am b1."
b2.speak(); // alerts: "Hello, I am b2."

Now, let’s instead consider this alternative snippet of code, which accomplishes exactly the same, but it does so without any of the confusion/distraction of “constructor functions”, new.prototype, etc. It just creates several objects and links them together.

var Foo = {
    init: function(who) {
        this.me = who;
    },
    identify: function() {
        return "I am " + this.me;
    }
};

var Bar = Object.create(Foo);

Bar.speak = function() {
    alert("Hello, " + this.identify() + ".");
};

var b1 = Object.create(Bar);
b1.init("b1");
var b2 = Object.create(Bar);
b2.init("b2");

b1.speak(); // alerts: "Hello, I am b1."
b2.speak(); // alerts: "Hello, I am b2."

Let’s try to take some comparison looks between this snippet and the previous one. They both accomplish the same thing, but there’s some important differences in how we get there.

First of all, Bar and Foo are now just objects, they’re not functions or constructors anymore. I left them as capital letters just for the symmetry and because some people feel better with them. They make it clear that the objects being linked are what we cared about all along, so instead of the indirectness of linking Bar.prototype toFoo.prototype, we just make Foo and Bar objects themselves and link themAND, we only need one line of code to link them, instead of the extra ugly polymorphic linkage. Bam!

Instead of calling function constructors like new Bar(..), we use Object.create(..), which is an ES5 helper that allows us to create a new object and optionally provide another object to [[Prototype]] link it to. We get the same outcome (object creation and linkage) as a constructor call, but without needing the constructor. BTW, there’s a simple non-ES5 polyfill for Object.create(..), so you can safely use this style of code in all browsers without concern.

Secondly, notice that because we’re not worried about constructors anymore, we have eliminated any concerns about awkward polymorphisms forcing us to do manual implied mixins to call Foo() from Bar(). Instead, we put the code we wanted to run to initialize our objects into a init() method, on Foo, and we can now callb1.init(..) directly via the delegation chain and it “magically” just works like we want.

So, we have a tradeoff here. We don’t get automatic constructor calls, which means we create the object likevar b1 = Object.create(Bar) and then we have to additionally call b1.init("b1"). That’s “more code”.

But the benefits we get, which I think are much better and well worth it, are no awkwardness with the linkage between Foo and Bar – instead we leverage [[Prototype]] delegation to get at the code reuse ininit(). Also, no more verbose/repetitive .prototype references, and neither do we need to use.call(this) nearly as often (especially if we avoid polymorphism!).

Looks are everything

And to visualize the simplicity this approach brings us, here’s the diagram when we remove the functions entirely and focus only on the objects:

I don’t know about you, but I just think that mental model is so much cleaner, and the bonus is that its semantics perfectly match the code.

I have shown you simple enough code using only core JS syntax, that I don’t need any helper libraries to wire up my objects. Of course, I could use one, but why? Simpler is better. KISS.

Any fool can make something complicated. It takes a genius to make it simple. –Woody Guthrie

For the record, I’m not even remotely the genius here. Brendan Eich, creator of our language, was the genius for making something so powerful yet so simple.

Object self-reflection

Last thing to address: how does this simplification affect the process of reflecting on an object? In other words, can we inspect an object and find out about its relationships to other objects?

For prototype-style code, reflection looks like this:

b1 instanceof Bar; // true
b2 instanceof Bar; // true
b1 instanceof Foo; // true
b2 instanceof Foo; // true
Bar.prototype instanceof Foo; // true
Object.getPrototypeOf(b1) === Bar.prototype; // true
Object.getPrototypeOf(b2) === Bar.prototype; // true
Object.getPrototypeOf(Bar.prototype) === Foo.prototype; // true

Notice that you’re using instanceof and having to think in terms of the constructor functions that made your objects, and their .prototypes, rather than just reflecting on the objects themselves. Each of those reflections comes with slightly more mental tax as a result.

And when there’s only objects?

Bar.isPrototypeOf(b1); // true
Bar.isPrototypeOf(b2); // true
Foo.isPrototypeOf(b1); // true
Foo.isPrototypeOf(b2); // true
Foo.isPrototypeOf(Bar); // true
Object.getPrototypeOf(b1) === Bar; // true
Object.getPrototypeOf(b2) === Bar; // true
Object.getPrototypeOf(Bar) === Foo; // true

By contrast, reflection on objects is only about the objects. There’s no awkward references to a constructor’s.prototype property for the checks. You can just inspect if one object is related via [[Prototype]] to another object. Same capabilities as above, but with less mental tax.

Moreover, as I mentioned in part 2, this sort of explicit object reflection is preferable and more robust/reliable than implicit detection through duck typing.

Object.wrapItUpAlready()

Take a deep breath! That was a lot to take in. If you’ve followed all 3 parts of the article series, I hope by now you see the bottom line: JS has objects and when we link them, we get powerful behavior delegation.

There’s just no need to pile on class-orientation on top of such a great system, because it ultimately just leads to the confusion and distraction that has kept JS’ object mechanism shrouded and covered up by all these helper libraries and misunderstandings about JS syntax.

If you stop thinking about inheritance, and instead think with the arrows headed the other way: delegation, your JS code will be simpler. Remember: it’s just objects linked to objects!

Read the full article at: JS Objects: De”construct”ion

Treehouse

Sencha Conference

Author: "Kyle Simpson" Tags: "Guest Blogger, JavaScript"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 23 Apr 2013 13:33

JS Objects: TL;DR

JavaScript has been plagued since the beginning with misunderstanding and awkwardness around its “prototypal inheritance” system, mostly due to the fact that “inheritance” isn’t how JS works at all, and trying to do that only leads to gotchas and confusions that we have to pave over with user-land helper libs. Instead, embracing that JS has “behavior delegation” (merely delegation links between objects) fits naturally with how JS syntax works, which creates more sensible code without the need of helpers.

When you set aside distractions like mixins, polymorphism, composition, classes, constructors, and instances, and only focus on the objects that link to each other, you gain a powerful tool in behavior delegation that is easier to write, reason about, explain, and code-maintain. Simpler is better. JS is “objects-only” (OO). Leave the classes to those other languages!

Due Thanks

I’d like to thank the following amazing devs for their generous time in feedback/tech review of this article series: David Bruant, Hugh Wood, Mark Trostler, and Mark McDonnell. I am also honored that David Walsh wanted to publish these articles on his fantastic blog.

Complete Series

In part 1 of this article series, I went into great detail (aka, wordiness) about the differences between what the traditional definition of “inheritance” means and how JS’s [[Prototype]] mechanism works. We saw that JS operates oppositely to “inheritance”, being better labeled as “behavior delegation”. If you haven’t read it and you have any twinges of doubt or confusion about that statement, I’d encourage you to go read part 1 first.

Inheritance implies, to an extent, copying of behavioral definition down the chain, whereas behavior delegation implies delegating behavior up the chain. These aren’t just word semantics, but an important distinction that, when examined, can de-mystify a lot of confusing stuff around JS objects.

I’m by far not the first dev to realize this truth about JS. What differs here is in my reaction to that realization. The response usually is layering on other concepts to smoothe out the rough edges or unexpected consequences of how “prototypal inheritance” can surprise us, to try to make JS feel more like classical OO.

I think those attempts just distract us from the plain truth of how JS works.

I would rather identify the things which are merely distractions, and set them aside, and embrace only the true essence of how JS’s [[Prototype]] works. Rather than trying to make JS more “inheritance friendly”, I’d rather rip out everything that confuses me (and others) into thinking JS has “inheritance” at all.

Types

It’s often cited that in JavaScript, if you declare a function and add things to that function’s prototype, then that alone makes a definition of a custom “type”, which can be instantiated. If we were in a traditional OO language, that sort of thinking might be more appropriate, but here in JS land, it’s just one of many distractions.

You’re not really creating a new type in any real sense of that word. It’s not a new type that will be revealed by thetypeof operator, and it’s not going to affect the internal [[Class]] characteristic of a value (what would be reported by default via Object#toString()). It is true that you can do some self-reflection to check if an object is an “instance of” some function’s construction (via the instanceof operator). But importantly,foo1 instanceof Foo is just following the internal [[Prototype]] chain of your object foo1 to see if at any level of that chain it happens to find the .prototype object attached to the Foo function.

In other words, the reflection you’re doing is not about checking if the value is a specified type at all, nor is it about the function constructor. It’s only about asking if one object is in another object’s [[Prototype]] chain. The name and semantics of the instanceof operator (referring to “instances” and “constructor functions”) are layering on extra and unnecessary meaning, which only confuses you into thinking there’s anything more than simple [[Prototype]] chain checking going on.

Some developers frown on the usage of instanceof, and so an alternate form of determining the “type” of some object is called duck typing, which is basically inferring a value’s “type” by inspecting the object for one or more charateristic features, like a specific method or property.

Either way, these aren’t really “types”, they’re just approximations of types, which is one part of what makes JS’s object mechanism more complicated than other languages.

Mixins

Another distraction is trying to mimic the automatic “copying” of inheritance by using the “mixin” pattern, which essentially manually iterates through all the methods/properties on an object and makes a “copy” (techically just a reference for functions and objects) onto the target object.

I’m not saying that mixins are bad — they’re a very useful pattern. However, mixins have nothing to do with the[[Prototype]] chain or inheritance or delegation or any of that — they rely entirely on implicit assignment ofthis by having an “owning object” at the call-time of a function/method. They are, in fact, completely circumventing the [[Prototype]] chain.

Take any two independent objects, call them A and B (they don’t have to be linked via [[Prototype]] at all), and you can still mixin A‘s stuff into B. If that style of code works for your situation, use it! But just note that it has nothing to do with [[Prototype]] or inheritance. Trying to think of them as related is just a distraction.

Another related distraction is when the inevitable desire to create “multiple inheritance” comes up, because JavaScript only allows an object to be [[Prototype]] linked to one other object at a time. When we read about the lack of multiple inheritance in JavaScript, several problems come up, and various “solutions” are often proposed, but we never actually solve them, we just do more fancy hand-waiving to distract us from the difficulties that JS poses at the syntax/semantic level.

For example, you basically end up doing some form of “mixin” to get multiple different sets of properties/methods added into your object, but these techniques don’t, without elaborate and inefficient work-arounds, gracefully handle collision if two of your “ancestor” objects have the same property or method name. Only one version of the property/method is going to end up on your object, and that’s usually going to be the last one you mixed-in. There’s not really a clean way to have your object reference the different versions simultaneously.

Some people choose another distraction to resolve these problems, by using the “composition” pattern. Basically, instead of wiring your object C to both A and B, you just maintain a separate instance of each of A andB inside your C object’s properties/members. Again, this is not a bad pattern, it has plenty of goodness to it.

Parasitic Inheritance is another example of a pattern that works around this “problem” that [[Prototype]] doesn’t work like classes by simply avoiding [[Prototype]] altogether. It’s a fine pattern, but I think it’s a confusing distraction because it makes you feel like you’re doing OO when you’re not.

Whatever technique you use here, you basically end up ignoring the [[Prototype]] chain, and doing things manually, which means you’ve moved away from JavaScript’s “prototypal inheritance” mechanism altogether.

Polymorphism

One particular distraction that ends up creating some of the most awkward code patterns we deal with in JS is polymorphism, which is the practice of having the same method or property name at different levels of your “inheritance chain”, and then using super-style relative references to access ancestor versions of the same.

The problem is mechanical: JavaScript provides a this property, but importantly it is always rooted at the bottom of the [[Prototype]] chain, not whatever level of the chain the current function was found at. While it’s true that this.foobar() might end up resolving (finding) foobar() at an ancestor level of the chain, inside that call, his this will still be the original rooted this object.

Put more simply, this is not relative, but absolute to the beginning of the call stack. If JS had a super or acurrentThis (as I proposed recently), then those references would be relative to whatever the currently resolved link in the [[Prototype]] chain was, which would allow you to make a relative reference to a link “above”. But, JS does not currently have any such mechanism. And this being absolute rooted makes it an ineffective (or inefficient at best, thus impractical) solution to these relative references that polymorphism requires.

Most of the OO helper libraries try to provide a way for you to make super calls, but all of them end up having to do inefficient things under the covers to make that kind of relative call work.

class { .. }

Lastly, I think the long and hotly debated topic of class { .. } syntax that is coming to the language in ES6 represents more of the attempt to cover up what JS actually does with what people wished JS did. These sorts of distractions are not likely to make understanding JS’s actual mechanisms better. Some speculate that it will make JS more approachable from traditional OO devotees, which may be true at first, but I suspect the ultimate result is that they’ll quickly become frustrated about how it doesn’t work as they’d expect.

What’s important to understand is that the new class syntax we’re getting is not introducing radically new behavior or a more classical version of inheritance. It’s wrapping up how JS [[Prototype]] delegation currently works, in a syntax and semantics which come pre-loaded with lots of baggage understanding and expectation, which run quite contradictory to what you’ll really get with JS classes. If you currently do not understand, or don’t like, JS object “inheritance”, the class {..} syntax is pretty unlikely to satisfy you.

Yes, the syntax takes away some of the boilerplate of explicitly adding items to a “constructor” function’s.prototype object, and goodness knows we all will love not having to type the function keyword as many times. Hooray! If you already fully understand the awkward parts of JS “classes”, and you can’t wait forclass {..} to sugar up the syntax, I’m sure you’re happy, but I also think you’re probably in the minority. It’s made far too many compromises to even make it into the language to fully please a broad range of totally opposite opinions.

The underlying [[Prototype]] system isn’t changing, and almost none of the difficulties we just outlined are getting measurably any better. The only exception is the addition of the super keyword. That will be a welcome change I suppose.

Although, as a side note, the engine won’t actually bind super dynamically (at call time) to the appropriate link in the [[Prototype]] chain, but will instead bind it statically (at definition time) based on the owning object of a function reference. This is going to possibly create some weird WTF’s because the engine is going to have to create new function references on the fly as functions that use super are assigned around to different owning objects. It’s possible (unconfirmed suspicion) that it may not work in all cases as you’d expect if super were instead bound dynamically.

Simplificationizing™

We’ve just examined a variety of ways that many JS devs try to layer on extra abstractions and concepts on top of JS’s core object mechanism. I argue that this is a mistake that takes us further from the beauty of core JavaScript. Rather than adding complexity to smoothe out the rough edges, I think we need to strip things out to get to the good stuff.

In part 3, I will address exactly that, taking JS from the more complex world of classes and inheritance back to the simpler world of objects and delegation links.

Read the full article at: JS Objects: Distractions

Treehouse

Sencha Conference

Author: "Kyle Simpson" Tags: "Guest Blogger, JavaScript"
Comments Send by mail Print  Save  Delicious 
Next page
» You can also retrieve older items : Read
» © All content and copyrights belong to their respective authors.«
» © FeedShow - Online RSS Feeds Reader