Introduction to Ext JS 4

At the end of last 2010 we capped off an incredible year with SenchaCon – by far the biggest gathering of Sencha developers ever assembled. We descended on San Francisco, 500 strong, and spent an amazing few days sharing the awesome new stuff we’re working on, learning from each other, and addressing the web’s most pressing problems.

Now, we’re proud to release all of the videos from the conference completely free for everyone. You can see a full list on our conference site, where you’ll find days worth of material all about Ext JS 4, Sencha Touch and all of the other treats we’re working on at the moment.

Some of the videos in particular stand out for me – Jamie’s Charting and Layouts talks were spectacular, as was Rob’s Theming Ext JS 4 talk. On the Touch side, Tommy’s talks on Performance and Debugging are required viewing, as is Dave Kaneda’s characteristically off the cuff Theming talk.

My personal high point was standing in front of all of you and introducing Ext JS 4 and its three core goals – speed, stability and ease of use. I think you’re going to love what we’ve done with the framework in version 4, but for now I’ll let the video do the talking:

If you’re so inclined, you can find the slides for this talk on slideshare, and if you can still stand the sound of my voice check out my other presentation on Ext JS 4 Architecture, focusing chiefly on the new data package (slides).

Ext JS 4: The Class Definition Pipeline

Last time, we looked at some of the features of the new class system in Ext JS 4, and explored some of the code that makes it work. Today we’re going to dig a little deeper and look at the class definition pipeline – the framework responsible for creating every class in Ext JS 4.

As I mentioned last time, every class in Ext JS 4 is an instance of Ext.Class. When an Ext.Class is constructed, it hands itself off to a pipeline populated by small, focused processors, each of which handles one part of the class definition process. We ship a number of these processors out of the box – there are processors for handling mixins, setting up configuration functions and handling class extension.

The pipeline is probably best explained with a picture. Think of your class starting its definition journey at the bottom left, working its way up the preprocessors on the left hand side and then down the postprocessors on the right, until finally it reaches the end, where it signals its readiness to a callback function:

Processors

The distinction between preprocessors and postprocessors is that a class is considered ‘ready’ (e.g. can be instantiated) after the preprocessors have all been executed. Postprocessors typically perform functions like aliasing the class name to an xtype or back to a legacy class name – things that don’t affect the class’ behavior.

Each processor runs asynchronously, calling back to the Ext.Class constructor when it is ready – this is what enables us to extend classes that don’t exist on the page yet. The first preprocessor is the Loader, which checks to see if all of the new Class’ dependencies are available. If they are not, the Loader can dynamically load those dependencies before calling back to Ext.Class and allowing the next preprocessor to run. We’ll take another look at the Loader in another post.

After running the Loader, the new Class is set up to inherit from the declared superclass by the Extend preprocessor. The Mixins preprocessor takes care of copying all of the functions from each of our mixins, and the Config preprocessor handles the creation of the 4 config functions we saw last time (e.g. getTitle, setTitle, resetTitle, applyTitle – check out yesterday’s post to see how the Configs processor helps out).

Finally, the Statics preprocessor looks for any static functions that we set up on our new class and makes them available statically on the class. The processors that are run are completely customizable, and it’s easy to add custom processors at any point. Let’s take a look at that Statics preprocessor as an example:

//Each processor is passed three arguments - the class under construction,
//the configuration for that class and a callback function to call when the processor has finished
Ext.Class.registerPreprocessor('statics', function(cls, data, callback) {
    if (Ext.isObject(data.statics)) {
        var statics = data.statics,
            name;
        
        //here we just copy each static function onto the new Class
        for (name in statics) {
            if (statics.hasOwnProperty(name)) {
                cls[name] = statics[name];
            }
        }
    }

    delete data.statics;

    //Once the processor's work is done, we just call the callback function to kick off the next processor
    if (callback) {
        callback.call(this, cls, data);
    }
});

//Changing the order that the preprocessors are called in is easy too - this is the default
Ext.Class.setDefaultPreprocessors(['extend', 'mixins', 'config', 'statics']);

What happens above is pretty straightforward. We’re registering a preprocessor called ‘statics’ with Ext.Class. The function we provide is called whenever the ‘statics’ preprocessor is invoked, and is passed the new Ext.Class instance, the configuration for that class, and a callback to call when the preprocessor has finished its work.

The actual work that this preprocessor does is trivial – it just looks to see if we declared a ‘statics’ property in our class configuration and if so copies it onto the new class. For example, let’s say we want to create a static getNextId function on a class:

Ext.define('MyClass', {
    statics: {
        idSeed: 1000,
        getNextId: function() {
            return this.idSeed++;
        }
    }
});

Because of the Statics preprocessor, we can now call the function statically on the Class (e.g. without creating an instance of MyClass):

MyClass.getNextId(); //1000
MyClass.getNextId(); //1001
MyClass.getNextId(); //1002
... etc

Finally, let’s come back to that callback at the bottom of the picture above. If we supply one, a callback function is run after all of the processors have run. At this point the new class is completely ready for use in your application. Here we create an instance of MyClass using the callback function, guaranteeing that the dependency on Ext.Window has been honored:

Ext.define('MyClass', {
    extend: 'Ext.Window'
}, function() {
   //this callback is called when MyClass is ready for use
   var cls = new MyClass();
   cls.setTitle('Everything is ready');
   cls.show();
});

That’s it for today. Next time we’ll look at some of the new features in the part of Ext JS 4 that is closest to my heart – the data package.

Classes in Ext JS 4: Under the hood

Last week we unveiled a the brand new class system coming in Ext JS 4. If you haven’t seen the new system in action I hope you’ll take a look at the blog post on sencha.com and check out the live demo. Today we’re going to dig a little deeper into the class system to see how it actually works.

To briefly recap, the new class system enables us to define classes like this:

Ext.define('Ext.Window', {
    extend: 'Ext.Panel',
    requires: 'Ext.Tool',
    mixins: {
        draggable: 'Ext.util.Draggable'
    },
    
    config: {
        title: "Window Title"
    }
});

Here we’ve set up a slightly simplified version of the Ext.Window class. We’ve set Window up to be a subclass of Panel, declared that it requires the Ext.Tool class and that it mixes in functionality from the Ext.util.Draggable class.

There are a few new things here so we’ll attack them one at a time. The ‘extend’ declaration does what you’d expect – we’re just saying that Window should be a subclass of Panel. The ‘requires’ declaration means that the named classes (just Ext.Tool in this case) have to be present before the Window class can be considered ‘ready’ for use (more on class readiness in a moment).

The ‘mixins’ declaration is a brand new concept when it comes to Ext JS. A mixin is just a set of functions (and sometimes properties) that are merged into a class. For example, the Ext.util.Draggable mixin we defined above might contain a function called ‘startDragging’ – this gets copied into Ext.Window to enable us to use the function in a window instance:

//a simplified Draggable mixin
Ext.define('Ext.util.Draggable', {
    startDragging: function() {
        console.log('started dragging');
    }
});

When we create a new Ext.Window instance now, we can call the function that was mixed in from Ext.util.Draggable:

var win = Ext.create('Ext.Window');
win.startDragging(); //"started dragging"

Mixins are really useful when a class needs to inherit multiple traits but can’t do so easily using a traditional single inheritance mechanism. For example, Ext.Windows is a draggable component, as are Sliders, Grid headers, and many other UI elements. Because this behavior crops up in many different places it’s not feasible to work the draggable behavior into a single superclass because not all of those UI elements actually share a common superclass. Creating a Draggable mixin solves this problem – now anything can be made draggable with a couple of lines of code.

The last new piece of functionality I’ll mention briefly is the ‘config’ declaration. Most of the classes in Ext JS take configuration parameters, many of which can be changed at runtime. In the Ext.Window above example we declared that the class has a ‘title’ configuration, which takes the default value of ‘Window Title’. By setting the class up like this we get 4 methods for free – getTitle, setTitle, resetTitle and applyTitle.

  • getTitle – returns the current title
  • setTitle – sets the title to a new value
  • resetTitle – reverts the title to its default value (‘Window Title’)
  • applyTitle – this is a template method that you can choose to define. It is called whenever setTitle is called.

The applyTitle function is the place to put any logic that needs to be called when the title is changed – for example we might want to update a DOM Element with the new title:

Ext.define(‘Ext.Window’, {
    //..as above,
    
    config: {
        title: 'Window Title'
    },
    
    //updates the DOM element that contains the window title
    applyTitle: function(newTitle) {
        this.titleEl.update(newTitle);
    }
});

This saves us a lot of time and code while providing a consistent API for all configuration options: win-win.

Digging Deeper

Ext JS 4 introduces 4 new classes to make all this magic work:

  • Ext.Base – all classes inherit from Ext.Base. It provides basic low-level functionality used by all classes
  • Ext.Class – a factory for making new classes
  • Ext.ClassLoader – responsible for ensuring that classes are available, loading them if they aren’t on the page already
  • Ext.ClassManager – kicks off class creation and manages dependencies

These all work together behind the scenes and most of the time you won’t even need to be aware of what is being called when you define and use a class. The two functions that you’ll use most often – Ext.define and Ext.create – both call Ext.ClassManager under the hood, which in turn utilizes the other three classes to put everything together.

The distinction between Ext.Class and Ext.Base is important. Ext.Base is the top-level superclass for every class ever defined – every class inherits from Ext.Base at some point. Ext.Class represents the class itself – every class you define is an instance of Ext.Class, and a subclass of Ext.Base. To illustrate, let’s say we created a class called MyClass, which doesn’t extend any other class:

Ext.define('MyClass', {
    someFunction: function() {
        console.log('Ran some function');
    }
});

The direct superclass for MyClass is Ext.Base because we didn’t specify that MyClass should extend anything else. If you imagine a tree of all the classes we’ve defined so far, it will look something like this:

Sample-inheritance-tree

This tree bases its hierarchy on the inheritance structure of our classes, and the root is always Ext.Base – that is, every class eventually inherits from Ext.Base. So every item in the diagram above is a subclass of Ext.Base, but every item is also an instance of Ext.Class. Classes themselves are instances of Ext.Class, which means we can easily modify the Class at a later time – for example mixing in additional functionality:

//we can define some mixins at definition time
Ext.define('MyClass', {
    mixins: {
        observable: 'Ext.util.Observable'
    }
});

//it’s easy to add more later too
MyClass.mixin('draggable', 'Ext.util.Draggable');

This architecture opens up new possibilities for dynamic class creation and metaprogramming, which were difficult to pull off in earlier versions.

In the next episode, we’ll look at how the class definition pipeline is structured and how to extend it to add your own features.

Writing Compressible JavaScript

Writing a library is a balancing act between the (sometimes competing) interests of API clarity, code clarity, performance and compressibility. In this article I’m going to detail three of the approaches we take to meet this balance and suggest them for your own usage.

1. Collecting var statements

Every time we declare variables we add 4 bytes to the compressed file size. Variables are declared sufficiently often that this can really add up, so instead of this:

var myFirstVar = 'something'; 
var myOtherVar = 'another thing'; 
var answer = 42; 
var adama = true;

One should use this form:

var myFirstVar = 'something', 
    myOtherVar = 'another thing', 
    answer = 42, 
    adama = true;

When this code is compressed, each variable name above is turned into a single-letter name, meaning that the wasted 4 bytes per useless additional ‘var ‘ in the first example would have contributed significantly to code size with no benefit.

2. Local variable pointers to object properties

The following code (pruned from a previous version of Ext JS) is not as compressible as it could be:

var cs = {}; 
for (var n in this.modified) { 
    if (this.modified.hasOwnProperty(n)) { 
        cs[n] = this.data[n]; 
    } 
} 
return cs;  

We’re better off aliasing ‘this.modified’ to a local variable first. Aside from the performance benefits some JS engines derive from not having to perform object property lookups over and over again, we save precious bytes this way too:

var modified = this.modified, 
    changes  = {}, 
    field; 

for (field in modified) { 
    if (modified.hasOwnProperty(field)) { 
        changes[field] = this.data[field]; 
    } 
}

return changes;

Again, the minifier will compress those variable names down to a single character each, so for our ‘this.modified’ example we’re going to use 15 bytes to define the variable plus 1 byte each time we use it (totalling 15), vs the 26 bytes for that code previously. This approach scales especially well – were we to refer to this.modified a third time in the function, as our code will now minify to 16 bytes, vs 39 without the variable declaration.

Side note: in the first example here the variable ‘n’ was being used in the for…in loop. We can always safely exchange that for a meaningful variable name (in this case ‘field’) and leave the rest to the minifier.

3. Aliasing ‘this’ to ‘me’

In Ext.data.Record’s markDirty method we have the following code:

this.dirty = true; 
if(!this.modified){ 
    this.modified = {}; 
} 
this.fields.each(function(f) { 
    this.modified[f.name] = this.data[f.name]; 
},this);

There are 7 references to ‘this’ in that method, taking 28 bytes and completely incompressible. We could rewrite it like this (note that the final ‘this’ can be removed in this format):

var me = this; 

me.dirty = true; 
if (!me.modified) { 
    me.modified = {}; 
} 
me.fields.each(function(f) { 
    me.modified[f.name] = me.data[f.name]; 
});

Again, our minifier will change the ‘me’ var to a single character, saving us 8 bytes in this instance. That might not sound like a lot but after minification it equates to a 7% reduction in code size for this function.

In each of the cases above we’re generally talking about single-digit percentage savings after minification. There is value in that small slice though, especially as more and more applications shift onto bandwidth-constrained mobile platforms.

The first two approaches are no-brainers and must always be done but the third is slightly more controversial. Personally I find it makes the code a little harder to read, largely because my syntax highlighter doesn’t recognise that ‘me’ is now the same as ‘this’. Its value also varies significantly by function – some functions can contain over a dozen references to ‘this’, in which case this approach makes a big difference.

Answering Nicholas Zakas’ JavaScript quiz

A current meme that’s floating around the JavaScript geek corner of the internet is setting quizzes on some of the more unusual aspects of JavaScript. This time round Nicholas Zakas is providing the entertainment, so I thought I’d provide some answers. Let’s get started:

Question 1

Question 1 looks like this:

var num1 = 5,
    num2 = 10,
    result = num1+++num2;

We’re asked what the values of result, num2 and num1 are. First, let’s deconstruct what that +++ is doing. There is no +++ operator in JavaScript – instead we have a num1++ followed by a + num2.

JavaScript has two ways of incrementing a number by 1 – we can either put the ++ before the variable or after it. The variable is incremented either way – the only difference is what is returned. ++10 returns 11, whereas 10++ returns 10:

var a = 10;

var b = a++; //a is set to 11 now, but b is set to 10
var c = ++a; //a is set to 12 now, c is also set to 12

So ‘result’ is the sum of num1++ (which is 5) and num2, which is 10, so result equals 15. num2 remains at 10 as it was not modified. num1 is now equal to 6 because we incremented it by 1, though the incrementation did not affect the sum passed to result.

Question 2

var x = 5,
    o = {
        x: 10,
        doIt: function doIt(){
            var x = 20;
            setTimeout(function(){
                alert(this.x);
            }, 10);
        }
    };
o.doIt();

We’re asked what is alerted. This is mostly smoke and mirrors – there’s some indirection with all the duplicate names but the important thing here is the setTimeout. The function we pass to setTimeout gets run in the global scope, meaning ‘this’ refers to the window object. Declaring x as a variable in the global scope (var x = 5) is the same as setting window.x = 5, so 5 is alerted.

Question 3

var num1 = "10",
    num2 = "9";

We’re asked:

  • What is the value of num1 < num2?
  • What is the value of +num1 < num2?
  • What is the value of num1 + num2?
  • What is the value of +num1 + num2?

This question is all about type casting.

  • num1 < num2 is true – if both operands are strings JavaScript will compare them alphabetically, and "10" is lower alphabetically than "9"
  • +num1 < num2 is false – placing a "+" operator before a string casts it into a number, so we're actually testing 10 < "9". When testing a mixture of numbers and strings like this, everything is cast into a number, so we're testing 10 < 9, which is false
  • num1 + num2 === “109” – the plus sign can mean both addition and concatenation, depending on the operand types. Here we have 2 strings so we’re concatenating them together
  • +num1 + num2 === “109” also – again we’re casting num1 into a number, but the + operator means concatenation if at least one operand is a string

The confusion around this comes largely from the fact that the plus sign is used for both addition and concatenation in JavaScript. This causes the engine to have to test the typeof each operand and cast accordingly. All of the other math operators (e.g. /, *, % etc) cast both operands to numbers.

Question 4

var message = "Hello world!";

We’re asked:

  • What is the value of message.substring(1, 4)?
  • What is the value of message.substr(1,4)?
    • substring and substr do similar things. The first argument to each is the character index to start from, but whereas substring’s second argument is the character index to end at, substr’s second argument is the number of characters to return. Therefore message.substr(1, 4) will return a string of length 4, whereas message.substring(1, 4) will return a string of length 3 (4 – 1):

      • message.substring(1, 4); //”ell”
      • message.substr(1, 4); //”ello”

      Question 5

      var o = {
              x: 8,
      
              valueOf: function(){
                  return this.x + 2;
              },
              toString: function(){
                  return this.x.toString();
              }
          },
          result = o < "9";
      alert(o);
      

      We’re asked the value of ‘result’, and what gets alerted. This requires an understanding of the special valueOf and toString functions available on every object. These functions are used internally by the JavaScript engine to pull out the best representation of an object’s value based on the situation.

      When alerting a value, we want a string representation so toString is called. When comparing the value to another object, valueOf is called instead. So alert(o) alerts “8”, and result is set equal to the result of 10 < "9". The JavaScript engine will decide when to use which option, or we can specify it ourselves:

      var num1 = 8, num2 = 9;

      num1 + num2; //17
      num1.toString() + num2.toString(); //"89"
      num1.valueOf() + num2.valueOf(); //17

      The 'result' assignment needs a little explanation. First, the engine calls valueOf on the object, which returns 10. Second, because one of the operands to the < operator is a number, the other is also cast into a number, so we are testing 10 < 9, which returns false. We could instead force it to use toString: o.toString() < "9" returns true.

      Quizzes like this are great for getting your teeth into some of the guts of JavaScript, but don't mistake them for a good way to write code. The point is to demonstrate how quirky JS code can be unless you write it in a sensible way.

Ext JS is looking for a QA rockstar

This has been cross-posted from our Open Discussion Forum.

As part of our ambition of creating the world’s best JavaScript framework, we’re looking to hire a special somebody to help maintain the high quality of our components.

While we have one eye on implementing new features and improving Ext JS’s performance, the other is on making sure what we already have still works well.

This is a difficult job and we need someone smart, focused and well versed in Ext JS. Somebody who will:

* Use our existing systems to test components as new builds of the library are landed
* Maintain a strong presence in the forums and be the first to know of any reported issues
* Respond to bug tickets such as rendering issues and broken functionality
* Totally own the Quality Assurance of Ext JS – we want your ideas and your initiative as well as your expertise with Ext
* Liaise with the core team on a daily basis

This is a full-time position, though allowances can be made for the right person. If you think you would enjoy working with Ext JS, and have what it takes to help us keep Ext at the forefront of our field, drop me a private message with the following information:

* Your name
* Email address
* Location (city, country, timezone)
* All experience with Ext JS
* Bonus points for links to open source software

JavaScript FizzBuzz in a tweet

The FizzBuzz challenge has been around a while but I stumbled across it again after reading another unique Giles Bowkett post.

If you’re not familiar with FizzBuzz, it’s a little ‘challenge’ designed to test a candidate programmer’s ability to perform a simple task. In this case, you just have to print out the numbers from 1 to 100, unless the number is a multiple of 3, when you should instead print “Fizz”, 5 in which case you print “Buzz”, or both 3 and 5 in which case you print “FizzBuzz”.

Here’s a trivial JavaScript implementation:

for (var i=1; i &lt;= 100; i++) {
  if (i % 3 == 0) {
    if (i % 5 == 0) {
      console.log('FizzBuzz');
    } else {
     console.log('Fizz');
   }
  } else if (i % 5 == 0) {
    console.log('Buzz');
  } else {
    console.log(i);
  }
};

Pretty simple stuff, but a bit verbose. I wanted something that would fit into a tweet. It turns out that’s pretty simple – this is 133 characters including whitespace, 7 within tolerance for a twitter message:

for (var i = 1; i &lt;= 100; i++) {
  var f = i % 3 == 0, b = i % 5 == 0;
  console.log(f ? b ? &quot;FizzBuzz&quot; : &quot;Fizz&quot; : b ? &quot;Buzz&quot; : i);
}

Which of course begs the question – just how short can a JavaScript FizzBuzz implementation be? Here’s my baseline, which is a tortured and contorted version of the above:

for(i=1;i&lt;101;i++){console.log(i%3?i%5?i:&quot;Buzz&quot;:i%5?&quot;Fizz&quot;:&quot;FizzBuzz&quot;)}

The above is 71 characters – I expect you to do better. The rules are that the only dependency is Firebug’s console.log being available, and you can’t replace ‘console.log’ for anything else.

Of course, if we did swap ‘console.log’ for ‘alert’, the whole thing would fit in a tweet twice, but that would be damn annoying.

Hint: you can take at least three more characters off the above – can you see how?

Using the ExtJS Row Editor

The RowEditor plugin was recently added to the ExtJS examples page. It works a lot like a normal Grid Editor, except you can edit several fields on a given row at once before saving.

This neatly solves the problem of adding a new row to an editor grid, entering data into the first field and finding it save itself straight away, which is rarely desired. In this fashion we can provide full CRUD for simple models in a single page.

Installation

You’ll need to get a copy of the javascript, css and images from the server. This is a bit of a pain. If you still have the ExtJS SDK around you can find these in the examples folder, if not you can get each file as follows:

Grab the plugin JS file below and put it where you usually put your .js files:
http://www.extjs.com/deploy/dev/examples/ux/RowEditor.js

This needs to go with your other stylesheets, usually in a directory called ‘css’:
http://www.extjs.com/deploy/dev/examples/ux/css/RowEditor.css

Download these two images and put them into your existing ‘images’ folder (the same place the other ExtJS images live):
http://www.extjs.com/deploy/dev/examples/ux/images/row-editor-bg.gif
http://www.extjs.com/deploy/dev/examples/ux/images/row-editor-btns.gif

Include the .js and .css files on your page and you should be ready to go.

Usage

RowEditor is a normal grid plugin, so you’ll need to instantiate it and add to your grid’s ‘plugins’ property. You also need to define what type of Editor is available (if any) on each column:

var editor = new Ext.ux.grid.RowEditor();

var grid = new Ext.grid.GridPanel({
  plugins: [editor],
  columns: [
    {
      header   : 'User Name',
      dataIndex: 'name',
      editor   : new Ext.form.TextField()
    },
    {
      header   : 'Email',
      dataIndex: 'email',
      editor   : new Ext.form.TextField()
    }
  ]
  ... the rest of your grid config here
});

RowEditor defines a few events, the most useful one being ‘afteredit’. Its signature looks like this:

/**
 * @event afteredit
 * Fired after a row is edited and passes validation.  This event is fired
 * after the store's update event is fired with this edit.
 * @param {Ext.ux.grid.RowEditor} roweditor This object
 * @param {Object} changes Object with changes made to the record.
 * @param {Ext.data.Record} r The Record that was edited.
 * @param {Number} rowIndex The rowIndex of the row just edited
 */
'afteredit'

All you need to do is listen to that event on your RowEditor and save your model object appropriately. First though, we’ll define the Ext.data.Record that we’re using in this grid’s store:

var User = Ext.data.Record.create([
  {name: 'user_id', type: 'int'},
  {name: 'name',    type: 'string'},
  {name: 'email',   type: 'string'}
]);

And now the afteredit listener itself

editor.on({
  scope: this,
  afteredit: function(roweditor, changes, record, rowIndex) {
    //your save logic here - might look something like this:
    Ext.Ajax.request({
      url   : record.phantom ? '/users' : '/users/' + record.get('user_id'),
      method: record.phantom ? 'POST'   : 'PUT',
      params: changes,
      success: function() {
        //post-processing here - this might include reloading the grid if there are calculated fields
      }
    });
  }
});

The code above simply takes the changes object (which is just key: value object with all the changed fields) and issues a request to your server backend. ‘record.phantom’ returns true if this record does not yet exist on the server – we use this information above to specify whether we’re POSTing to /users or PUTing to /users/123, in line with normal RESTful practices.

Adding a new record

The example above allows for editing an existing record, but how do we add a new one? Like this:

var grid = new Ext.grid.GridPanel({
  //... the same config from above goes here,
  tbar: [
    {
      text   : &quot;Add User&quot;,
      handler: function() {
        //make a new empty User and stop any current editing
        var newUser = new User({});
        rowEditor.stopEditing();
        
        //add our new record as the first row, select it
        grid.store.insert(0, newUser);
        grid.getView().refresh();
        grid.getSelectionModel().selectRow(0);
        
        //start editing our new User
        rowEditor.startEditing(0);
      }
    }
  ]
});

Pretty simple stuff – we’ve just added a toolbar with a button which, when clicked, creates a new User record, inserts it at the top of the grid and focusses the RowEditor on it.

Configuration Options

Although not documented, the plugin has a few configuration options:

var editor = new Ext.ux.grid.RowEditor({
  saveText  : &quot;My Save Button Text&quot;,
  cancelText: &quot;My Cancel Button Text&quot;,
  clicksToEdit: 1, //this changes from the default double-click activation to single click activation
  errorSummary: false //disables display of validation messages if the row is invalid
});

If you want to customise other elements of the RowEditor you probably can, but you’ll need to take a look at the source (it’s not scary).

Final Thought

RowEditor is a really nice component which can provide an intuitive interface and save you writing a lot of CRUD code. It is best employed on grids with only a few columns – for models with lots of data fields you’re better off with a full FormPanel.

I’d be pretty happy to see this included in the default ExtJS distribution, as I find myself returning to it frequently.

Moving from Blogger to WordPress

Over the weekend I migrated from Blogger (hosted by Google) to WordPress (hosted by me). Overall, WordPress feels far superior, but the migration was not without problems. Here’s a short guide to what I had to do:

Get WordPress

First, grab the latest version of WordPress. Being a PHP application, it just drops into a directory and works 🙂

Create a database, set config

WordPress has a setup script but being a bit of a noob I couldn’t give it write permission to my filesystem. If you are also afflicted by such inadequacies the following steps may help you. For clarity I’ll call my DB ‘wordpress’. First, set up your database:

  1. mysql -u root
  2. CREATE DATABASE wordpress;
  3. GRANT ALL on wordpress.* TO ‘wordpress’@’localhost’ identified by ‘wordpress’;

You’ll need a wp-config.php file – WordPress comes with a default one which you can copy thusly (in the root directory of your wordpress directory):

cp wp-config-sample.php wp-config.php

Now edit wp-config.php, and fill in the details to make it look a little like this:

// ** MySQL settings – You can get this info from your web host ** //
/** The name of the database for WordPress */
define(‘DB_NAME’, ‘wordpress’);

/** MySQL database username */
define(‘DB_USER’, ‘wordpress’);

/** MySQL database password */
define(‘DB_PASSWORD’, ‘wordpress’);

/** MySQL hostname */
define(‘DB_HOST’, ‘localhost’);

Hitting the site now should show a default WordPress installation with some dummy content. Whoop.

Import from Blogger

Importing from Blogger is pleasingly simple – just use the Tools -> Import option on the menu. It’ll ask you to verify access and then pull down all your posts and comments.

It’s not perfect though – for me the post Tags were imported as Categories. To get them to be Tags again, go to the Posts -> Categories menu and use the handy Categories to Tags converter.

I found that the imported Post markup was pretty mangled (I think this is Blogger’s fault, not WordPress’) – <br />s everywhere and no line breaks. To resolve this I cracked open mysql again and ran the following:

  1. use wordpress;
  2. UPDATE wp_posts SET post_content = REPLACE(post_content, “<br />”, “n”);

That sorted me out alright. Next we need to set up how our permalinks work. Set this in the Settings -> Permalinks menu, and use the following format to mimic the Blogger urls:

/%year%/%monthnum%/%postname%.html

WordPress will either write a .htaccess file for you at this point, or tell you it can’t write to the filesystem and give you a short text config which you must manually copy into a file called .htaccess.

One final thing to note is that WordPress constructs its slug urls differently to Blogger (WordPress would use ‘the-trouble-with-new’ vs Blogger’s ‘trouble-with-new’, for example). If you’re importing blog posts this means your urls won’t always match, so any incoming links will be broken. I couldn’t find an easier way to correct them than just copy/paste by hand – doesn’t take long though.

Syntax Highlighting

This whole step is entirely optional.

Because I’m a geek I post code fairly often. I used the SyntaxHighlighter library back in the Blogger days and wanted to keep using it. You can install the WordPress plugin version from http://www.viper007bond.com/wordpress-plugins/syntaxhighlighter/. The old syntax didn’t seem to work, so I needed to go back into mysql and run the following:

UPDATE wp_posts SET post_content = REPLACE(post_content, "<pre name="code" class="js">", "[c0de language="js"]");
UPDATE wp_posts SET post_content = REPLACE(post_content, "</pre>", "[/c0de]");

NOTE: So that WordPress doesn’t interpret those tags above I’ve changed the ‘o’ in code to a ‘0’. You need to change it back 🙂

This just swaps all your old <pre name="code" class="js"> and </pre> tags for [c0de language=”js”]and [/c0de] respectively. Repeat the first line for any other languages you have used (for me this was xml, css, html and ruby).

Fixing feeds

WordPress doesn’t like the world to see your content via RSS. Odd, isn’t it? There’s an option in Settings -> Reading which claims to output the full text of each article into your feed, but it doesn’t seem to work. Instead, what you need to do is hack your theme a little. You’ll need to edit the wp-includes/feed-rss2.php file and change line 47 from <?php the_excerpt_rss() ?> to <?php the_content() ?>.

If you’re using Feedburner or similar, don’t forget to give it your new feed url too. In this case you should also update wp-content/themes/yourTheme/header.php and swap out the occurrences with your Feedburner url.

Upload and update DNS

At this point everything should be working nicely, so upload your blog folder and update your DNS settings. I’m guessing if you’re hosting WordPress yourself you don’t need help with this. I’ve made my own blog into a git repository up on Github, allowing me to deploy any changes I make using Capistrano. It’s a nice solution – for more information see this lovely post by the gentlemen at imedo.

Read my BDD article in this month’s JS Magazine

I have an article on Behaviour Driven Development for JavaScript in June’s edition of the excellent JavaScript Magazine.

If you haven’t seen or read the magazine before (it’s quite new), it’s well worth the few dollars charged. The magazine format allows for in-depth articles that require more space, time and effort to write than a typical blog post, and which therefore often go unwritten.

The thrust of my article is that too much of our JavaScript goes untested, but that nowadays it’s easy to fix that. I go through an example of a client side shopping cart, using the JSpec BDD library. Even if you don’t buy/read the magazine, I highly recommend checking out JSpec and other libraries like it. As JavaScript powered applications become the norm, BDD will only become more important in ensuring our applications work properly, so now is a good time to start.

Also in this month’s issue is a guide to using the Canvas tag, tips on how to use build scripts to optimise your JavaScript for each environment, AJAX security pointers and a roundup of community news.

%d bloggers like this: