You are viewing the Articles tagged in html5

Polymer Behaviors in ES6

Being a typical aspect of Object Oriented Design, inheritance, and mixins, provide the means by which modular reuse patterns can be facilitated within a given system. Similarly, Polymer facilitates code reuse patterns by employing the notion of shared behaviors modules. Let’s take a quick look at how to leverage them in Polymer when using ES6 classes.

Implementing Behaviors

Implementing a Behavior is quite simple, just define an object within a block expression or an IIFE, and expose it via a namespace, or module loader of choice:

some-behaviors.js

Then, include the behavior in a corresponding .html document of the same name so as to allow the behavior to be imported by subsequent elements:

some-behavior.html

Extending Behaviors

After having defined and exposed a given Behavior, the Behavior can then be extended from element classes by defining a behaviors getter / setter as follows:

Once the behavior has been extended, simply import the behavior in the element’s template (or element bundle, etc.) and it is available to the template class:

Try it

Implementing Multiple Behaviors

Similar to individual behaviors, multiple behaviors can also be defined and extended:

first-behavior.js

second-behavior.js

In certain cases, I have found it helpful to group related behaviors together within a new behaviors (array) which bundles the individual behaviors together:

Note: As can be seen in the FourthBehavior, a behavior can also be implemented as an Array of previously defined behaviors.

Extending Multiple Behaviors

As with extending individual behaviors, multiple behaviors can also be extended using a behaviors getter / setter. However, when extending multiple behaviors in ES6, there are syntactic differences which one must take note of. Specifically, the behaviors getter must be implemented as follows:

Try it

And that’s basically all there is to it. Hopefully this article helped outline how Polymer Behaviors can easily be leveraged when implementing elements as ES6 classes. Enjoy.

Property Change Observers in Polymer

When building Web Components the ability to observe property / attribute changes on custom elements and respond to them accordingly can prove quite useful.

Fortunately, Polymer makes this incredibly easy. Let’s take a quick look …
(note, we’ll be using ES6 here)

Single Property Observers

In it’s most basic form, a Single Property Observer can be defined by simply implementing a method and adding it to the property’s observer configuration:

Now, whenever the property changes, Polymer will automatically invoke the observer method; handily passing two arguments: the updated value, and the previous value:

Try it

Pretty cool, right? It gets even better…

Multi-Property Observers

In addition to Single Property Observers, multiple properties can be observed for changes using the observers array:

The observers array is rather self-explanatory: each item is simply a string representation of the method to be invoked with the observed properties specified as arguments:

Try it.

For more information, see multi-property-observers.

Sub-Property Observers

Similar to Multi-Property Observers, sub-properties can be observed as well (e.g. user.username, or user.account.name, etc.). For instance:

Try it

Deep Sub-Property Observers

As with explicit Sub-Property Observers, (n-level) arbitrary sub-properties can be observed using wildcard notation:

Try it.

Both Sub-Property Observers and Deep Sub-Property Observers differ from Single-Property Observers in that a changeRecord is passed to the observer method as opposed to the updated value. A changeRecord is simply an object which contains the following properties (as per the Polymer Docs):

  • changeRecord.path: Path to the property that changed.
  • changeRecord.value: New value of the path that changed.
  • changeRecord.base: The object matching the non-wildcard portion of the path.

It’s important to keep in mind that Sub-Property, and Deep Sub-Property observations can only be made using either property bindings or the set method.

Array Mutation Observers

Complimentary to Single, Multi, Sub, and Deep Property Observers, Polymer provides Array Mutation Observers which allow for observing Array and Array element properties for changes.

This is where the API requires a little getting used to IMHO, and so I would recommend reading the Docs in detail.

That being said, Array Mutation Observers are quite powerful, for example:

Try it.

When observing Arrays, in order for bindings to reflect properly, Polymer’s Array Mutation Methods must be used. This is quite simple in that the API is the same as that of the corresponding Native Array methods, with the only difference being the first argument is the path to the array which is to be modified. For example, rather than: this.items.splice(...) one would simply use: this.splice('items', ...).

Conclusion

Hopefully this simple introduction to Polymer Observers has demonstrated some of the powerful capabilities they provide. Understanding how each can be implemented will certainly simplify the implementation of your custom elements, therefore leveraging them where needed is almost always a good design decision.

Feel free to explore any of the accompanying examples.

Simplifying Designs with Parameter Objects

Recently, while reading the HTML5 Doctor interview with Ian Hickson, when asked what some of his regrets have been over the years, the one he mentions, rather comically so as being his “favorite mistake”, also happened to be the one which stood out to me most; that is, his disappointment with pushState; specifically, the fact that of the three arguments accepted, the second argument is now ignored.

I can empathize with his (Hixie’s) frustration here; not simply because he is one of the most influential figures on the web – particularly for his successful work surrounding CSS, HTML5, and his responsibilities at the WHATWG in general – but rather, it is quite understandable how such a seemingly insignificant design shortcoming would bother such an obviously talented individual, especially considering the fact that pushState's parameters simply could not be changed due to the feature being used prior to completion. Indeed, the Web Platform poses some very unique and challenging constraints under which one must design.

While the ignored pushState argument is a rather trivial issue, I found it to be of particular interest as I often employ Parameter Objects to avoid similar design issues.

Parameter Objects

The term “Parameter Object” is one I use rather loosely to describe any object that simply serves as a wrapper from which all arguments are provided to a function. In the context of JavaScript, object literals serve quite well in this capacity, even for simpler cases where a function would otherwise require only a few arguments of the same type.

Parameter Objects are quite similar to that of an “Options Argument” – a pattern commonly implemented by many JavaScript libraries to simplify providing optional arguments to a function; however, I tend to use the term Parameter Objects more broadly to describe a single object parameter from which all arguments are provided to a function, optional arguments included. The two terms are often used interchangeably to describe the same pattern. However, I specifically use the term Options Argument to describe a single object which is reserved exclusively for providing optional arguments only, and is always defined as the last parameter of a function, proceeding all required arguments.

Benefits

Parameter Objects can prove beneficial in that they afford developers the ability to defer having to make any final design decisions with regard to what particular inputs are accepted by a function; thus, allowing an API to evolve gracefully over time.

For instance, using a Parameter Object, one can circumvent the general approach of implementing functions which define a fixed, specific order of parameters. As a result, should it be determined that any one particular parameter is no longer needed, API designers need not be concerned with requiring calling code to be refactored in order to allow for the removal of the parameter. Likewise, should any additional parameters need to be added, they can simply be defined as additional properties of the Parameter Object, irrespective of any particular ordering of previous parameters defined by the function.

As an example, consider a theoretical rotation function which defines five parameters:

Using a Parameter Object, we can refactor the above function to the following:

Should we wish to remove a parameter from the function, doing so simply requires making the appropriate changes at the API level without changing the actual signature of the function (assuming of course, there are no specific expectations already being made by calling code regarding the argument to be removed). Likewise, should additional parameters need to be added, such as a completion callback, etc., doing so, again, only requires making the appropriate API changes, and would not impact current calling code.

Additionally, taking these potential changes as an example, we can also see that with Parameter Objects, implementation specifics can be delegated to the API itself, rather than client code insofar that the provided arguments can be used to determine the actual behavior of the function. In this respect, Parameter Objects can also double as an Options Argument. For example, should the arguments required to perform a 3D rotation be omitted from the Parameter Object, the function can default to a 2D rotation based on the provided arguments, etc.

Convenience

Parameter Objects are rather convenient in terms of there being less mental overhead required than that of a function which requires ordered arguments; this is especially true for cases where a function defines numerous parameters, or successive parameters of the same type.

Since code is generally read much more frequently than it is written, it can be easier to understand what is being passed to a function when reading explicit property names of an object, in which each property name maps to a parameter name, and each property value maps to parameter argument. This can aid in readability where it would otherwise require reading the rather ambiguous arguments passed to a function. For example:

With Parameter Objects it becomes more apparent as to which arguments correspond to each specific parameter:

As mentioned, if a function accepts multiple arguments of the same type, the likelihood that users of the API may accidentally pass them in an incorrect order increases. This can result in errors that are likely to fail silently, possibly leading to the application (or a portion thereof) becoming in an unpredictable state. With Parameter Objects, such unintentional errors are less likely to occur.

Considerations

While Parameter Objects allow for implementing flexible parameter definitions, the arguments for which being provided by a single object, they are obviously not intended as a replacement for normal function parameters in that should a function need only require a few arguments, and the function’s parameters are unlikely to change, then using a Parameter Object in place of normal function parameters is not recommended. Also, perhaps one could make the argument that creating an additional object to store parameter/argument mappings where normal arguments would suffice adds additional or unnecessary overhead; however, considering how marginal the additional footprint would be, this point is rather moot as the benefits outweigh the cost.

A Look at pushState’s Parameters

Consider the parameters defined by pushState:

  1. data: Object
  2. title: String
  3. url: String

The second parameter, title, is the parameter of interest here as it is no longer used. Thus, calling push state requires passing either null or an empty String (recommended) as the second argument (i.e. title) before one can pass the third argument, url. For example:

Using a Parameter Object, pushState could have been, theoretically, implemented such that only a single argument was required:

  1. params: Object
    • data: Object
    • title: String
    • url: String

Thus, the ignored title argument could be safely removed from current calling code:

And simply ignored in previously implemented calls:

As can be seen, the difference between the two is quite simple: the specification for pushState accepts three arguments, whereas the theoretical Parameter Object implementation accepts a single object as an argument, which in turn provides the original arguments.

Concluding Thoughts

I certainly do not assume to understand the details surrounding pushState in enough detail to assert that the use of a Parameters Object would have addressed the issue. Thus, while this article may reference pushState as a basic example to illustrate how the use of a Parameter Object may have proved beneficial, it is really intended to highlight the value of using Parameter Objects from a general design perspective, by describing common use-cases in which they can prove useful. As such, Parameter Objects provide a valuable pattern worth considering when a function requires flexibility.

External Templates in jQote2

The jQote2 API Reference provides plenty of useful examples which are sure to help users get up and running quickly. I found it a bit unclear, though, as to how templates could be loaded externally as, in the reference examples, templates are defined within the containing page. For the sake of simplicity this approach certainly makes sense in the context of examples. However, in practice, templates would ideally be loaded externally.

While jQote2 provides a perfect API for templating, it does not provide a method specifically for loading external templates; this is likely due to the fact that loading external templates could easily be accomplished natively in jQuery. However, since this is a rather common development use case, having such a facility available would be quite useful.

After reviewing the comments I came across a nice example from aefxx (the author of jQote2) which demonstrated a typical approach to loading external templates which was simular to what I had been implementing myself.

And so, I wrote a simple jQuery Plug-in which provides a tested, reusable solution for loading external templates. After having leveraged the Plugin on quite a few different projects, I decided to open source it as others may find it useful as well.

Using the Plugin

Using the jQote2 Template Loader plugin is rather straight forward. Simply include jQuery, jQote2 and the jquery.jqote2.loader-min.js script on your page.

As a basic example, assume a file named example.tpl exists, which contains the following template definition:

We can load the example.tpl template file described above via $.jqoteload as follows:

After example.tpl has been loaded, from another context we can access the compiled templates via their template element id. In this example "articles_tpl".

You can grab the source and view the example over on the jQote2 Template Loader Github page.

Function Overwriting in JavaScript

Whether intentional, or simply a by-product of it’s design, Javascript, being a dynamic language, allows for a level of expressiveness which most any seasoned programmer would come to appreciate. Javascript naturally provides the ability to implement some rather intriguing and quite unique patterns; one of which is the ability to overwrite a function at runtime.

Function Overwriting

Function Overwriting (also known as “Self-Defining Functions” or “Lazy Defining Functions”) provides a pattern which, as stated above, allows for overwriting a function’s definition at runtime. This can be accomplished from outside of the function, but also from within the function’s implementation itself.

For example, on occasion a function may need to perform some initial piece of work, after which, all subsequent invocations would result in unnecessarily re-executing the initialization code. Typically, this issue is addressed by storing initialization flags or refactoring the initialization code to another function. While such a design solves this problem, it does result in unnecessary code which will need to be maintained. In JavaScript, perhaps a different approach is in order: we can simply redefine the function after the initialization work has been completed.

A possible candidate use-case for Function Overwriting is Feature Detection as, detecting for specific feature support in the Browser typically only needs to be tested once, at which point subsequent tests are unnecessary.

Below is a basic example of implementing Function Overwritting in the context of an abstraction of the HTML5 Geolocation API.

Considerations

Since functions are objects in Javascript, it is important to keep in mind that if you add a property or method to a function (either statically or via the function’s prototype), and then overwrite the function, you will have effectively removed those properties or methods as well. Also, if the function is referenced by another variable, or by a method of another object, the initially defined implementation will be preserved and the overwriting process will not occur. As such, be mindful when implementing this pattern. As a general rule of thumb, I typically only implement Function Overwriting when the function being redefined is in a private scope.

Concluding Thoughts

As you can see, Function Overwriting provides a convenient facility for optimizing code execution at runtime. There are many use-cases for dynamically overwriting functions and, where appropriate, they can certainly provide value in terms of performance and code maintainability.

Below you can find an example which demonstrates two basic Function Overwriting implementations. Simply load the page and add some breakpoints in Firebug to test the execution paths; both before and after overwriting each function occurs, or you can simply view the source.
Example

jQuery Mobile 1.0 Released

, the jQuery Mobile Team announced the official release of jQuery Mobile 1.0.

Having worked with jQuery Mobile since Alpha 1, in the time since, the framework has certainly evolved into a mature, premier platform on which Mobile Web Applications can be built.

On a personal note, as I am currently in the process of working towards the release of a multi form-factor Mobile Web Application built on jQuery Mobile, the 1.0 release couldn’t have come at a better time.

Be sure to check out the updated API Docs, especially the new Data Attributes section.

jQuery Mobile 1.0 represents a significant milestone in the Mobile Web Space. I am certainly excited to see what is on the roadmap next.