PJAX-Standalone version 0.6.0 released

As the first major bit of work I’ve done on PJAX-Standalone (Pushstate AJAX) in quite some time (aside from the occasional bug fix), version 0.6.0 of PJAX-Standalone includes a totally overhauled demo site (saving future PJAX uses from the horror of encountering my design skills), in addition to the bug fixes, code tweaks and features I was initially planning.

Key changes include:

  • Updated docs & demo
  • Options to enable/disable autoAnalytics and returnToTop
  • Universal Analytics support
  • Access to request information in callbacks via event.data
  • Fixes for title handling & control click not working

A fuller list of changes found in the new version can be found in this github pull request.

The new and improved PJAX-standalone sample site is also now live.

By Carl on January 30th, 2014 in General

Simple JavaScript Templating

While working on a little side project of mine, I came across the need for a really simple method of performing HTML templating within JavaScript. Since JQuerys method had been deprecated, and seeing as I had no real requirement for any fancy functionality, I decided to quickly throw together my own implementation, which can be grabbed below.

 /**
 * TPL provides an ultra light weight, super simple method for quickly doing HTML templating in javascript.
 * @author Carl Saggs
 * @version 0.2
 * @source https://github.com/thybag/base.js
 */
 (function(){

	/**
	 * template
	 * Template a HTML string by replacing {attributes} with the corisponding value in a js Object.
	 * @param String (Raw HTML or ID of template node)
	 * @param JS Object
	 * @return NodeList|Node
	 */
	this.template = function(tpl, data){
		//Find out if ID was provided by attempting to find template node by ID  
		var el = document.getElementById(tpl);
		// If result is null, assume was passwed raw HTML template
		if(el !== null) tpl = el.innerHTML;
		//transform result in to DOM node(s)
		var tmp = document.createElement("div");
		tmp.innerHTML = replaceAttr(tpl,data);
		var results = tmp.children;
		//if only one node, return as individual result
		if(tmp.children.length===1)results = tmp.children[0];
		return results;
	}

	/**
	 * replaceAttr
	 * Replace all {attribute} with the corisponding value in a js Object.
	 * @param String (raw HTML)
	 * @return String (raw HTML)
	 * @scope private
	 */
	var replaceAttr = function(tpl, data, prefix){
		//Foreach data value
		for(var i in data){
			//Used for higher depth items
			var accessor = i;
			if(typeof prefix !== 'undefined') i = prefix+'.'+i
			//If object, recusivly call self, else template value.
			if(typeof data[i] === 'object'){
				tpl = this.replaceAttr(tpl, data[i], i);
			}else{
				tpl = tpl.replace(new RegExp('{'+i+'}','g'), data[accessor]);
			}
		}
		//return templated HTML
		return tpl;
	}

	//Add tpl to global scope
	window.tpl = this;
}).call({});

Essentially the code just provides a simple way of passing in some arbitrary HTML markup, then swapping out any contained {bla} tags with the values stored in the associated JavaScript object.
Say for example we had a array of people objects and we wanted to apply a simple template to them, before appending them in to our document. To do this you could use code similar to the following:

var test = [
	{"name":"Dave","age":22},
	{"name":"James","age":42},
	{"name":"Tim","age":27}
];
test.forEach(function(personObj){
	var el = tpl.template("<div class='person'><strong>{name}</strong><span class='right'>{age}</span></div>",personObj);
	document.body.appendChild(el);
});

Alternately if you had some more complex markup, or just wanted to separate the templates from the general script a little more, you can specify your template HTML in script tags (or any other elements) and reference them by id. For the example above you would just have something like this within your html document

<script id='myTemplate' type='text'>
	<div class='person'>
		<strong>{name}</strong>
		<span class='right'>{age}</span>
	</div>
</script>

Which could then be utilised in the following manner.

var el = tpl.template("myTemplate", personObj);

The script will also happily support passing in multidimensional objects which can be used in the templates as obj.attr.anotherattr etc.

As with most code I write, the source is on github and may be updated periodically with bug fixes and new features. Currently my templating method is incredibly basic and has almost no features compared to pretty much all others out there. That said, it does what I need it to, so its not all bad 🙂

Thanks for reading,
Carl

PHP SharePoint Lists API release

A new version of my PHP SharePoint Lists API has now been released; the new version includes multiple bug fixes, optimisations and a number of new features.

The most notable new feature of the PHP SharePoint Lists API is the query method. The query function allows users to run complex query’s against sharepoint lists using an easy to follow and expressive SQL like syntax.

For example, using the query feature you can easily query a list of pets to return all items relating to dogs under 5, ordered by age.

$sp->query('list of pets')
   ->where('type','=','dog')
   ->and_where('age','<','5')
   ->sort('age','ASC')
   ->get();

“OR” querys can also be used, for example, if you wanted to return a list of 10 pets that were either cats or dogs, you might write:

$sp->query('list of pets')
   ->where('type','=','cat')
   ->or_where('type','=','dog')
   ->limit(10)
   ->get();

The PHP SharePoint Lists API is available on Github and can be used for free in any projects you may wish (under the terms of the MIT Licence). You can download it directly by clicking here.

PJAX-Standalone – Pushstate Ajax

PJAX or Pushstate AJAX is a fairly new twist on the traditional AJAX page loading idea, although unlike its predecessors PJAX takes advantage of the new Pushstate history API’s in order to provide it with real permalinks and history as opposed the the document.hash based hacks which the former has had to make do with.

The result is that its now possible to gain the performance boosts that AJAX page loading makes possible, across the majority of the major browsers (IE not included), without any fear of compromising backwards compatibility or the native behaviours of the browser (back button etc).

Unfortunately the main source of PJAX goodness is JQuery plugin ( jquery-pjax) meaning that those who favour alternative JavaScript frameworks – or even none at all – are left out in the cold.

To remedy this, I decided to create my own standalone implementation of PJAX (Which I insightfully named as PJAX-Standalone). Like its counterpart PJAX-standalone was designed to be highly customisable while at the same time, incredibly easy to get working. For many webpages nothing more than the addition of an ID to your content container and a single call to the PJAX-Standalone script is required.

For those who want more functionality a number of callbacks can also be set in addition to being able to invoke PJAX page loading programmatically as well.

You can see an example of the script in action on the PJAX-Standalone demo page.

Full details on how to use and configure PJAX-Standalone can be found on  Github.

Ubuntu 11.10 – Setting up with LXDE

I like Ubuntu, it’s not every ones favourite linux distribution, but for me, it’s always done what I’ve needed it to. Installation is simple and painless, and almost everything I want comes with it out of the box. Or at least it used to.

Maybe I’m just falling into the “I hate change” trap, but Unity, for me at least, just isn’t what I’m after. Despite a number of attempts to get used it it,  it just  feels awkward to use and doesn’t really fit with the way I want to interact with my computer. Switching back to the gnome environment doesn’t really do the trick either, as I just find myself annoyed at how the gnome 3 “classic” mode has stripped out so many of the features I took for granted. Gnome 3 itself… lets not even go there. So there is the problem, as much as I like Ubuntu, it no longer provides me with an interface I’m comfortable with.

Rather than just continue to moan about all this stuff at great length, I decided I would actually spend a little time being semi-constructive and have a tinker with some of the other options out there (XFCE  and LXDE being the main contenders). Since I’ve used xfce in the past, I opted to give my attention to LXDE.

I already had a blank Ubunutu 11.10 installation sitting around in VirtualBox, so I decided to use that as my base, rather than downloading and installing the proper lubuntu installation.

To begin, I booted up virtual box and logged in to the Ubuntus default unity environment. Then to add the LXDE desktop, I opened up the terminal and ran:

sudo apt-get install lxde

After agreeuing to its demands (50 or so mb of space) and waiting for it to complete, I logged out, switched my environment from “Unity” to “LXDE” (right click the cog next to the login box to select this) and logged back in.

I was then greeted by the following functional (although not especially pretty) desktop.

LXDE Default Desktop

LXDE Default Desktop

Although not as fully featured as gnome, I was happy to find the interface provided pretty much everything I wanted (including the ability to freely customise the panels). The only real issues I found with the interface, was the clunky and cluttered menu, and its (in my opinion) somewhat unattractive looks. Thankfully, this being Linux, both issues were fairly straightforward to solve.

My first target was the start menu, having come from a windows system the thing I missed most in the menu was the ability to quickly search for what I was after. To solve this problem, I opted to use Cardapio as it offered the above functionality in addition to being stand alone (making it easy to get running).

To get cardapio installed, you’ll want to run the following 3 commands in the terminal which will add the cardapio repository and then download cardapio itself (along with  tracker – in order to allow file searches, and python-glade2 which is a missing dependency of cardapio).

sudo add-apt-repository ppa:cardapio-team/unstable
sudo apt-get update
sudo apt-get install cardapio tracker python-glade2

Once cardapio is installed, the next step is the slighly more difficult task of setting it up in place of the default start menu. Since I was unable to find any reliable documention on how to do this properly, I fiddled around and finally settled on the solution of “botching” it by replacing the panels “Menu” with an “Application launch bar” containing only the cardapio icon.

To do this right click the taskbar and select “Add / Remove panel items”. Then in the dialog, select “Add” and “Appliction launch bar”. This should place the new “appliction launch bar” on the end of the panel, use the up button to move it in front of the existing “Menu”. Double clicking this will now give you the opportunity to add applictions to the “launch bar”. Unfortunately, Cardapio is no where to be seen.

This is becuse cardapio by deafult is set to hidden. To fix this, in your terminal window run.

sudo nano /usr/share/applications/cardapio.desktop

Then using nano, change the value of “NoDisplay” from true to false and save over the original file.

On opening your appliction launch bar again, you should now find Cardapio helpfully listed under “Accessories”. Hit add to move it in to the Launcher, then close the window and give it a try.

With a decent start manager now in place, the next step is just to pretty it up.

To start with I right click the task bar, selected “Panel Settings” and changed the panel Edge to “top” (to place the panel at the top of the desktop). Then in the “Appearance” tab, I change from “Image” to solid “color (with optacity)” and adjusted the colour and opacity in order to provide a semi-transparent black taskbar.

Next, install avant-window-navigator (my dock of choice) using:

sudo apt-get install avant-window-navigator

Once installed, open the start menu and select AWN (just search avant) which should start it running. Don’t worry that it looks hidious at this point. Just right click the dock and select dock preferences, then in the main panel tick the box that says “start Awn automatically” and close it.

To make AWN (Avant Window Navigator) display correctly, you will now need to install and enable a “compositor”. I opted to use “xcompmgr” for this purpose. Install it using:

sudo apt-get install xcompmgr

And to ensure it starts up whenever your copy of ubuntu does, You’ll need to create it a new startup entry.

Run:

sudo nano /etc/xdg/autostart/XCompmgr.desktop

And add the following data:

[Desktop Entry]
Encoding=UTF-8
Name=XCompmgr
Type=Application
Comment=XCompmgr--a light compositor
Exec=xcompmgr
Terminal=false
OnlyShowIn=LXDE

Once this is done, save, then  logout and in again to see the effects.

Now you have a dock, there is not much point having your running applictions listed up top, so right click the panel, select “add/remove items” and remove the “Task bar” and any other unwanted bits from it.

You can also right click AWN and select a more fitting theme within dock preferences.

To finish off prettying up the desktop, I’d suggest changing the desktop background by right clicking the desktop, selecting preferences and then setting it to use an image of your choice. Adjusting the Theme can then be done using lxAppearence (I stuck with clearlook but switched the highlight colour from orange to dark grey) and Configure the window chrome using the “openbox configution manager”. I switched the theme from “Onyx” to “Carbon”.

The end result, with a little luck should now be a somewhat prettier looking LXDE, with a decent start menu and a nice dock. What’s more, even with all the extra stuff, It’s still quite noticeably nippier than both Unity and Gnome.

LXDE Tweaked

LXDE Tweaked

As one final task for those using the AutoLogin feature in Ubuntu, you will need to set Ubuntu to use LXDE by default. You can do this with the following command:

sudo /usr/lib/lightdm/lightdm-set-defaults -s LXDE