One of the first things that a YUI developer learns about are the attribute change events that are fired any time an attribute value is successfully changed. But one often overlooked feature of Y.Attribute is the validator.

The validator allows you to test that a value is valid for the attribute prior to it being sent to the setter. A common use is validating that the value trying to be set is in an accepted format - such as only allowing integers in a quantity attribute. Returning true from the validator sends the value to the setter, returning false causes the value to not be set. But unlike a successful change event no event is fired to notify you that the value failed validation and was not set. So lets augment our modules to fire a validation failed event.

Unfortunately to monkey patch this feature into Y.Attribute properly would require a large amount of code duplication so we’ll leave that to the coming pull request. Instead we are going to pick a small simple method which will allow us to inject our enhancement but not force us to duplicate a bunch of the library code. This is only intended to be a short term solution until the patch makes its way into the library as monkey patching introduces a number of potential negative side effects.

Because we may not want to apply this patch to all of the modules which extend Y.Attribute we will only modify this method in the objects that we need it for. To make this really easy we will create a small object and mix it into the instances.

Y.attrValidatePatch = function() {};

Y.attrValidatePatch.prototype = {
    _defAttrChangeFn: function(e) {
        if (!this._setAttrVal(e.attrName, e.subAttrName, e.prevVal, e.newVal)) {
            e.stopImmediatePropagation();
            this.fire(e.attrName+'ValidationFail', e); // The only new line
        } else {
            e.newVal = this.get(e.attrName);
        }
    }
};

We then mix that patch into our new module

var CustomModule = Y.Base.create('custom-module', Y.Base, [Y.attrValidatePatch], {

    //Custom  module code here

}, {
    ATTRS: {
        "number": {
            validator: function(val) {
                return Y.Lang.isNumber(val);
            }
        }
    }
});

And now we are able to listen for that attributes validation fail event just like we would for the change event

var MyModule = new CustomModule();

MyModule.on('numberValidationFail', function(e) {
    Y.log('Validation failed setting ' + e.attrName + ' to ' + e.newVal, 'error', MyModule.name);
});

// As usual you need to listen using 'after' to be sure attributes were set
MyModule.after('numberChange', function(e) { Y.log('New value is: ' + e.newVal); });

MyModule.set('number', 100); // Valid value
MyModule.set('number', 'to string'); //Invalid value

Wrap all of the above code up in a use() and watch your console to see it in action. As usual If you are having any issues implementing this patch feel free to comment below, mention me @fromanegg or pop into #yui on irc.freenode.net

I have been trying to take some time away from the warm glow of the LCD screen after hours so I haven’t had much time to write up new code related posts. Instead, I have been spending some of this time away reading books, blog posts, and articles on business and web development. So in an effort to keep my blog from going stale here is my very first book review outside of high school English class.

It has been some time since I have been on the receiving end of a traditional interview and have never had the anxiety experienced by some of my fellow developers applying at large tech companies. Being self employed for many years giving those traditional interviews which are widely regarded as useless, then working for a great web development company whose interview was friendly and informative. So when I was walking through the local Indigo book store and saw the book titled Are You Smart Enough to Work at Google? I had to pick it up.

When starting this book I set a rule that I would do my best to answer all of the questions before reading the summaries to follow. Most went well, others not so much, which I suppose is to be expected. Although I’m sure it would be entertaining for me to include my responses in this post I didn’t want to spoil this excellent book.

Picking it up off the shelf you would be forgiven to think that it was simply a list of whimsical interview questions and their answers but it is much more. The book is broken into two distinct sections that almost split the book right down the middle with the first set of chapters covering various topics from the history of interviews, the relationship between creativity and intelligence, business history, hiring practices, and of course, employment in general. Spread throughout this first section, and what most will probably find the most interesting, are the reports of Google’s hiring practices as explained by past and present employees from both sides of the HR table.

So where are the questions I mentions earlier? Each chapter in the first section ends with a list of popular creative interview questions with the page number the answers start on in the second section.

Also found in the first section, and most interesting to me, are the final sections giving you the tools you will need in order to be successful if you happen to end up on the other side of an interview at Google or many other companies who are moving towards this new method of interviewing potential candidates. It covers techniques such as whiteboarding, estimation tricks, spotting various types of questions, and much more.

The second section contains very detailed answer summaries to all of these questions as most don’t have a right or wrong component these summaries do a great job to illustrate the types of answers will be successful and which will fall flat.

For those not in the industry it’s hard to believe that with today’s unemployment rates that there is a shortage of qualified developers available for company’s to hire from, but ask any manager tasked with growing their team and they will happily discuss with you the challenges of finding a qualified work force. Even when most companies are struggling to find qualified employees Google still maintains it’s stringent hiring practices to ensure they they only hire the most qualified people for their teams.

If you are looking to learn about the new hiring practices employed by many companies looking to find just the right candidate to help their company grow and enjoy a bunch of brain teasers on the way I highly recommend picking this book up.

Are you smart enough to work at Google - Indigo.ca

A commonly requested feature for the popup calendar is to be able to pop it open via a button. Unfortunately I haven’t had time to add this feature directly into the module but today @gdanko popped into #yui on irc.freenode.net and was willing to help test the small code changes required to make sure that this would work.

Until I am able to add support into the module, simply copy and paste the following code before the first instance of Y.PopupCalendar or Y.PopupCalendarGroup.

Y.PopupCalendar.prototype._bindEvents = function() {
  Y.log('_bindEvents', 'info', this.name);

  var input = this.get('input');

  if (input.get('type') === 'text') {
      input.on('focus', this.showCalendar, this);
  } else {
      input.on('click', this.showCalendar, this);
  }

  input.on('keydown', this.testKey, this);
  this.on('selectionChange', this._emitDate, this);
  this.after('autoFocusOnFieldFocusChange', this.setHideOn, this);
},

And that’s it. You can now supply most elements to show the calendar. If you are having any issues implementing this patch feel free to comment below, mention me @fromanegg or pop into #yui on irc.freenode.net

Loading YUI from Yahoo!’s CDN was one of the most requested features after the previous post Guide to using YUI with PhoneGap (Cordova). The good news is that it’s very easy to setup but does come with a few drawbacks.

Using the code from the previous post we only need to make minor changes to load from the CDN.

<!DOCTYPE HTML>
<html>
<head>
<title>My First Cordova YUI App</title>
<script type="text/javascript" src="cordova-1.8.0.js"></script>
<!-- Add in the YUI seed file -->
<script src="http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js"></script>
<!-- Remove the included local scripts and YUI_CONFIG object
<script type="text/javascript" src="yui-file-1.js"></script>
<script type="text/javascript" src="yui-file-2.js"></script>
<script type="text/javascript">YUI_CONFIG = { bootstrap: false };</script>-->
</head>
<body>

<h1>YUI PhoneGap (Cordova) Example</h1>
<p>Click this button for a surprise</p>
<button>Click Me</button>

<script type="text/javascript">
// Remove the 'load all' flag from the use statement
// YUI().use('*', function(Y) {
// Request the Node and Event modules
YUI().use('node', 'event', function(Y) {

	var button = Y.one('button'),
		header = Y.one('h1');

	button.on('touchstart', function(e) {
		header.setStyle('color', '#00B2EE');
	});

});
</script>
</body>
</html>

And that’s it! That will load the YUI seed and loader from Yahoo!’s CDN then load in the Node, Event, and all dependent modules automatically for you. Isn’t loader great?

But all isn’t perfect, at the beginning I mentioned some drawbacks. In the previous version we were packaging up all of the required assets into the package which will be stored on the device. This will guarantee that those files are always available regardless of the users network connection. Using the remote loading method, once the application loads up it needs to make the request of the remote files before it will become functional. This can cause unnecessary delays in the bootup of the application or cause the application to be entirely useless if there is no network connection. Because of that I don’t recommend using remote loading for core application components. This technique can be very useful during development where your required modules may be changing frequently.

I’m going to try to keep making these tutorials so if you have anything specific you would find helpful for yourself or others please comment below, mention me on twitter or join #yui on irc.freenode.net

If you have ever wanted to use YUI in your next PhoneGap (Cordova) application you are in luck, it is so easy, it’s almost trivial. This will be the first in what will probably be a series of posts about using YUI with PhoneGap (Cordova).

This tutorial assumes that you already know the basics of YUI but, at least for this first instalment, you shouldn’t have any problem following along if you don’t. I am also not going to cover the installation and setup as it is covered in detail in the Getting Started Guide. If you have never built a PhoneGap app I highly recommend completing their Hello World application first. I will be progressing through using an HTC Incredible S with Android 2.3.3 but I will be sure to point out what is device or OS specific. The application that we are going to make is going to build upon the aforementioned Hello World application adding in a button to change the text color.

Most of the confusion with using YUI and PhoneGap (Cordova) is the combo loading - How do you use the Loader in a mobile app? The simple answer is that to get started we aren’t going to be. To accomplish our task we require a certain set of YUI modules. To simplify this tutorial we are going to use the YUI Configurator. In the All Module list, click on the Node and Event Rollups. These rollups include more code than necessary but it makes the setup easier.

The configurator will generate two script tags, be sure to select both urls individually Then copy the URL portions of the link generated by the configurator and paste it into the address bar of your browser. If you are having trouble with the configurator I have included the link to the two required files: File 1 and File 2

Copy the code which is in your browser window and save the code into your assets/www directory in yui-file-1.js and yui-file-2.js respectively, the order these files are loaded is important

Now we are going to get YUI loaded and set up in our index.html file with three additional script tags.

<script type="text/javascript" src="cordova-1.8.0.js"></script>
<script type="text/javascript" src="yui-file-1.js"></script>
<script type="text/javascript" src="yui-file-2.js"></script>
<script type="text/javascript">YUI_CONFIG = { bootstrap: false };</script>

First we load in the Cordova script followed by the two files generated by the YUI configurator plus one more to configure the YUI instance to follow. By setting bootstrap to false we are preventing YUI from trying to load the Loader. Additional details can be found in the bootstrap api documentation.

We are ready for our typical YUI().use statement. Add another script tag just above the closing body tag and instead of loading in specific modules like you normally would, we are going to load in all modules that have been loaded into the page using the * symbol.

<script type="text/javascript">
YUI().use('*', function(Y) {

	var button = Y.one('button'),
		header = Y.one('h1');

	button.on('touchstart', function(e) {
		header.setStyle('color', '#00B2EE');
	});

});
</script>

We use the Y.one() method to select our dom elements as usual and then attach an event listener to the button using the Node.on() method. But instead of using the typical click event, we substitute it for the touchstart event. Just for fun you can change the touchstart back to click and you will see that it works but there is a noticeable delay in the action - this will happen with any click event handler with PhoneGap (Cordova). we then take the element we assigned to the header property and set it’s color with the Node.setStyle() method.

And that’s it! You can now load this onto your device using the same method described in the PhoneGap (Cordova) example and you have made your very first YUI PhoneGap (Cordova) application. I hope you enjoyed this brief tutorial and if you have any questions feel free to comment below, mention me on twitter or join #yui on irc.freenode.net

<!DOCTYPE HTML>
<html>
<head>
<title>My First Cordova YUI App</title>
<script type="text/javascript" src="cordova-1.8.0.js"></script>
<script type="text/javascript" src="yui-file-1.js"></script>
<script type="text/javascript" src="yui-file-2.js"></script>
<script type="text/javascript">YUI_CONFIG = { bootstrap: false };</script>
</head>
<body>

<h1>YUI PhoneGap (Cordova) Example</h1>
<p>Click this button for a surprise</p>
<button>Click Me</button>

<script type="text/javascript">
YUI().use('*', function(Y) {

	var button = Y.one('button'),
		header = Y.one('h1');

	button.on('touchstart', function(e) {
		header.setStyle('color', '#00B2EE');
	});

});
</script>
</body>
</html>