Posted on

WordPress Boolean Options and JavaScript : Handle With Care

JavaScript WordPress Banner

After chasing my tail for the past 5 days I finally uncovered the source of a bug in my code that was causing Store Locator Plus to not initialize properly on fresh installs. The culprit? How WordPress handles booleans. In particular, how WordPress handles the persistent storage and the JavaScript localization of booleans.

The important lesson:

WordPress option storage is done using STRINGS*.
* there is a caveat here: SERIALIZED options are stored with the data type,
single options (non-arrays) are stored as strings

WordPress JavaScript localization uses PHP and JavaScript DATA TYPES.

 

What does this mean for plugin coding?

If you are passing WordPress options that have been fetched from the wp_options table with get_option to JavaScript via the wp_localize_script() method your booleans that are set to true/false will be passed to JavaScript as ‘1’/’0′. On the other hand, if you are setting a PHP variable to true/false and passing that to JavaScript they are set as a JavaScript boolean value of true/false.

The difference is important.

In JavaScript you write this for booleans:

if ( myoption.booleanvar ) { alert('true'); }

However you write this for the string version:

if ( myoption.booleanvar === '1' ) { alert('true'); }

How did this break my code?

When my plugin environment loads for the first time it uses an array to store option defaults. Since the user has not yet set or saved the plugin options the get_option call returns an empty array and those defaults are employed. However my option array looked something like this:

$options = array( 'booleanvar' => true );

To further compound the problem, I introduced yet ANOTHER issue by converting what was previously a single-element option to a serialized array in the latest patch release.   Serialized data is MUCH faster.  When you are fetching/setting more than a single option for your plugin.   To be a good WordPress citizen I’ve been slowly migrating all my legacy options to a single serial array.   HOWEVER the update did something like this:

$old_option = get_option('booleanvar');  // singular boolean options are stored as strings '1'/'0'
$options = array ( 'booleanvar' => $old_option ); // $old_option is a string
update_option( 'my_option_setting', $options);
delete_option('booleanvar');

My code is a lot “deeper” than shown here, but the basic idea was to fetch the pre-existing value of the singular option and store it in my options array. I save it back out to persistent storage and blast the old non-serialized option out of the database. THIS conversion for existing sites works well as the singular option variables will store and retrieve boolean data as a STRING. Thus my option comes back as ‘1’/’0′ depending on how the user left it and all is good in JavaScript-land.

HOWEVER, if you note above the NEW DEFAULT is to set booleanvar as a boolean with a default value of true. When storing a compound option (named array) with update_option it stores and retrieves values using the DATA TYPE.

$options = array( 'booleanvar' => true );
update_option( 'my_option_settings', $options );  // serial options are stored as proper data types
$options = get_option( 'my_option_settings');

Here the $options[‘booleanvar’] is set to a proper boolean.

As you can probably guess, this creates inconsistency in the Javascript.

Why? Because my JavaScript has been written for the most common use case which is one where users have set and saved the plugin options at least once. The JavaScript code uses the string comparison code shown above, ( myoption.booleanvar === ‘1’ ). It works as expected every time after the user has saved the options at least once.

Why does it work after options are saved? Because WordPress returns the boolean variable as the string value ‘1’. You can see this for yourself by playing with the update_option() and get_option() functions in WordPress to store/get a boolean true value. Since my code uses the stored values if they are set my booleanvar is not taking on the default true setting after the first save, it is coming back as ‘1’ which is what JavaScript expects to see.

The Lesson?

Use string values of ‘1’ and ‘0’ for your WordPress option values any time you are not using 100% serialized option values. It ensures consistency throughout your application by following the precedence set by the WordPress get_option function.

Yes, you can get away with using boolean true/false values. It even makes the code more readable, IMO. However it can cause issues if you ever decide you need to pass those values along to your JavaScript functions with wp_localize_script() if you are not 100% certain you are using pure non-translated boolean variables throughout.

If you are ever uncertain of your true data types add a gettype($varname) debugging output to your plugin code. Remember that simple print_r statements will convert booleans to strings as well, use gettype to be certain of what flavor variable you have inside PHP.

Posted on

Improved Grunt Tasks for the Vagrant WordPress Dev Box

Grunt WordPress Dev Kit

Last week I found myself having to rebuild my WordPress plugin development box after a “laptop fiasco”.   While it was a lot of work it feels as though I am in a better position to not only recover my environment quickly but also distribute it to other developers that are interested in assisting with plugin development.

If you are interested you can read more about it in the related WordPress Workflow and related WordPress Development Kit articles.

This morning I realized that having a new almost-fully-configured Vagrant box for my WordPress Development Kit allows me to make assumptions in my Grunt tasks.    While it would be more flexible to create options-based tasks where users can set their own configuration for things like MySQL usernames and passwords, the WP Dev Kit Vagrant box assumption allows me to bypass that for now and come back to it when time allows.  Fast turnaround and fewer interruptions in my already-busy work flow is paramount this week.

Today’s WordPress Dev Kit Updates

The official tag I’ve assigned to the newest WordPress Dev Kit is version 0.5.0.  Here is what has been added.

WordPress Database Reset

One of the tasks I do fairly often is to “clear the data cruft” from my development box WordPress tables.  I  accomplish this by dropping the WordPress database and recreating it.

The Vagrant box makes this far easier as I know that when I spin up the WP Dev Kit Vagrant box it already has the WordPress MySQL tables setup.  I also know the username and password.  As such I can execute a simple drop/create table as the privileges are already in place in the meta data for MySQL and will carry over.   Thus I only need to execute a single mysql-cli command to get the data reset.

To get this working in Grunt I added the grunt-ssh module and created a ‘resetdb’ target.

I can now reset my WordPress table with a simple grunt command:


$ grunt shell:resetdb

Online Documentation

The other change I made today will help me remember how the heck all this stuff works.  Now that the dev kit has grown to a couple of commands I know I will soon be forgetting the nuances to certain build and workflow processes.   I started creating my own Markdown files I realized that Bitbucket has a system for using .md files on the repository wiki.    The easy solution was to add the Bitbucket wiki as a submodule to the WP Dev Kit repository and edit the file there.    Doing so means that any doc update will also be published immediately when pushed back to the repo at the WP Dev Kit Bitbucket Wiki.

Now back to getting the Store Locator Plus and Enhanced Results first-pass testing run and prerelease copies published for my Premier Members.

Posted on

Improving WordPress Plugin Development with Sass

SLP Sass Banner

If you’ve been following along since my WordCamp Atlanta trip this spring you know that I’ve been working on automating my WordPress plugin development and production process.    If you missed it you can read about it in the WordPress Workflow and WordPress Development Kit articles.   Since I needed to patch some basic CSS rules in my Store Locator Plus themes, these are plugin “sub-themes” that style the store locator interface within a page, I decided now was the time to leverage Sass.

Sass Is In The House

It was one of my first sessions at WordCamp Atlanta and I KNEW it was going to be part of my automation process.    Sass is a CSS pre-processor.   Store Locator Plus has its own “theme system”, a sort of plugin sub-theme that lives within the WordPress over-arching site theme.     The SLP themes allow users to tweak the CSS that renders the search form, map, and results of location searches to create in-page layouts that better fit within their WordPress theme layout.

Until this past release it was a very tedious process to update themes or create a new theme.    In the latest release there are some 30-odd SLP theme files.    The problem is that when I find an over-arching CSS issue, like the update to Google Maps images that rendered incorrectly on virtually EVERY WordPress Theme in existence, it was a HUGE PAIN.   I was literally editing 30 files and hoping my cut-and-paste job went well.   Yes, I could have done CSS include statements but that slows things down by making multiple server requests to fetch each included CSS file.   Since the store locator is the most-visited page on many retail sites performance cannot be a secondary consideration.   Sass deals with that issue for me and brings some other benefits with it.

There are PLENTY of articles that describe how to install Sass, so I am not going to get into those details here.  On CentOS it was a simple matter of doing a yum install of ruby and ruby gems and a few other things that are required for Sass to operate.  Google can help you here.

My Sass Lives Here…

For my current Sass setup I am letting NetBeans take care of the pre-compiling for me.    It has a quick setup that, once you have Sass and related ruby gems installed, will automatically regenerate the production css files for you whenever you edit a mixin, include, or base SCSS file.

NetBeans Sass Setup
NetBeans Sass Setup

I combine this with the fact that the assets directory is ignored by the WP Dev Kit publication and build tasks to create a simple production environment for my CSS files.   I store my SCSS files in the ./assets/stylesheets directory for my plugin.   I put any includes or mixin files in a ./assets/stylesheets/include subdirectory.     I configure NetBeans to process any SCSS changes and write out the production CSS files to the plugin /css directory.

The first thing I did was copy over a few of my .css files to the new stylesheets directory and changed the extension to .scss as I prepared to start building my Sass rules.

Includes

I then ripped out the repeated “image fix” rules that existed in EVERY .css file and created a new ./stylesheets/include/_map_fix.scss file.     This _map_fix file would now become part of EVERY css file that goes into production by adding the line @include ‘include/_map_fix” at the top of the SLP theme .scss files.    Why is this better?   In the past, when Google has made changes or WordPress has made changes, I had to edit 30+ files.  Now I can edit one file if a map image rule is changing that has to be propagated to all of the css files.   However, unlike standard CSS includes Sass will preprocess the includes and create a SINGLE CSS file.   That means the production server makes ONE file request instead of two.  It is faster.

SLP Map Fix Include
SLP Map Fix Include

As I reiterated this process I ended up with a half-dozen CSS rules that appear in MOST of my CSS files.    Since all of the rules do not appear in all of my plugin theme files I ended up with a half-dozen separate _this_or_that scss files that could be included in a mix-and-match style to get the right rule set for each theme.     I also created a new _slp_defaults include file that does nothing more than include all of those half-dozen rules.  Nearly half of the current CSS files use all of rules that were “boiled out of” the CSS files.

Store Locator Plus Default Includes
Store Locator Plus Default Includes

Mixins

Along the way I learned about mixins.   At first I was a bit confused as to the difference between include files and mixins.  Both are “pulled in” using similar commands in SCSS, @import for the “include files” and @include for the mixins, but what was the difference?    While you can likely get away with “faking it” and having mixins act like includes they serve different purposes.   I like to think of a mixin as a “short snippet of a CSS rule”.

A common example is a “set the border style mixin”.  In the simplest form it can set the border style with a rule for each of the browser variants.  This rule is not a complete CSS rule but rather a portion of a CSS rule that may do other styling AND set a border.    The mixin includes the -moz and other special rule sets to accomodate each browser.   Rather than clutter up a CSS entry with a bunch of border-radius settings, use a mixin and get something like:

.mystyle {
   @include mixin_border_radius;
   color: blue;
}

That is a very simplistic way of using a mixin. One advantage is that if you decide to change the default border radius settings in all of your CSS files you can edit a single mixin file. However that is not a typical use. Yes, you can create subsets of CSS rules, but it really gets better when you add parameters.

At a higher level a mixin is more than just a “CSS rule snippet”. It becomes more like a custom PHP function. In typical coder fashion, I snarfed this box-shadow mixin somewhere along the way:

// _csa_mixins.scss

@mixin box-shadow( $horiz : .5em , $vert : .5em , $blur : 0px , $spread : 0px , $color : #000000 ){
    -webkit-box-shadow: $horiz $vert $blur $spread $color;
    -moz-box-shadow: $horiz $vert $blur $spread $color;
    box-shadow: $horiz $vert $blur $spread $color;
}
@mixin csa_default_map_tagline {
    color: #B4B4B4;
    text-align: right;
    font-size: 0.7em;
}
@mixin csa_ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

Since that rule is part of my default _csa_mixins that I tend to use in multiple places I use it as follows:


@import 'include/_csa_mixins';
@import 'include/_slp_defaults';

//blah blah boring stuff here omitted

// Results : Entries (entire locations)
.results_entry {
    padding: 0.3em;
    @include box-shadow(2px, 4px, 4px, 0px, #DADADA);
    border-bottom: 1px solid #DDDDDD;
    border-right: 1px solid #EEEEEE;
}

Notice how I now call in the include with parameters. This is passed to the mixin and the Sass preprocessor calculates the final rules to put in the CSS file. This makes the mixin very flexible. I can create all sorts of different box shadow rules in my CSS files and have the cross-browser CSS generated for me. No more editing a dozen box shadow entries every time I want to change a shadow offset.

Here is what comes out in the final production CSS when using the above mixin. You can see where the parameters are dropped into the .results_entry CSS rule:

.results_entry {
  padding: 0.3em;
  -webkit-box-shadow: 2px 4px 4px 0px #dadada;
  -moz-box-shadow: 2px 4px 4px 0px #dadada;
  box-shadow: 2px 4px 4px 0px #dadada;
  border-bottom: 1px solid #DDDDDD;
  border-right: 1px solid #EEEEEE; }

This is only a start of my journey with Sass and I’ve barely scratched the surface. However I can already see the benefits that are going to come from using Sass. In fact I already used it to fix a problem with cascading menus where one of the SLP theme files did not contain a rule set. Rather than copy-paste from another theme file that contained the proper rules I only needed to add @import ‘include/_slp_tagalong_defaults’ and the problem was fixed.

Going forward Sass will not only increase my throughput in CSS development but also improve the quality of the final product that reaches the customer.

My first SLP Theme file, Twenty Fourteen 01, that was built using these new Sass files is only a 136 line CSS file with LOTS of whitespace and comments.  When the final processing is finished it has all of the rules necessary to support the current add-on packs and style them nicely for the WordPress Twenty Fourteen theme in all major browsers.

A new SLP Theme: Twenty Fourteen Rev 01
A new SLP Theme: Twenty Fourteen Rev 01

 

Posted on

WordPress Dev Kit : Grunt 0.3.0 and Plugin 0.0.2

Grunt WordPress Dev Kit

More refinements have been made this week to my WordPress Workflow and related WordPress Development Kit.  With new products going into production shortly and some older products coming out with new releases, I realized I needed a more efficient way to publish prerelease copies.  As part of the Premier membership program I am trying to get stable prerelease products in the hands of those Premier members that want them.   Some members like to test new releases or try out new features on their test systems before they come out.    It allows them to plan for future updates and provides an opportunity for feedback and updates before the new version is released.  A win-win for the Premier member and for Charleston Software Associates.

In order to support a formal prerelease and production configuration I realized I needed to be able to track two different versions and release dates separately.   Following the general format presented in other Grunt examples, this meant setting up new sub-sections within the plugins.json pluginMeta structure.   The new format looks something like this:

"wordpress-dev-kit-plugin": {
"production": {
"new_version": "0.0.02",
"last_updated": "2014-04-03"
},
"prerelease": {
"new_version": "0.0.03",
"last_updated": "2014-04-04"
},
"publishto" : "myserver"
}

Changing the structure meant updating both the Gruntfile.js for the development kit as well as the parser that is in the WordPress Development Kit plugin. The changes were relatively minor to address this particular issue, but I did learn some other things along the way.

Tasks and Targets

In my own Grunt tasks I had been calling one of my parameters in my build sequence the “type”, as in the “build type”. However the configuration file examples online often talk about a “target”. A target would be something like “production” or “prerelease” that shows up in a configuration block like this one:

// sftp
//
sftp: {
options: {
host: ‘<%= myServer.host %>’,
username: ‘<%= myServer.username %>’,
privateKey: ‘<%= myServer.privateKey %>’,
passphrase: ‘<%= myServer.passphrase %>’,
path: ‘<%= myServer.path %><%= grunt.task.current.target %>/’,
srcBasePath: "../public/<%= grunt.task.current.target %>/",
showProgress: true
},
production: { expand: true, cwd: "../public/<%= grunt.task.current.target %>/", src: ["<%= currentPlugin.zipbase %>.zip","plugins.json"] },
prerelease: { expand: true, cwd: "../public/<%= grunt.task.current.target %>/", src: ["<%= currentPlugin.zipbase %>.zip","plugins.json"] }
},

I have updated my scripts and documentation terminology to refer to this parameter as the “target” to follow convention.

Simplify Congiguration With grunt.task.current.target

I learned a new trick that helps condense my task configuration options. In one of my interim builds of the WordPress Dev Kit I had something that looked more like this:

// sftp
//
sftp: {
options: {
host: ‘<%= myServer.host %>’,
username: ‘<%= myServer.username %>’,
privateKey: ‘<%= myServer.privateKey %>’,
passphrase: ‘<%= myServer.passphrase %>’,
showProgress: true
},
production: {
expand: true,
cwd: "../public/<%= grunt.task.current.target %>/",
src: ["<%= currentPlugin.zipbase %>.zip","plugins.json"]
path: ‘<%= myServer.path %>production/’,
srcBasePath: "../public/production/",
},
prerelease: {
expand: true,
cwd: "../public/<%= grunt.task.current.target %>/",
src: ["<%= currentPlugin.zipbase %>.zip","plugins.json"]
path: ‘<%= myServer.path %>prerelease/’,
srcBasePath: "../public/prerelease/",
},
},

A bit repetitive, right? I found you can use the variable grunt.task.current.target to drop the current task name as a string into a configuration directive:

// sftp
//
sftp: {
options: {
host: ‘<%= myServer.host %>’,
username: ‘<%= myServer.username %>’,
privateKey: ‘<%= myServer.privateKey %>’,
passphrase: ‘<%= myServer.passphrase %>’,
showProgress: true
},
production: {
expand: true,
cwd: "../public/<%= grunt.task.current.target %>/",
src: ["<%= currentPlugin.zipbase %>.zip","plugins.json"]
path: ‘<%= myServer.path %><%= grunk.task.current.target %>/’,
srcBasePath: "../public/<%= grunk.task.current.target %>/",
},
prerelease: {
expand: true,
cwd: "../public/<%= grunt.task.current.target %>/",
src: ["<%= currentPlugin.zipbase %>.zip","plugins.json"]
path: ‘<%= myServer.path %><%= grunk.task.current.target %>/’,
srcBasePath: "../public/<%= grunk.task.current.target %>/",
},
},

Now that the prerelease and production path and scrBasePath variables are identical they can be moved into the top options section.

Now if I can just figure out how to have shared FILE configurations which define the current working directory (cwd), source (src), and destination (dest) file sets I could eliminate ALL of the settings in the production and prerelease configuration blocks and leave them with a simple “use the defaults setup like this:

// sftp
//
sftp: {
options: {
host: ‘<%= myServer.host %>’,
username: ‘<%= myServer.username %>’,
privateKey: ‘<%= myServer.privateKey %>’,
passphrase: ‘<%= myServer.passphrase %>’,
path: ‘<%= myServer.path %><%= grunk.task.current.target %>/’,
srcBasePath: "../public/<%= grunk.task.current.target %>/",
showProgress: true
},
production: { },
prerelease: { },
},

Maybe someday.

Simplify Congiguration With Shared Variables

Another trick I learned is that common configuration strings can be put at the top of the configuration block and re-used. This is alluded to on the Grunt tasks configuration page but they never expound on how to use the common configuration variables. Here is how it works, define the variable at the top of the configuration block then reference that variable inside a string like ‘<%= my_var %>’. Here is my example with some “fluff” missing from the middle:

// Project configuration.
grunt.initConfig({

// Metadata.
currentPlugin: currentPlugin,
myServer: myServer,
pkg: grunt.file.readJSON(‘package.json’),
my_plugin_dir: ‘/var/www/wpslp/wp-content/plugins/<%= currentPlugin.slug %>’,
my_src_files: [
‘**’,
‘!**.neon’,
‘!**.md’,
‘!assets/**’,
‘!nbproject/**’
],
// compress
//
compress: {
options: {
mode: ‘zip’,
archive: ‘../public/<%= grunt.task.current.target %>/<%= currentPlugin.zipbase %>.zip’,
},
prerelease: { expand: true, cwd: ‘<%= my_plugin_dir %>’, src: ‘<%= my_src_files %>’ },
production: { expand: true, cwd: ‘<%= my_plugin_dir %>’, src: ‘<%= my_src_files %>’ },
},

In this example you can see how I’m using the my_plugin_dir variable to set my path to the plugins I am working on on my dev box and my_src_files to list the files I want to add (or ignore) when pushing my development plugin directories to a zip file or the WordPress svn repo for publication.

This has simplified a lot of task configuration entries in my custom grunt tasks script.

That combined with smarter configuration blocks in areas like the SFTP node module has simplified my Grunt configuration which will make it less prone to errors and easier to maintain going forward.

Back to coding…

Posted on

Mobile Cross Platform Development : Cordova

Apache CordovaApache Cordova (aka Phonegap).

A little clarification on the name.  The NEW name will be Apache Cordova.   After Adobe bought the development firm that was working on Phonegap the Phonegap project itself was given to Apache Software Foundation to maintain its open source roots and continue development.  As of this writing the transition is still underway with MOST, but not all, elements haven taken on the Apache Cordova persona.

Our First App On Cordova

Our first app that we wrote using Cordova was the Abundascan application for Abundatrade.   The first release is a simple app that uses the camera to scan a barcode then sends the UPC to the Abundatrade server to get real-time prices that they will pay for used books, CDs, DVDs, and video games.    Functionally the app is simple and works well.    However one key element here is the primary reason we started with Cordova over other cross-platform tools like Corona, the camera.

Turns out that many of the cross-platform tools do NOT support the camera interface. That shot down Corona right away, which otherwise looked promising.

Cordova And Cameras

The nice part about Cordova is that the system is basically a wrapper for the native web browser.  That means coding in HTML5, CSS, and JavaScript.  It also has a number of third party plugins that hook native mobile functionality (via Java or Objective-C) to a JavaScript class.   In theory that sounds great.

Luckily there is a good camera scanner app that reads UPC,and other machine-enabled codes like QR, codes created by Google released in the ZXing project.  The ZXing applet is ported and ready to use for Cordova as a plugin.

Cordova Camera Caveats

The problem is that theory does not work out in reality.   The plugin for Android works wonderfully.  The plugin on OS-X, not so much.  Not surprising that a Google app talking through JavaScript to an Apple owned OS and development environment doesn’t work well.  Apple really does go through a lot of effort to put a stranglehold on their development pipeline.

The bottom line, we have yet to get the camera plugin to work on IOS4 or higher devices.   In theory the demo app works, but we’ve yet to see it on our iPod Touch or newer iPhones.

The Android Version of Abundascan is out, but we still are having issues with Cordova on IOS.

Our Second App

Our second app is a little less ambitious as it is testing the waters for a larger project.  This app is simply a screen that shows your current GPS location with exact latitude and longitude.   Where Am I Standing? is a free app that does just that.   To make it a little more interesting we wanted to add an info page with our name and logo and a little bit of graphic “window dressing”.

Again, here we ran into multiple issues.  This time noticeable right on the Android before we even attempted the iPhone release.    We want a simple app with no glitches yet there are several things that still aren’t right.  We can spend a good bit more time addressing in convoluted code to workaround quirky UI elements.  Others are as-yet un-fixable.

Technically it was easy & works well. Aesthetically it is NOT of the caliber I want it to be at.    As I dug deeper into this I uncovered a lot of hidden secrets about mobile app development and why 99.99% of these cross-platform tooks like Cordova fail.

The Compromises

Here are the “little details” that are compromises I don’t want to make.  I want to build QUALITY apps.  That means making them as perfect as we can, and this stuff is far from it:

Swipe Right / Left : I wanted to be able to simply swipe the main screen to see the info screen (“created by Cyber Sprocket”).     One swipe works, then it breaks.  This is a fundamental issue in the browser kit Cordova uses as the foundation for their solution.   Google developers refuse to address it saying it is “as designed”.

Vertical Page Scrolling : I don’t want ANY page scrolling, jitter, etc.   The pages are too “tall” and are scrollable if you swipe up or down.  This can be fixed but takes extra coding to do so.   What a pain.

Button Highlighting : Sometimes the highlights on the info/home buttons “stick”.  This is a built-in feature of jQuery Mobile and Cordova.  It is wonky at best.

Screen Hesitation: Even on a mid-range phone with just about the simplest app possible, sometimes going to the “info” page hesitates, same with going back to home.

Navigation History : Go to info, then back to home.   Each time you do this is adds to the “history”.  Do it a few times and your back button is loaded up with a bazillion loops of home/info/home.   Again, fixable with code (mostly) but why?

Summary

While Apache Cordova will help you build apps using technologies you likely already know like HTML5 and JavaScript, the implementation is far from simple.  Getting stuff to work on more than one platform requires extensive knowledge of all the quirks.  Like IOS requires a special onDeviceReady hook or it won’t even load properly.   The apps also feel “heavy”.    The UI is not responsive and, depending on the hardware, often misbehaves.

While Apache Cordova may be a great tools for building a functional prototype or possibly building corporate apps where users may value function over form, in my opinion Cordova is a compromise.

Yes,  you can probably build a well-polished UI.   But it takes a LOT of extra effort because you are hamstrung by the JavaScript/web interface.  Of course you can write custom Java or Objective-C hooks and/or make your own plugin, but isn’t that point to get away from native custom code?    You can also get around *some* of the quirks with a good bit more coding, but how you get around which quirks often requires intimate knowledge of the quirks for the particular mobile OS that is giving you problems.

I’m sure we can build quality apps with Apache Cordova, but this is not about CAN we do that, it is about what are the benefits of doing so.  From a business perspective there appears to be little gained here over a process that includes solid architecture, documentation, code design, and good old-fashioned cross-platform awareness and porting.

Posted on

Passing Variables To JavaScript In WordPress

We have touched on several complex subjects when it comes to writing plugins for WordPress that make use of JavaScript. In these articles we discuss built-in scripts, custom static scripts, and dynamic scripts. Dynamic scripts are the scripts that need access to information from the WordPress application environment in order to function properly, such as passing in a setting stored in the WordPress database or a variable that is calculated within PHP. There is a simple trick for getting variables into your JavaScript that is quite a bit more elegant than our dynamic scripting approach using the output buffering PHP trick we outlined earlier.

In later versions of WordPress (2.2+ if I recall) there is a function that was originally intended for language translation. It is meant to localize your scripts. You can leverage this feature to load up a variable array in JavaScript which provides an effective mechanism for getting your WordPress variables into the JavaScript environment.

Localize Script Outline

The basic premise for getting data into JavaScript is as follows:

  • Register your script in the wp_enqueue_script() action hook.
  • Localize your script when you render your shortcode.
  • Enqueue your script when you render the footer.

The important part is to use the footer enqueue method to ensure that your variable processing happens ahead of time. If you are doing a simple script you could put the register, localize, and enqueue steps all in the function you write for the wp_enqueue_script action hook. You will want to separate this into the 3 steps outlined above, however.

Register The Script

Here is an example from one of our plugins.

In the main application file, call our hook for the wp_enqueue_scripts action:

add_action('wp_enqueue_scripts',array('SLPlus_Actions','wp_enqueue_scripts'));

In the SLPlus_Actions class:

/*************************************
 * method: wp_enqueue_scripts()
 *
 * This is called whenever the WordPress wp_enqueue_scripts action is called.
 */
 static function wp_enqueue_scripts() {
     //------------------------
     // Register our scripts for later enqueue when needed
     //
     wp_register_script(
       'slplus_map',
       SLPLUS_PLUGINURL.'/core/js/store-locator-map.js',
       array('google_maps')
     );
 }

These steps tell WordPress to keep track of our JavaScript, helping do some version management, cache management, and get the script ready to be rendered. Since WordPress 3.3 will automatically set the “render in footer” flag for any script enqueued after the wp_enqueue_scripts() action hook, we don’t need to set that here.

Pass Our Variables To JavaScript

When we process our shortcode we do two things. We tell WordPress to manipulate the JavaScript rendering engine to pass in a named array of variables we want our script to know about. We also set a global define so that we know our shortcode has been rendered so we can control IF the script is rendered at all when we call our last-stage processing hooks in WordPress.

In our shortcode processing function:

// Lets get some variables into our script
 //
 $scriptData = array(
    'map_domain' => get_option('sl_google_map_domain','maps.google.com'),
    'map_home_icon' => $slplus_home_icon,
    'map_type' => get_option('sl_map_type','G_NORMAL_MAP'),
    'map_typectrl' => (get_option(SLPLUS_PREFIX.'_disable_maptypecontrol')==0),
    'zoom_level' => get_option('sl_zoom_level',4),
);
 wp_localize_script('slplus_map','slplus',$scriptData);
 // Set our flag for later processing
 // of JavaScript files
 //
 if (!defined('SLPLUS_SHORTCODE_RENDERED')) {
 define('SLPLUS_SHORTCODE_RENDERED',true);
 }

Enqueue The Script

Now that we have our script registered and told WordPress to setup our environment we can now render our script. However we only want WordPress to render the script if our shortcode was processed, which is what the global define was for. We also find that some themes skip the footer processing which disables footer scripts, so we are going to force footer scripts to run within our late-stage WordPress action hook.

In our SLPlus_Action Class:

/*************************************
 * method: shutdown()
 *
 * This is called whenever the WordPress shutdown action is called.
 */
 function shutdown() {

 // If we rendered an SLPLUS shortcode...
 //
 if (defined('SLPLUS_SHORTCODE_RENDERED') && SLPLUS_SHORTCODE_RENDERED) {

 // Register Load JavaScript
 //
 wp_enqueue_script('slplus_map');

 // Force our scripts to load for badly behaved themes
 //
 wp_print_footer_scripts();
}

Using The Variables

Now our script only renders on pages where our shortcode appears and we now have our WordPress variables easily accessible from within the script. How do we reference these in our script? That’s the easy part, here is an example:

In our store-locator-map.js file:

/**************************************
 * function: sl_load()
 *
 * Initial map loading, before search is performed.
 *
 */
function sl_load() {
 if (GBrowserIsCompatible()) {
 geocoder = new GClientGeocoder();
 map = new GMap2(document.getElementById('map'));
 if (parseInt(slplus.overview_ctrl)==1) {
 map.addControl(new GOverviewMapControl());
 }
 map.addMapType(G_PHYSICAL_MAP);
 // This is asynchronous, as such we have no idea when it will return
 //
 geocoder.getLatLng(slplus.map_country,
 function(latlng) {
 if (!slplus.load_locations) {
 map.setCenter(latlng, parseInt(slplus.zoom_level), eval(slplus.map_type));
 }

 var customUI = map.getDefaultUI();
 customUI.controls.largemapcontrol3d = slplus.map_3dcontrol;
 customUI.controls.scalecontrol = slplus.map_scalectrl;
 customUI.controls.hierarchicalmaptypecontrol = slplus.map_typectrl;
 map.setUI(customUI);

 if (slplus.disable_scroll) { map.disableScrollWheelZoom(); }

 if (slplus.load_locations) {
 sl_load_locations(map,latlng.lat(),latlng.lng());
 }
 }
 );
 }
}

Obviously our example has variables we culled out of our localize_script section above, but you get the idea. The slplus prefix is based on the 2nd parameter in our wp_localize_script function call in the previous section. The variable name after the slplus prefix is the key of the $scriptData variable that we passed into that function call as the 3rd parameter.

Summary

By using wp_localize_script you can make use of the wp_register_script and wp_enqueue_script WordPress functions to manage your script loading and variable passing. This is a much cleaner environment for managing scripts than using the PHP output buffer tricks discussed earlier.

However, not all plugins play well with each other. Not all themes follow the rules. In many cases the methods we outline here may not work. In our experience, however, the more plugins that use these modern methodologies the more stable and efficient WordPress is. Eventually those plugins and themes that do not play well with others will atrophy and only those that are well crafted and utilizing best methods will survive.

Posted on

WordPress/JavaScript : Selective Enqueue

In the past couple of articles about WordPress and JavaScript we touched on several methods for managing JavaScript in WordPress. For simple “static” scripts or built-in WordPress scripts, such as jQuery, the standard register and enqueue methods provide all the control you need to invoke your scripts.

However there are several issues that come up when you decide you only want scripts to load when you render a specific shortcode. Here we touch on these issues and how we resolve them in our plugin. There are other methodologies as well, but here are the methods that worked for us.

Load Script For Shortcode Pages

One of the issues we’ve run into is loading the JavaScript only on pages where the shortcode is rendered. The problem is that for this trick to work you must load the scripts in the footer of the rendered page. WordPress (since v2.6) does provide a “load in footer” flag when registering or enqueing a script. As we learned, however, this is fatally flawed in all releases prior to WordPress version 3.3.

In versions prior to WordPress 3.3, the “load in footer” flag will actually render your scripts immediately after rendering the page content. There are no actions you can hook to between the time your shortcode is rendered and the point that the scripts are rendered. This causes a number of issues when you are trying to selectively load your scripts when your shortcode is rendered.

Post 3.3 Process

For sites running WordPress 3.3+ the best practice for selectively loading scripts, as described in our previous posts, is:

    • Register your script via the wp_enqueue_scripts() action hook.
    • Enqueue your script via your shortcode rendering script
      -OR-
    • Set a global flag when rendering the shortcode, then enqueue your script with the shutdown() action hook

As we found, not all themes play well with rendering scripts in the footer of a page.  Thus, our preferred method is to set a global flag when we render our shortcode and then create a custom shutdown hook.   This way we can force footer scripts to be rendered immediately after we enqueue any scripts we need to make our shortcode work.

For example, in our main plugin PHP file:

add_action('shutdown',array('SLPlus_Actions','shutdown'));

Then in our SLPlus_Actions Class file:

/*************************************
 * method: shutdown()
 *
 * This is called whenever the WordPress shutdown action is called.
 */
 function shutdown() {

 // If we rendered an SLPLUS shortcode...
 //
 if (defined('SLPLUS_SHORTCODE_RENDERED') && SLPLUS_SHORTCODE_RENDERED) {

 // Register Load JavaScript
 //
wp_enqueue_script('google_maps');
wp_enqueue_script('slplus_map');

// Force our scripts to load for badly behaved themes
 //
 wp_print_footer_scripts();
}

This works wonderfully in our WordPress 3.3+ installations.

However, in version prior to 3.3 the enqueued scripts are completely ignored at this point in the page rendering process.

Pre WordPress 3.3 Methods

There are several methods we tried in versions prior to WordPress 3.3, none of which are a great solution.  In these earlier versions of WordPress you MUST enqueue your scripts via the wp_enqueue_scripts() method, so they are rendered in the header of the page.   In versions greater than 2.6 these scripts will appear in the “footer” (which is really not the footer, but post-content rendering) but you still must enqueue them in the wp_enqueue_scripts() action. BTW, as a side note, do NOT enqueue in the init hook.  This is an old school method that we found does not work properly in all cases.

As we found, however, you cannot turn the script on/off at that point even if you selected the “load in footer” flag.    Some things we tried:

  • Deregister/denqueue the script if our shortcode was NOT rendered.
    The problem is that there is no hook that runs between content rendering and script rendering, so you can’t test your “shortcode rendered/not rendered” flag.
  • Register only in wp_enqueue_scripts(), then enqueue in the shortcode rendering.
    These mid-page enqueues are ignored.  WordPress changed this in 3.3 so it will render scripts in the footer, but pre 3.3 this does not work.
  • Register only in wp_enqueue_scripts(), then enqueue in the shutdown/footer/post-content-action-of-any-kind hook.
    Same problem as above.

In short if you don’t enqueue  in the header with wp_enqueue_scripts() on pre 3.3 versions of WordPress you will get inconsistent results.

Selectively Enqueue Scripts 3.3 and Pre-3.3

So how do we address pre-3.3 and 3.3+ versions of WordPress?   We certainly want to eliminate all the overhead we can and make our plugin as efficient as possible.     In 3.3+ we don’t want the script to render at all, but this is not compatible with pre 3.3 release.   Here is what we do today that is a compromise between both worlds:

  • Enqueue the script in the wp_enqueue_scripts() action hook with the footer flag set.
  • Set a global flag when we render the shortcode.
  • If the global flag is NOT set, deregister/deenqueue the script via a wp_footer() or wp_shutdown() action hook.

By using this methodology, WordPress 3.3+ will prepare the scripts to be enqueued in the footer.  Since they really do enqueue in the footer now, we can now intercept the process PRIOR to the rendering via the late-stage action hooks like wp_footer or wp_shutdown.    So in version 3.3+ the deenqueue call will stop the script from being rendered via  last minute “woah, don’t do this” request.

In versions prior to 3.3 the script will always be rendered on every page.   Unfortunately that is the price to pay for pre version 3.3 users if we are trying to be as efficient as possible for users of the latest releases of WordPress.  Yes there are other methods that work, but at the price of slowing down everyone that uses the latest version of WordPress.

Don’t Enqueue Pre 3.3

Since we mentioned it, here is the basic premise if you want to use the above methodology and not enqueue for version 3.2:

  • Add a hook to wp_enqueue_scripts() as per above.
  • In that hook, get the current post ID.
  • Grep the content of that page and check for your shortcode (WordPress has a function that returns your shortcode regex).
  • Only if the content has the shortcode do you enqueue.

The reason we don’t like to do this is there is extra processing involved.  For larger pages this can be fairly intensive.  On a low-traffic site your users will never notice the extra half-second or less, but on large traffic sites or sites with a longer pages this can be a big hit on server resources.

Summary

As we have found, getting scripts to only load when you want them can be a chore.  The simple solution is just enqueue your scripts for your shortcodes all the time.  Your plugin will always work, however this comes at the expense of the overall site performance for your plugin users.    In our case we don’t want to load up the Google Maps API JavaScript on ever page and post on our client sites.   We only want the scripts to load when they are showing the location map.

Unfortunately not all themes play nice with the header and footer actions in WordPress.   In addition, WordPress 3.3 is the first release that actually gives us the level of control we need to render scripts in a proper controlled fashion.

Posted on

WordPress and JavaScript Part 2

WordPress

This is our second article in a series about working efficiently with JavaScript in WordPress. There are a lot of sites and lots of examples on how to implement JavaScript in WordPress. Many of the articles we came across were incorrect or outdated. What was once the viable, or possibly the only available, method for implementing JavaScript hooks a few years ago with WordPress version 2.X are not the most efficient methods today. In our second article we touch on this point and continue to distill the information we’ve uncovered that have helped us create better JavaScript hooks in our plugins.

This follow-on to the first article unveils some key points about using JavaScript in WordPress:

  1. Not all plugins follow best practices.
  2. Some very popular plugins (one of which has 6,000,000 downloads) completely bypasses wp_register_script and wp_enqueue_script, instead doing print <script src="blah"> right in the HTML output header.
  3. These plugins, and themes for that matter, thwart any attempts to abide by best practices in your own plugin.

What we found when working on various client sites is the techniques in our last article are not foolproof.

The main issues we discovered:

  • Some scripts force an archaic version of jQuery to be used, in our case v1.4.X when the current WordPress version of jQuery is 1.7.1. Our plugin, for one, requires jQuery 1.7 or higher as we follow best practices for jQuery and use the .on() method for invoking actions.
  • Some plugins kill the wp_enqueue_script process well before the WordPress action stack has exited. In our case it was being shut down well before the content, and thus shortcodes, were rendered.

Our workaround:

– Register AND Enqueue the scripts in the wp_enqueue_script action.

But…

This loads your scripts on EVERY PAGE. Exactly what we want to avoid.

The solution that gets around “mis-behaving” plugins? Use the much-hated, at least by me, filter to check if the current post has your shortcode.

However, unlike other archaic methods for implementing this test with a direct database query, you can use the built-ins of WordPress to make this run a bit faster. It still accesses the database so it is slower than simply firing enqueue when the shortcode is rendered but it is a price we have to pay if we want to live in the same neighborhood with our miscreant neighbors.

How to filter your enqueue script:

function setup_scripts_for_plugin() {
   global $post;
   $pattern = get_shortcode_regex();
   if ( preg_match_all('/'.$pattern.'/s',$post->content,$matches) &&
        array_key_exists(2,$matches) &&
        in_array('our_shortcode', $matches[2])       ) {     wp_register_script('jquery');   wp_enqueue_script('jquery'); }

Summary

That’s it. Now your scripts will be loaded only on the page with the shortcode you specified in the in_array() call.

In our example we are registering the jQuery built-in, but this works just as well with any script, including your own custom static or dynamic scripts. Speaking of dynamic scripts, we have a new trick for that too… coming up next…

The corresponding presentation for this discussion is available here:

Adobe PDFWordPress Plugin Tips & Tricks Apr 2012

Posted on

WordPress and JavaScript Part 1

WordPressIntroduction

For those that were not present, we had a discussion that was about wpCSL and using JavaScript in a WordPress plugin.

The part of the discussion that would be of interest to the general public revolved around the use of wp_register_script and wp_enqueue_script and the best practices for implementing scripts.

WoAdobe PDFrdPress Plugin Tips & Tricks Mar 2012

 The Key Points

  1. Call your function to REGISTER scripts early in the action stack for WordPress. Typically hooking into the wp_enqueue_scripts action.
  2. Call your function to ENQUEUE the scripts when you know you’ll need them. Typically this should be when the shortcode is rendered. This prevents your scripts from loading on EVERY page in Wordpress.
  3. There are three basic script types, per my definition of scripts, that are important:
    1. Built-in ScriptsWordPress has approximately 30 scripts that ship with or are directly accessible from within WordPress.
    2. Static Scripts: your custom javascript that depends on no external PHP variables or data from the database
    3. Dynamic Scripts: custom javascript that references PHP variables or data from the database
  4. Dynamic scripts can use the ob_start()/ob_content() feature of PHP to render the JavaScript.
  5. Hook dynamic scripts in LATE in the action stack of WordPress, I prefer wp_print_footer_scripts.
  6. Dynamic scripts implemented this way should use a global flag (a property of our wpCSL driver class in our case) to only render the script when the shortcode was rendered. Unlike enqueue_script this footer action hook is called for ALL pages.

Summary

There are a couple of follow up discussion based on findings from working “in the field” on client systems. Those will be posted next.

Posted on

Upgrade Issues from MooTools 1.2.4 to Mootools 1.3.2

This past week we worked on some site updates for Abundatrade.  During the updates we attempted to upgrade Mootools from 1.2.4 to 1.3.2.  Unfortunately this did not go as well as expected.  After 8 hours of trying to get it to work we ended up rolling back to Mootools Core 1.2.4 with Mootools More 1.2.5.1.   Here are some of the pitfalls.

$empty Is Not Defined

The first problem was with the FormCheck library from floor.ch.   The library requires the “old-school” $empty function definition from MooTools.   This has been deprecated in later versions.   It also turns out it is a pain to replicate, though we were able to patch around this by adding a this.$empty function() {} definition to the JavaScript library.    After doing so we ran into more problems with undefined methods so we gave up and ended up loading MooTools Core 1.3.2 with compatibility.  That resolved both the $empty definition problem as well as some other issues we had with failing code.

Unintended Recursion

The bigger problem that forced us back to v1.2.4 was an unintended recursion problem in one of our AJAX calls that queues and consumes requests to/from a back-end server script that feeds JSON back into the main web document. With all versions up to 1.3.X the system works as we expect, you put in a UPC, click “Add Item”, it is sent to the back-end for real time pricing lookups, and a single row is added to an on-page table showing the item and the offer price. With version 1.3.2 the call to the back-end system is now working as a factorial function.  The first time you add an item you get one call to the back-end. The second time you get 2 calls, by the 6th added item you have a table full of duplicates that is growing exponentially. Not good.

We dug around for answers for most of the day yesterday, but nothing obvious was uncovered. The basic culprit is a form submit handler that eventually does something like this:

function MyHandler() {
… this.set(‘send’,func () { do stuff; });
this.send();
}

The first time through it works perfectly. Subsequent iterations are looping through the this.set call, as if this is now an array of handler objects.  There must be a way to reset the form handler stack to be a single instance, but damned if we can find it. The problem appears to be triggered by a change in the MooTools library that now handles the anonymous function definition differently as it is no “array aware”.

MooTools 1.2.X Problems

Unfortunately, staying with MooTools 1.2.4 presents another problem.  The spinner class breaks for Internet Explorer 9.  With the spinner class in place the submit form handler fails.   Thus for MooTools 1.2.4 we are stuck with a subset of the UX.

The failing code:

        document.id('top_content').set('spinner',
            {
                hideOnClick:true
            }
            );
        document.id('top_content').spin();

 

Summary

There is probably a design flaw in our code, but it is not easy to unwrap and simply turning on MooTools 1.3.2 with compatibility mode is not fixing it.  So much for the easy way out.  For now we’re back to MooTools 1.2.X and moving on.  Other projects await.   If you have any hints on what the issue may be please share.

Posted on

Logistics & Inventory Management with Alutiiq

Alutiiq recently award Cyber Sprocket a 1-year teaming agreement, making this our 4th year of working with Alutiiq on developing, supporting, & maintaining their military logistics & inventory management application.  We are very excited to be working with Alutiiq for another year.  The upcoming year will bring some exciting new possibilities for follow on projects that augment the system already in place.  We’re looking forward to being part of the design & development team and supporting our clients and our country both at home and abroad.

Technical Overview

Services Provided

  • Web Application Programming
  • Database Design
  • Database Maintenance
  • System Architecture
  • Network Support

Platform Details

Posted on

Consumer Web Apps with Abundatrade

When Abundatrade decided to take their project to the next level they chose Cyber Sprocket Labs to help them get there.   They brought their existing website to us and asked us to help.  They were looking for a more fluid, more enjoyable web experience for their users.   They needed an updated easy-to-use web calculator & they needed it fast.

Cyber Sprocket did the job quickly & did it right.   More than a year after that first quick “help us fix our site” project we are still helping them push their technology further.   We are now not only helping them slowly morph their consumer services into something bigger & better, we are also helping them run their operations more efficiently by integrating the web technologies with their daily operations & services that run the business.

The main part of the consumer interface is a product valuation calculator.  Using a proprietary algorithm the system looks up a bar code on a product that a consumer enters and runs a series of data queries against a variety of popular online stores such as Amazon to determine a fair market valuation on the product.  The system then compares that to current stock levels within the Abundatrade warehouse and generates a real-time trade-in value for the consumer.

During our first year with Abundatrade we have helped them improve the user experience, refined the user interface, and given them some valuable ideas and insight into how technology can make their business more efficient.   We are looking forward to forging an even closer relationship with Abundatrade in the coming year in both a business sense… and a physical sense; Abundatrade is now our closest neighbor – literally just a few hundred yards away from our new Mount Pleasant home!

We are looking forward to another fun-filled and exciting year working with Abundatrade and helping them grow!

Thanks Kent & Clayton, we appreciate working with you!

Technical Overview

Services Provided

  • Web Application Programming
    • PayPal API
    • Amazon API
    • Monsoon API
    • 3rd Party Music DB API
  • Web Interface Design
  • Process Flow Analysis

Platform Details

Posted on

Anonymous Functions With Names?

I discovered an odd thing about JavaScript last night. As you know, one way to add methods to an object is to assign anonymous functions to property names. For example:

var foo = {
    woo: function (鯣) {
        print(鯣);
    }
};

Strictly speaking, our function has no name. We just happen to assign it to a property which we can use to call the function. Contrast that to the ‘normal’ way of defining functions:

function woo(色魚) {
    print(色魚);
}

But here’s the weird thing, we can combine these two styles.

var foo = {
    woo: function specialHiddenName(鯣) {
        print(鯣);
    }
};

We get no error for this. Interestingly, I could not find a way to call the function using specialHiddenName. So it looks like the JS engine just throws it away.

I don’t think this behavior could ever be useful, but there may be some creative way to (ab)use it. An extreme form of self-documenting code?

var foo = {
    woo: function PrintsTheArgumentAndReturnsNothing(鯣) {
        print(鯣);
    }
};

No—this idea is horrible. Paul, you had better not do this.

Posted on

Pitfalls With Optional Arguments

Let’s talk about a couple of problems we can run into when writing functions that have optional arguments.

First there is the matter of how we should declare such functions to begin with. If our function can take any number of arguments then it is easiest to use the ‘arguments’ array inside of the code. This array[1] is always available inside of our functions, so if we have an unknown number of parameters we can loop through it to get all of them.

function Σ() {
    var total = 0;

    Array.forEach(
        arguments,
        function (n) {
            total += n;
        },
        this
    );

    return total;
}

print(Σ(2, 1, 10, 35));

If we have a fixed number of arguments, but some are optional, then I think it is best if we go ahead and write out all of the argument names in the declaration. This will not cause an error even if we do not pass in those values. Let’s consider this trivial function:

/**
 * Accepts one or two arguments.  Given one, it adds 100 to it.
 * If given both, it adds them together.
 */
function add(x, y) {
    var y = y || 100;
    return x + y;
}

print(add(10));    // Prints 110

We use ‘||’ here as an idiom for assigning a default value to ‘y’. We assign to either itself if it has a false value, or 100 if it doesn’t have one. This is where we can shoot ourselves in the foot. The important part is that the idiom assigns the default when the variable has a _boolean false_ value. Consider this error.

print(add(20, 0));    // Prints 120, not 20

If it makes sense for our arguments to have boolean false values, i.e. ‘false’, zero, empty string, or null, then we have to be a little more verbose in our test for assigning the default value.

function add(x, y) {
    var y = (typeof y !== "undefined") ? y : 100;
    return x + y;
}

print(add(20, 0));    // Prints 20

We need to be careful when writing functions that take optional arguments, but where those optional arguments can meaningfully have false values. The safest thing we can do is see if the type of the values are undefined. But if we do not need to worry about boolean false values, then the ‘||’ method is both easier to read and faster.

Notes

  1. The ‘arguments’ array is not _exactly_ an array, because we can’t do everything with it that we can with a normal array. If we add items to the array, its ‘length’ property is not updated accordingly. We also cannot call ‘arguments.forEach()’. As you see in the example, we have to call Array.forEach() on it.
  2. Apparently you can use Greek characters in function names. At least with Mozilla’s Javascript engine. You can’t use any arbitrary Unicode characters though. My attempt to define ☃() failed.