<?xml version='1.0' encoding='ISO-8859-1' ?>

<rss version='2.0'>
	<channel>
		<title>Mitya.co.uk | Javascript and general front-end dev blog</title>
		<link>http://www.mitya.co.uk</link>
		<webmaster>rss@mitya.co.uk</webmaster>
		<lastBuildDate>2011-12-12 18:27:00</lastBuildDate>
		<image>
			<url></url>
			<link>http://www.mitya.co.uk</link>
		</image>
		<description></description>
		<ttl>5</ttl>
		<language>en-gb</language>

		<item>
			<title>Distinguishing real events from simulated events</title>
			<link>http://www.mitya.co.uk/blog/2012/Apr/Distinguishing-real-events-from-simulated-events-209</link>
			<description>Simulated events are one of the real joys of jQuery. Geniusly, to simulate an event in jQuery you simply call the method relating to the event in question (or use the trigger() method) without any arguments.

[VISIT THE LINK FOR THE CODE].

This is a common situation. Here, I have some tabs which, when clicked, show a corresponding tab content area, which are all hidden to start with. By simulating the event on the first tab, it is automatically turned on as though we had clicked it ourselves.

(Yes, I could avoid this by having the first tab area showing by default via CSS, but let's imagine our event handler does more than simply show and hide DIVs, but also some more complex code).

So far, so easy, and so common. But how do you differentiate a simulated event from a real one?

I had a situation the other day where I had a carousel-like widget on the page, and a bigger version of the same carousel, hidden, to appear in a lightbox should the user wish. Traversing one of the carousels (i.e. changing slide) should update the other one, too.

Consider the following.

[VISIT THE LINK FOR THE CODE].

There, we listen for clicks to the left/right buttons of each carousel and then simulate the same click on the other carousel.

But there's an obvious problem; the simulated click uses the same event handler, so it too will invoke a simulated click on the first carousel, and so on and so on, without end.

What we actually want, of course, is for a simulated click to occur only in response to a real click. In other words, how do we spot the difference between a real and simulated event with jQuery?

Simple: with a simulated event, the originalEvent property of the event object will be undefined, whereas with a real event it will be the native event object.

[VISIT THE LINK FOR THE CODE].

Obviously you don't have to simulate events - you could assign their callbacks to a named function and call the function manually. But then you'd have no event object passed, so this often means filling your code with lots of conditions - to work both as an event callback and as a direct function call. Simulated event calls save the need for this reengineering.</description>
			<pubDate>2012-04-28 17:56:00</pubDate>
		</item>
	
		<item>
			<title>Non-AJAX use for jQuery's deferred objects</title>
			<link>http://www.mitya.co.uk/blog/2012/Apr/Non-AJAX-use-for-jQuerys-deferred-objects-207</link>
			<description>I'm currently writing another article for .NET magazine on the newer features of jQuery, for developers who perhaps got comfy with jQuery 1.3 or 1.4 and didn't keep up.

One of the obvious candidates for the article is deferred objects, which landed in jQuery 1.5 as part of the overhaul to jQuery's AJAX module.

AJAX is the obvious use-case for deferred objects, and it's simple to come up with examples for that. But I was also trying to show a non-AJAX example.

I'm talking about cases where you would manually make your own deferred objects and apply subjective logic as to whether, when and how it is resolved or rejected. So other forms of asynchronous code execution.

This is quite a different beast from using deferreds with AJAX, since, at least usually, jQuery's AJAX methods automatically create, return and resolve/reject deferred objects for you. In other words, you can use deferreds in an AJAX context without ever going near methods like $.Deferred(), $.when() or deferred.resolve().

[h]Click the vowels[/h]

I eventually came up with a slightly contrived game for children where they have to identify and click the vowels in a sequence of words. Each vowel would constitute a deferred object. When clicked, the vowel fades out and its deferred object is set to resolved. When all deferreds are resolved (i.e. all vowels have been clicked), we give feedback and move on. I think it's quite a nice pattern.

You can see a demo of the game here.

First, some simple HTML:
[VISIT THE LINK FOR THE CODE].

And CSS:
[VISIT THE LINK FOR THE CODE].

Now on to the JS (all inside a DRH, of course, as we're dealing with the DOM).

[VISIT THE LINK FOR THE CODE].

All rather self-explanatory. Now for the bulk of the code:

[VISIT THE LINK FOR THE CODE].

[h]A few points[/h]

Hopefully the comments make it possible to follow what's going on there, but here's some points of particular note.

Firstly, I invoke $.when not directly but via the native apply(). This is because $.when() does not presently allow you to pass multiple objects as an array, which is necessary for my example. apply(), as you may know, allows you to stipulate arguments to a function as an array, so problem solved.

(If you're new to $.when(), I'll be covering that in a separate post, as it has a lot to offer your patterns.)

Secondly, in a production environment it would be prudent to expose not the deferreds themselves but their inherant promise objects (via the promise() method) instead. This allows environmental code to bind callbacks to them but not interfere with their state or progress. See the jQuery API page on promise objects for more detail.

[h]Summary[/h]

I reiterate that this is a slightly contrived example, to highlight the use of deferreds independently of AJAX, but I think it's quite a nice pattern.

Of course, the same effect could be achieved several other ways without deferreds; one could continually check, in the fadeout callback, whether there were any vowels still remaining at full opacity. If no, the user has clicked all the vowels. That would require a more complex fadeout callback, but it would of course work.</description>
			<pubDate>2012-04-09 19:41:00</pubDate>
		</item>
	
		<item>
			<title>JSON-P: what it is, what it's not and how it works</title>
			<link>http://www.mitya.co.uk/blog/2012/Mar/JSON-P-what-what-s-not-and-how-works-205</link>
			<description>I thought I'd take time out from discussing the brave new world of ECMA5 (to be continued) and do a post on JSON-P, since it's occured to me lately that it's often misunderstood by intermediate developers.

This post is aimed at developers who use JSON-P but have been been too sure about what it does under the bonnet. We'll pin down what it is, isn't, how it works, and some common misconceptions.

[h]JSON-P in two sentences[/h]

JSON-P is means of loading data from a remote server, provided the server in question is expecting the request. It is not AJAX, and does not necessarily involve JSON.

[h]How JSON-P works[/h]

JSON-P gets around the fact that JavaScript's Same Origin Policy prevents cross-domain AJAX by exploiting the fact that the src attribute of the script tag is not subject to this limitation, and can load in content (i.e. JavaScript) from remote servers.

Therefore, the steps of a JSON-P request are as follows:

a new script tag is DOM-scripted into the page (or an old one is re-used)the request URL is applied to the script tag's src attributethe requested server loads our request and outputs a responsethe response is evaluated as JS, since we requested via a script tag

[VISIT THE LINK FOR THE CODE].

If the server's response is...

[VISIT THE LINK FOR THE CODE].

...the alert will fire in our page once the request completes. Likewise, if the response is...

[VISIT THE LINK FOR THE CODE].

...a global variable, something, will be set in our page.

The key to understanding JSON-P is to remember that the server's response ultimately ends being evaluated as JavaScript, since it is called by a script tag.

These are simple examples. Usually, of course, you're going to want the server to give you some data.

[h]Accessing the server response: assignment and callback[/h]

Normally we want our JSON-P request to result in one of two things happening:

the data is passed to a globally-accessible callback function that we've preparedthe data is assigned to a global variable

It must do one or the other, otherwise the response will not be accessible to our page's JavaScript. So if the server simply returned:

[VISIT THE LINK FOR THE CODE].

...that data would be unreachable - even though it's valid JavaScript. This is not a trait of JSON-P but of JavaScript itself, but it is a common stumbling block for developers new to JSON-P. Think about it; if a linked script in your page contains the above, without assigning it to a variable or passing it to a function, it is inaccessible.

[h]Assignment[/h]

We saw variable assignment in the example further up. This is useful when, say, loading jQuery from CDN; we don't need the request to call a callback - we simply want jQuery to load. In other words, our JSON-P response should simply assign the variable jQuery (the jQuery namespace on which the library's API lives).

[h]Callback[/h]

More common is for the response to call a callback function that we have prepared. For this, the server will need to know the name of the callback function; large, public JSON-P web services allows you to specify this in your request structure.

For example, the following is a request to Twitter's JSON-P web service to retrieve five Tweets that mention Paddington Bear:

[VISIT THE LINK FOR THE CODE].

If you run that in your browser, you'll see the web service outputs JS that passes the returned data, as JSON, to the callback I requested, my_callback_func().

Imagining the Twitter web service in simple terms, if it was built in PHP, it would look something like this: (I include this only for context; if you're a front-end-only developer, don't worry too much about this).

[VISIT THE LINK FOR THE CODE].

The web service fetches and JSON-encodes the tweets, then builds an output string consisting of a call to our callback function, passing it the JSON as its only argument, i.e.

[VISIT THE LINK FOR THE CODE].

If we hadn't specified a callback, only the JSON would be output - useless for JSON-P requests but usable by server-side cross-domain requests (not relevant to this article).

As I touched on above, it is not always certain that you'll need to tell the web service the name of your callback function. If you control the web service, you may choose to hard-code the name of the callback on the server, so our PHP would look like:

[VISIT THE LINK FOR THE CODE].

There, the server assumes jsonp_callback - so your callback will have to be called that. This is a less common scenario, but illustrates the point that, whilst the ability to stipulate the name of your callback to the web service is a convenience, it is not a fundamental component of the JSON-P concept.

[h]Callbacks with jQuery[/h]

We've established that our callback needs to be globally accessible. Given that, you might wonder how this, a typical JSON-P request with jQuery, works:

[VISIT THE LINK FOR THE CODE].

There, our callback is an anonymous function, clearly not globally accessible. What we don't see, though, is that jQuery redefines it globally, assigning it a randomly generated function name (to minimise name clashes with other global entities).

This is why we stipulated the name of our callback function as ? in the request URL rather than choosing it ourselves (though we could have done). This permits jQuery to handle this whole issue; sure enough, Opera's Dragonfly tools shows the actual request URL that was sent, and the global function that was created:



[h]Misconceptions[/h]

Now we've taken a tour of what JSON-P is and how it works, some of the common misconceptions about should now seem obvious when you read them.

[h]Misconception 1: JSON-P is a form of AJAX request[/h]

[UPDATE: granted, this depends on your definition of AJAX. I would hold that it's not a form of AJAX, but see the comments below for a discussion on this...]

This misconception is understandable for two reasons. Firstly, JSON-P involves the silent loading of data, just like AJAX. Secondly, jQuery implements JSON-P through its AJAX module, something that is understandable (i.e. to have a single section of the API concerned with data retrieval/submission) but can and does lead to this misconception.

As we've seen, though, JSON-P works by exploiting the src attribute of script tags, whereas AJAX requests are done over XMLHTTPRequest.

[h]Misconception 2: JSON-P always involves JSON[/h]

The original proposal for JSON centred on the idea that servers would, on receipt of a JSON-P request, go off to the database (where applicable), get some rows of data, and serialise and output that data as JSON.

This is often the case - but it's not to say it has to be. The server response could equally be a string or a number, say.

[h]Misconception 3: JSON-P requests must involve a callback[/h]

Again, most JSON-P web services do involve callbacks, but it does not have to be the case. As we saw early on, there's no need for callbacks when, say, loading jQuery over JSON-P - we simply want jQuery's jQuery global variable to be set.

[h]Misconception 4: callbacks must be global functions[/h]

It's true that the callback function (or assigned variable) must be globally accessible, but this does not necessarily mean global in sense of being in the outermost scope.

[VISIT THE LINK FOR THE CODE].

If you're using a namespace pattern like above, i.e. where your entire code exists in a single namespace to avoid global pollution, there's no reason your callback function can't be a method of that namespace. So our Twitter request from above might become:

[VISIT THE LINK FOR THE CODE].

Likewise if the web service sets a variable rather than calling a callback. You could have the server do this:

[VISIT THE LINK FOR THE CODE].

[h]So there you have it[/h]

So there you have it. If JSON-P was hazy for you before this, I hope I've helped clear up the issue and shown you how it works under the scenes. It's certainly one of the lesser understood elements of every-day web development, but it pays to understand precisely what's going on.

For more on JSON-P, be sure to check out Kyle Simpson's JSON-P.org.</description>
			<pubDate>2012-03-23 23:24:00</pubDate>
		</item>
	
		<item>
			<title>JavaScript getters and setters: varying approaches</title>
			<link>http://www.mitya.co.uk/blog/2012/Mar/JavaScript-getters-and-setters-varying-approaches-204</link>
			<description>Last week I posted an introductory article on ECMAScript 5 object properties, and the mini-revolution that I think they constitute. (The post made the coveted JavaScript Weekly - thanks, guys.)

One of the key features of them is the ability to define getter/setter callbacks on them.

Getters and setters are a means of providing an arm's-length way of getting or setting certain data, whilst keeping private other data, and are common of most languages. In JavasScript, setters are also a good way of ensuring your UI stays up to date as your data changes, which I'll show you an example implementation further down.

[h]A new approach to getters and setters[/h]

The new approach looks like this, and can be used only on properties created via the new Object.create() and Object.definePropert[y/ies]() methods.

[VISIT THE LINK FOR THE CODE].

You'll note that this approach requires the help of a 'tracker variable' (in our case name) via which the getter/setter reference the property's value. This is to avoid maximum recursion errors that the following would cause:

[VISIT THE LINK FOR THE CODE].

That happens because we set a getter, via which any attempt to read the property is routed. Therefore, having the getter reference this.name is effectively asking the getter to call itself - endlessly. Likewise for a setter, if it tried to assign to this.name.

Since each property needs its own tracker, and you don't want lots of variables flying around, it's a good idea to use a closure when declaring several properties.

[VISIT THE LINK FOR THE CODE].

There, we declare what properties we want on our object, and some start values. The loop sets each property, and tracks its value via a private propVal variable in its closure.

One of the things I like about this new approach is you no longer have to call the getters/setters explicitly (as you did with previous implementations - see below) - they fire simply by talking to the property.

Admittedly this has its proponents and its opponents; those in favour say getters/setters should fire simply by calling/assigning to the property - not calling some special methods to do that. Those against normally point out that someone new to the code might be surprised to find that talking to a property in fact fires a function.

My take is that, as long as this is part of the spec, and your code is well documented, there can be few complaints with using the new implementation.

[h]Other ways of doing getters/setters[/h]

In any case, I much prefer them to the implementation we got in JavaScript 1.5.

[VISIT THE LINK FOR THE CODE].

I've never been in love with this approach, chiefly because you don't deal directly with the property but with a proxy that represents its getter/setter callbacks - in the above example foo. The new approach does away with this; you call/assign to the property just as you would if there were no getters/setters in play, and the getter/setter callbacks kick in automatically - they are not referenced explicitly.

That said, one good point about this separation of property value from getter/setter is that the getter/setter can safely reference the property via this without the risk of recursion error, as befalls the new approach.

[h]The older way[/h]

There's also the depracated __defineGetter__() and __defineSetter__() technique.

[VISIT THE LINK FOR THE CODE].

Once again you have to name your setters/getters. By far the most notable point about this approach, though, is you can assign getters/setters after assigning the property - not a super common desire, but useful any time you don't want to or can't alter the prototype. The other two implementations don't allow you to do this, at least without a lot of reworking.

A final point about these latter implementations is that they don't hijack control of your property like the new implementation does. That is, if a developer ignores them and manipulates the property directly, they can. This is not good news; if you defined getters/setters, you probably want them to run, not be bypassed.

[VISIT THE LINK FOR THE CODE].

[h]Setters and a responsive UI[/h]

As I mentioned in the intro, another role of getters in JavaScript can be to keep your UI up to date as your data changes. Frameworks like Backbone JS sell themselves heavily on this concept.

As the intro to the Backbone documentation points out, medium-large JavaScript applications can easily get bogged down with jQuery selectors and other means trying to keep your views in-sync with your data.

A getter can help here. Here's something I cooked up:

[VISIT THE LINK FOR THE CODE].

And here's some example HTML:

Elt;p id='dog'>Hi - my name's Elt;span id='name'>Elt;/span> and I'm a Elt;span id='type'>Elt;/span>!Elt;/p>

I'll go into the details of what my method does in a further post. Essentially, though, what's happening is we pass an object to the UIify() method where each property is a sub-object containing its starting value (val) and a CSS/jQuery selector pointing to to the UI element that should be updated as and when the value changes (target.)

UIify() then returns an object using the new ECMA5 getters/setters. Whenever a property of the object is overwritten, the corresponding UI element denoted by the target we specified is updated. In my case, the targets were simply elements with IDs, but it could of course be more complex targets - it's just CSS/jQuery selector syntax.

---------

So there you have it, three approaches through the ages. Next time up I'll be looking more at the new Object funcionality in ECMA5.

(p.s. for further reading, be sure to check out the extensive MDN article on working with objects, which talks a lot about getter/setter techniques.)</description>
			<pubDate>2012-03-13 17:50:00</pubDate>
		</item>
	
		<item>
			<title>ECMAScript 5: a revolution in object properties</title>
			<link>http://www.mitya.co.uk/blog/2012/Feb/ECMAScript-revolution-object-properties-201</link>
			<description>Over the coming weeks I'm going to focus on discussing the mini revolution that ECMAScript 5 brought, and the implications in particular for objects and their properties.

ECMA5's final draft was published at the end of 2009, but it was only really when IE9 launched in early 2011 - and, with it, impressive compatibility for ECMA5 - that it became a genuinely usable prospect. Now in 2012, it is being used more and more as browser vendors support it and its power becomes apparent. (Full ECMA5 compatibility table).

JavaScript has always been a bit of an untyped, unruly free-for-all. ECMAScript 5 remedies that somewhat by giving you much greater control over what, if anything, can happen to object properties once changed - and it's this I'll be looking at in this first post.

[h]A new approach to object properties[/h]

In fact the whole idea of an object property has changed; it's no longer a case of it simply being a name-value pairing - you can now dictate all sorts of configuration and behaviour for the property. The new configurations available to each property are:

value - the property's value (obviously)writable - whether the property can be overwrittenconfigurable - whether the property can be deleted or have its configuration properties changedenumerable - whether it will show up in a for-in loopget - a function to fire when the property's value is readset - a function to fire when the property's value is set

Collectively, these new configuration properties are called a property's descriptor. What's vital to understand, though, is that some are incompatible with others.

[h]Two flavours of objects[/h]

The extensive MDN article on ECMAScript 5 properties suggests thinking of object properties in two flavours:

data descriptors - a property that has a value. In its descriptor you can set value and writable but NOT get or setaccessor descriptors - a property described not by a value but by a pair of getter-setter functions. In its descriptor you can set get and set but NOT value or writable. Note that both a getter and setter must be set, not just one or the other.

Note that enumerable and configurable are usable on both types of property. I'm struggling to understand why someone thought the ability to set a value and a setter function, for example, were incompatible desires. If I find out, I'll let you know.

[h]New methods[/h]

To harness this new power, you need to define properties in one of three ways - all stored as new static methods of the base Object object:

defineProperty()defineProperties()create()

The first two work identically except the latter allows you to set multiple properties in one go. As for Object.create(), I'll be covering that separately in a forthcoming post.

Object.defineProperty() is arguably the most important part of this new ECMAScript spec; as John Resig points out in his post on the new features, practically every other new feature relies on this methd.

Object.defineProperty() accepts three arguments:

the object you wish to add a property tothe name of the property you wish to adda descriptor object to give it a value and configure it (writable, deletable etc)

Let's see it in action.

[VISIT THE LINK FOR THE CODE].

See how the overwrite failed? No error or warning is thrown - it simply fails silently. In ECMA5's new 'strict mode', though, it does throw an exception. (Thanks to Michiel van Eerd for pointing this out.)

There we set a data descriptor. Let's set an accessor descriptor instead.

[VISIT THE LINK FOR THE CODE].

You might be wondering what on earth is going on with that newPropVal variable. I'll come to that in my next post which will look at getters and setters in detail. Note also how, with our setter, the new value is forwarded to it as its only argument, as you'd expect.

The fact that these properties can be set only via these methods means you cannot create them by hand or in JSON files. So you can't do:

[VISIT THE LINK FOR THE CODE].

[h]ECMA 5 properties don't replace old-style ones[/h]

An important thing to understand early on is that this new form of 'uber' property is not the default. If you define properties in the old way, they will behave like before.

[VISIT THE LINK FOR THE CODE].

[h]Reporting back[/h]

Note that these new configuration properties are, once set, not available via the API; rather, they are remembered in the ECMAScript engine itself. So you can't do this (using the example above):

[VISIT THE LINK FOR THE CODE].

Instead, you'll be needing Object.getOwnPropertyDescriptor. This takes two arguments - the object in question and the property you want to know about. It returns the same descriptor object you set above, so something like:

[VISIT THE LINK FOR THE CODE].

[h]More to come..[/h]

So there you go - a very exciting mini revolution, as I said. This new breed of intelligent object property really is at the heart of arguably the most major shake-up to the language for a long time. Next week I'll continue this theme - stay posted!</description>
			<pubDate>2012-02-29 20:03:00</pubDate>
		</item>
	
		<item>
			<title>A friendly alternative to currying</title>
			<link>http://www.mitya.co.uk/blog/2012/Feb/A-friendly-alternative-to-currying-200</link>
			<description>I recently did a small talk and demonstration on currying in JavaScript. My personal take is that, while occasionally useful, it's a bit of a nuclear option, for limited reward.

[h]Er, what's currying?[/h]

If you don't know, currying involves what's called partial application: invoking functions or methods whilst omitting some of the arguments, for which default values are assumed instead.

In other languages this is simpler. In PHP, for example, you can specify default values at the point of declaring your function:

[VISIT THE LINK FOR THE CODE].

Since that's not possible in JavaScript, the typical workaround is to feed your function to a curry-fier function, along with some default values, and get back a new version of your function that will assume default values for any omitted arguments. It might look something like this:

[VISIT THE LINK FOR THE CODE].

It's a little beyond the scope of this article to explain line-by-line what's going on there, but needless to say I can now call my add function with only some, or even no arguments.

[VISIT THE LINK FOR THE CODE].

[h]Drawbacks[/h]

That's all very nice. BUT, there are drawbacks and pitfalls to curry-fying. For one thing, a curryfied function no longer behaves as its originally-declared former self suggests. This might well throw a developer that comes to your code anew - particularly since JavaScript, as I say, does not support natively any notion of default function arguments.

Another problem concerns hoisting. If your function is a traditional one, i.e. as opposed to an anonymous function, the function itself will be hoisted, but its curryfied redefinition will not be (since curryfying a function always means declaring it as an anonymous function. For example:

[VISIT THE LINK FOR THE CODE].

Our function is hoisted, since it's a traditional function not an anonymous one. That's the reason we can call it before the line where it's declared. However its curryfied redefinition will not be hoisted - so we would need to either curryfy it higher in the page or move our call to the function down.

[h]A friendly alternative[/h]

My approach is rather different. Instead of redefining the function, let's ensure that it - and, indeed, every function - automatically inherits an extension to itself that allows us to omit variables. In addition, we'll set up another extension, called after the function is declared, that lets us set the default values. So the end result would be:

[VISIT THE LINK FOR THE CODE].

Hopefully it's clear what's happening there. I declare my function, then immediately stipulate what the default values are. Then, to invoke my function in such a way that I can have those default values substitute any omitted arguments, I call an extension of my function, called withDefaults(). To this I pass partial or even no arguments at all.

An advantage of this is that it doesn't destroy our original function, so anyone coming to our code anew and expecting traditional, not curryfied behaviour from our function, won't be surprised or confused.

Here's the code behind this approach:

[VISIT THE LINK FOR THE CODE].

As you can see, I'm declaring these two extensions on the Function object's prototype, so I can be sure they are both inherited by any and all functions I create.

I'll talk through the code in a separate blog post, but here's some usage demos for it, showing you different ways it can be used.

[VISIT THE LINK FOR THE CODE].

The output from that will be:

Example 1
[VISIT THE LINK FOR THE CODE].

Example 2
[VISIT THE LINK FOR THE CODE].

Example 3
[VISIT THE LINK FOR THE CODE].



There's several interesting points of note there:

- When setting defaults for a function, you can specify values for as few or as many arguments as you like - it doesn't have to be all of them.

- When dealing with anonymous functions (example 2), you can call setDefaults() by chaining it to the end of your function literal.

- The approach even works with OO / instantiation, as shown in example 3. A lot of curryfyer scripts overlook this use case.

[h]Phew. So, in summary?[/h]

You have a function. It accepts a lot of arguments. You find yourself passing many of the same arguments to it each time. Using the above script you can set some default values and then not have to worry about passing them as arguments when you call the function in future.</description>
			<pubDate>2012-02-22 20:19:00</pubDate>
		</item>
	
		<item>
			<title>Presenting XMLTree v.2.0</title>
			<link>http://www.mitya.co.uk/blog/2012/Feb/Presenting-XMLTree-v-199</link>
			<description>You may remember XMLTree, which I launched several months ago. In short, it's a plugin that generates a tree from XML data, allowing you to traverse and interrogate the data but also bind events to the various branches of the tree.

Version 2.0 is now here, and comes with a host of powerful new features, including:

[h]Sub-trees: loading data from a web service[/h]

Sub-trees allow you to load data branch-by-branch rather than all at once. This means you can use XMLTree with a web service, which serves up the root-level data on load, and then branch-specific data as and when branches are expanded.

Imagine you have a tree showing the boroughs of London. When a branch is expanded, it should show all the bus numbers that serve that borough.

Let's assume the web service returns the following XML format for the root data:

[VISIT THE LINK FOR THE CODE].

Knowing that, here's our tree instantiation:

[VISIT THE LINK FOR THE CODE].

By using the attrsAsData param (see below), we ensure that any borough_id attributes from the XML are transfered over as element data onto the tree LIs.

That's critical, because it means that, when a branch is expanded, we can look up that piece of data to determine URL of the web service for loading the next set of data.

The URL is determined and returned by the subTreeRequest param, a callback function that fires when a sub-tree-able branch is expanded and to which the expanded branch's LI is automatically passed. So the URL returned will be something like my_web_service.php?borough_id=13

In summary: to start with, only the root-level data is loaded. The data that goes within branches is determined only when a branch is expanded, by making a separate call to the web service. Crucial information is passed to the web service so it knows what data is returned - in this case, the ID of the clicked branch.

[h]Transfer XML attributes to classes/element data[/h]

Attributes in your XML can now be transfered over to the resultant mark-up - in the form of either classes or element data attributes on the branch LIs.

In either case, you can either specify that all attributes should be transferred over, or just some.

[h]Other features[/h]

Other, more minor features in this release include:

- support for loading XML over JSONP internet requests
- ability to auto-open the tree at a specific point once it's loaded
- ability to output, ignore or output but hide attributes as branches

</description>
			<pubDate>2012-02-09 18:51:00</pubDate>
		</item>
	
		<item>
			<title>Numberfy: add line numbers to your textareas</title>
			<link>http://www.mitya.co.uk/blog/2012/Jan/Numberfy-add-line-numbers-to-your-textareas-198</link>
			<description>Ever wished textareas had native support for line numbers?

I, and doubtless the developers behind the many JSFiddle-esq sites out there these days, have.

So I've built a jQuery plugin that does precisely that. Just target the textarea(s) you want to add line number support to via a jQuery selector, call the numberfy method, and that's it.



[VISIT THE LINK FOR THE CODE].

This tuned out to be an interesting little thing to build. The most challenging part, obviously, was getting the numbers to appear at the right positions vertically, to take into account line wrapping.

The solution here is simple but effective; on every keypress in the textarea, the textarea's current value is split into lines, then one by one each line is added to the clone and its offset height measured.

That tells us how tall the line is, including wrapping, and tells us therefore where to position the line number.

It's worth pointing out that the clone is not actually a clone of the textarea - it's aElt;p> tag; the reason is the clone needs to have fluid height, so we can read its offset height. A textarea's dimensions are never fluid.

[h]IE, sod off[/h]

It doesn't currently work correctly in IE. This is because I discovered a little-known 'bug' in IE whereby text within textareas wraps differently from text in other areas - even where they have the same word-wrap / white-space CSS properties.

I moaned about it on Stack Overflow, and the consensus so far seems to be there's nothing that can be done about it. I'll keep looking at this.



Enjoy.</description>
			<pubDate>2012-01-23 18:31:00</pubDate>
		</item>
	
		<item>
			<title>JSON and PHP: formatting and validating</title>
			<link>http://www.mitya.co.uk/blog/2012/Jan/JSON-and-PHP-formatting-and-validating-196</link>
			<description>[h]Formatting JSON to look all lovely[/h]

It's always a happy day when I manage to use JSON in PHP. As a JS developer, it sort of feels like I'm marrying the two technologies. Take that, serialised arrays - I'm using JSON.

PHP, of course, has support for encoding and decoding JSON via json_encode() and json_decode() respectively. What it can't do natively, though, is format JSON.

Why would you want to format JSON in PHP to make it look all nice and indented? Well, if the system you're building uses JSON for a config file, and you want users to be able to edit that config file within the system, in a textarea, say.

I then found this function, which largely does the job.

It can, however, get the indentation wrong sometimes. Also, it can leave whitespace at the end of lines. So I extended it slightly. The following three snippets should be inserted just before the final return statement.

Firstly, let's clear any whitespace left at the end of lines.
[VISIT THE LINK FOR THE CODE].

Next, let's fix the indentation. What I noticed was that the script was indenting lines containing closing brackets/braces precisely double what it should be - so four tabs instead of two, for example. So, the following halves each case.

[VISIT THE LINK FOR THE CODE].

Note I'm using a callback on preg_replace() - this gives me greater control over the nature of my replacements. preg_replace() automatically forwards to my callback one argument - an array of the match. As ever, key 0 in the array contains the whole match and any subsequent keys contain any sub-matches my pattern looked for.

Lastly, either the script or (more probably) my hacks above end up killing some of the line breaks, so let's restore them.

[VISIT THE LINK FOR THE CODE].

Et voila - nicely formatted JSON.

[h]Make sure your JSON's valid[/h]

JSON and JavaScript Object Notation are not always the same thing. How so? Well, this is valid JS but INvalid JSON:

[VISIT THE LINK FOR THE CODE].

...because the JSON spec demands that a) property names are quoted; b) property names and strings must be encased in double, not single quotes.

So if you end up with invalid JSON, how will you know? PHP >= 5.3 defines json_last_error(), which returns a flag saying what went wrong.

Confusingly, it returns something even if nothing went wrong - JSON_ERROR_NONE. It does not return false, so it is insufficient to check the validity of JSON with:

[VISIT THE LINK FOR THE CODE].

Instead, the last line should be:

[VISIT THE LINK FOR THE CODE].

[h]PHP versions prior to 5.3[/h]

If you're running PHP prior to v.5.3, you won't have json_last_error(). Instead, you can simply check the truthy/falsy value of json_decode(), so:

[VISIT THE LINK FOR THE CODE].

Obviously this approach is more crude and won't tell you what went wrong - just that something did.

If you're looking for somewhere to host your PHP, whether Linux or Windows hosting, it always pays to make use of a good web hosting review site to find the right web hosting provider. This is a particularly good one, especially their WordPress hosting search page if you’re still on your way finding a suitable home for your WordPress blog.</description>
			<pubDate>2012-01-04 21:05:00</pubDate>
		</item>
	
		<item>
			<title>Being Firebug, pt2: which rules, which elements?</title>
			<link>http://www.mitya.co.uk/blog/2011/Dec/Being-Firebug-pt-which-rules-which-elements-195</link>
			<description>Ever wondered how Firebug, Dragonfly and other debug tools manage to detect which styles apply to an element, whether they're currently active, what stylesheet (if any) they're coming from, and other such info?

In this second part of a two-part blog post, I'll be showing you how to do just that.

[h]You read part 1, right?[/h]

Before we begin, make sure you read part one, which I posted last week, as this post continues from there and assumes you understood what I was waffling on about there.

[h]I read it - so now what?[/h]

So you read part one - therefore you understand how Javascript can read the CSS rules and styles coming into a page from stylesheets, and how it can also read 'computed styles' on a given element.

Now we're going to look at how to see which CSS rules apply to a given element - and which of its styles are active or have been overridden.

[h]Detecting if a rule applies to an element[/h]

This would be horrible to do in native Javascript. Possible, but horrible. Thankfully, an unsuspecting jQuery method, .is(), is going to save us a hell of lot of code writing.

If you're not familiar with .is(), it returns true or false based on whether the element(s) on the jQuery stack matches the selector you pass to it. So for example:

[VISIT THE LINK FOR THE CODE].

Pretty simple. So how does that help with what we're doing? Well, as we saw in part one, Javascript's DOM CSS Rule object allows us to access not only the styles of a particular rule but also the selector text, i.e. the part before the {.

If we pass that to .is() on the element we're interested in, we find out if the rule applies to that element. Pretty neat, eh? Observe.

[VISIT THE LINK FOR THE CODE].

Note I'm skipping the validation - i.e. checking that el actually finds an element with ID 'myElement', and that there really is a stylesheet[0] - just to keep the code succinct, but you'd obviously want to check for these things in a real-world environment.

If you console.log our rulesThatApply array, you'll see that it contains the selector text of the rules that apply to our element, just as we'd hoped. So far, so good.

[h]In case you missed it...[/h]

See what we did there? See how the .is() method is they key? The method, as I mentioned above, returns true or false depending on whether the element(s) in the jQuery stack matches - in other words, is targetable by - the selector you pass to the method.

That is NOT to say that the CSS rule's selector text must match exactly the jQuery selector we use to target the element (if we use jQuery at all; in the above code, I target an element natively) - rather, that it must ultimately select the same element. So for example:

[VISIT THE LINK FOR THE CODE].

[VISIT THE LINK FOR THE CODE].

When our code runs, and the loop gets to that rule, we are effectively asking:

[VISIT THE LINK FOR THE CODE].

[h]Detecting if a style is active or overridden[/h]

Detecting what rules are talking to an element is one thing. But that does not mean, of course, that all the styles of a particular rule are active on the element - they may have been overridden by other rules or by inline styles.

The key here is to test the implicitly-set CSS value of the style against the computed - i.e. current - value of the style. If they match, it means the CSS style is still in effect. It they don't, it has been overridden.

Simple, right? Well, pretty much, but there are a few pitfalls.

First, colours. You probably set colours in your CSS via HEX syntax - however most browsers return computed colours in RGB format. So if you set #f90 in your CSS, when you read it back from the computed styles you'll be told rgb(255, 153, 0).

Secondly, you'll want to harmonise string format before attempting comparison. The most obvious example here is the dashes-vs-camel-case thing going on between CSS and JS - i.e. text-decoration, but textDecoration in JS.

So, let's get to work. For demo purposes, let's work with just one CSS rule and its styles.

[VISIT THE LINK FOR THE CODE].

The first two parts of that are exactly the same as we did in the code earlier in this post. The last line simple grabs the first rule of the stylesheet. This returns to us a DOM CSS Rule object. This is an object of the various styles that the rule sets, e.g. color.

Let's iterate over these styles and, for each, compare it to the current, computed style. As I mentioned above, we'll need to harmonise the values so they are comparable. The most complex part of this is colours - we'll convert them all to HEX format.

[VISIT THE LINK FOR THE CODE].

You might be wondering where that RGBToHex function comes from. Well, I wrote it - and here it is, so you'll need this, too.

[VISIT THE LINK FOR THE CODE].

That function is beyond the scope of this article, but hopefully it's fairly simple in what it does. Basically, you feed it an RGB colour (e.g. rgb(255, 0, 0) or even just 255,0,0) and it returns the colour in HEX format. If the colour is already in HEX format it merely returns what you give it, unchanged.

[h]So, what did we just do?[/h]

Let's look at a few things in that code. As I said, in order to see if a style is active, we need to compare it to the current, computed equivalent. This means harmonising two values:

- Line 7: the name of style, from dashes to camel case, e.g. text-align to textAlign
- Lines 15/16: colours into HEX format, because most browsers return computed colours in RGB format (even if you set them in HEX!)

[h]So there you have it[/h]

A lot to take in, but hopefully you've got an idea of how the likes of Firebug and Dragonfly do their thing.

Oh and do remember that, like all code that deals with the DOM, you'll want to use the code from this post inside a window.onload callback or, if using jQuery, inside a document ready handler.</description>
			<pubDate>2011-12-12 18:27:00</pubDate>
		</item>
	
	</channel>
</rss>

