I’m officially announcing the jsKata librairies.
Why?
I just wanted to write some public code and share it with others. Javascript has a lot of pains in the butt and jQuery is not the answer to every problem. jsKata is the answer to some of the problems that I face everyday while writing javascript.
A manifesto?
I wrote a manifesto because it helps me focusing on what and how I want to achieve with jsKata. This is the manifesto of version 0.2.
- No internal dependence : every library can be used independently “as is”.
- No external dependence : don’t depend on external libraries.
- Everything is public : you know what you’re doing
- Avoid objects : use closures
- No unnecessary validation : if something goes wrong, an error will pop
- No error catching : if an error pop, it goes all the way up
- No DOM : jQuery already exists
- No plugins : if a developer wants to add something, he will find a way around
- Write good documentation : document as I code
- Promote : a good library is nothing without users
What are the libraries available?
I don’t consider jsKata to be a library but more a set of libraries because each one can be used independently (see #1 in manifesto). For the moment, there are two librairies.
Undo & redo
I wrote about undo and undo & redo before. I took the code and put it in jsKata. You can look at the code or try the demo.
No freeze
This librairy is to avoid unresponsive script warning when you have a really long loop. It cuts a loop to create digestible chunks without a warning. I’ll write more about this one in the future but meanwhile, you can look at the code or try the demo.
GitHub
All the code is hosted on GitHub. I hope you will enjoy it!
First of all, de-anonymized functions are called named functions and they look a lot like “regular” functions (in fact, they are).
Why should I de-anonymize?
For debugging. Instead of having a stack trace filled with ?() (representing an anonymous function), it is nicely printed and easier to follow.
For self-reference. Example, when you want an anonymous function to recall itself recursively, you would have to call arguments.callee. It’s odd and it’s deprecated anyway (people pointed to me that it’s not really deprecated but it throws an error in ECMAScript 5 strict).
Stack trace of anonymous functions…
If you run this in your firebug console (every javascripter should have firebug).
You get a stack trace that looks like this :
func()
func()
func()
… versus stack trace of named functions
You get a stack trace that looks like this :
f1()
f2()
f3()
As you can see, it’s a lot easier to debug and to understand who’s calling who.
Warning : There’s a bug in IE with named functions.
Recursive anonymous function
Let’s create a recursive anonymous function that counts to 10.
And let’s create it but using a named function.
Once again, the code is much clearer and it’s not using a deprecated element.
A note about closures to advanced javascripters
I just wanted to say that in the last example, you could have written this :
As you can see at line 4, I call the count function which is not the name of the function but the variable to which the function is assigned. It works, but it may not be the best thing to do. You can learn more about closure on that previous post and I’ll write more about it.
I wrote about undo before and I pushed it farther. What about an undo/redo system? I extended the v.01 of the undo and I now handle undo and redo in the same object.
Annoucing redo in jskata.undo
I made a new version of jskata.undo still hosted on GitHub. If you look closer, it is now part of a library called jskata that is not officially announced. My next post will talk about it in details.
Demo
Take a look at the demo. The javascript of the demo is available here. You can see the complete doc on GitHub.
How does it work?
Execute an action that you can undo/redo
Doing something requires calling execute with 2 functions as parameters : the do and the undo.
Undo and redo the last action
Very easy!
Events and properties
For the moment, jskata.undo has just one event : onChange.
There are 2 properties : canUndo() and canRedo().
Posted
on April 6, 2010, 8:55 am,
by Dan,
under
white belt.
There’s a common error that happens quite a lot on IE only and never on Firefox. You search it, you check all your variables, you comment your code to the bare minimum but you can never find it.
Stop looking! Here’s the answer.
You probably just forgot a comma (,) at the end of a hash. Here’s an example :
-
var val = {
-
cat:"Mistigri",
-
dog:"Rex",
-
butler:"Jeeves", // There’s an extra comma
-
}
You see the extra comma at the string “Jeeves”? This what causes the problem. Firefox handles an extra comma nicely but Internet explorer doesn’t. To correct the error, just write :
-
var val = {
-
cat:"Mistigri",
-
dog:"Rex",
-
butler:"Jeeves" // There’s no extra comma
-
}
JSLint to the rescue
Programmieraffe told me about JSLint. You paste your javascript code and it verifies it for you. Not only for extra-commas but everything else.
I really like undos. If I could undo that that last beer… Unfortunately, I can’t. But, I can offer undo to users of my application.
When I thought about undo before, I thought about a complicated Rails plugin that would keep an anonymous ID linking to any table in the database with an “action” field that would contain the action to undo. Pretty complicated stuff for something as simple.
The javascript solution
One day while I was writing some javascript, the solution struck me : I could handle this completely with javascript. The basic idea is that whenever an action is completed, I can save its undo function in an array and call it whenever I need it.
Example, if I’m saving a user in a database with Ajax :
- I send the data to server to save a new user
- The server returns the ID of the new user
- I create a function with an ajax request that will send a delete of this user to the server
- I add the previous function to a stack of undo functions to be able to call it later
That, when I call that last function, it will undo that user creation without having to keep it in memory server-side.
Introducing jsKata.undo
I wrote a little something called jsKata.undo on GitHub that contains the logic describe earlier. It’s quite simple but it may grow over time. It has no requirement, not even jQuery. It’s very simple to use.
The complete doc is on GitHub.
1. Adding an action that can you can undo
I’ll use the “add a user” example with jQuery.
-
$.post(
-
"http://yoursite.com/users/new", // The url to add a user
-
{name:"John Boucher"}, // The name of the user
-
function(newUser, textStatus, XMLHttpRequest) {
-
// This is called when the post is over
-
var newUserId = newUser.id;
-
-
// We begin by creating a function to delete the user
-
var undoNewUser = function() {
-
$.post(
-
"http://yoursite.com/users/delete", // The url to delete a user
-
{id:newUserId} // The ID of the new user to delete
-
);
-
}
-
-
// We add the undo function to the stack
-
jskataUndo.push(undoNewUser);
-
}
-
);
2. Undo the last action you made
3. Events
Each time there’s a change, an onChange event is called. To assign yours, simply write :
-
jsKata.undo.onChange = function() {
-
// Show the undo button
-
$("#undoButton").show();
-
}
There’s also an onEmpty event that is called when the stack of undoable actions is empty.
-
jsKata.undo.onEmpty = function() {
-
// Hide the undo button
-
$("#undoButton").hide();
-
}
Complete demo
There is a complete demo on GitHub as well as the HTML and Javascript code for it. Take a look!
Sometimes, it feels to me that javascript was invented for the only purpose of writing calendars to select a date. I wrote one myself (because I had to, not because I wanted to) in a previous job. I use a new calendar that is “better than the other one” on each of my project. It seems like the world will never run out of javascript calendars. In fact, you probably are writing a new one as you read this.
I want to talk about a different kind of calendar. The really hard one to write : calendars for displaying events in jquery.
The pretty jquery-week-calendar
Written by Rob Monie, this is the first one I tried. I was amazed about how easy it was to integrate with the current development of Timmy (you can see an early beta when you’re logged here). You can take a look at the demo. Unfortunately, I had unexplicable bugs and I didn’t take the time to understand them. Please, don’t do like me and participate to the code on GitHub.
- Looks good
- Easy to integrate
- May be buggy when drag-dropping/resizing
The robust fullcalendar
We switched to this calendar, written by Adam Shaw, because it had three different views (month, week, day) and because we had some problem with the other calendar. It doesn’t look as good as the week-calendar (demo). You can also participate on GitHub.
- The default look is OK
- Harder to work with
- Display may seem slow (on firefox)
- More robust than week-calendar
Finally
These guys have made a great job doing something really hard. Just think about two overlapping events or when an event is two minutes long or hundreds of special cases that could happen. Kudos to them for giving their time and talent to us.
A word about git
Our team (me and Frank, the RubyFleebie guy) worked with SVN for a couple of years until Git stole the spotlight. For a couple of months, we worked with it and enjoyed it. Until we had to do “more advanced” things (branching, merging which is pretty basic to my sense) and things got incredibly hard. We switched to Mercurial a couple weeks ago which feels more like the perfect mix between SVN and Git. So if, like us, you feel puzzled by Git, give Mercurial a chance.
If I look at my stats, a lot of people are wondering how to write a singleton class. I already wrote about it before but my old solution exposed the instance of the class so more than one instance could be created thus making it not completly a singleton class.
Here’s the new solution using a private variable for the instance.
-
function Cats() {
-
var names = [];
-
-
this.singletonInstance = null;
-
-
// Get the instance of the Cats class
-
// If there’s none, instanciate one
-
var getInstance = function() {
-
if (!this.singletonInstance) {
-
this.singletonInstance = createInstance();
-
}
-
return this.singletonInstance;
-
}
-
-
// Create an instance of the Cats class
-
var createInstance = function() {
-
// Here, you return all public methods and variables
-
return {
-
add : function(name) {
-
names.push(name);
-
return this.names();
-
},
-
names : function() {
-
return names;
-
}
-
}
-
}
-
-
return getInstance();
-
}
How to use it
-
function run() {
-
// Add a new cat
-
var cat1 = new Cats();
-
cat1.add("Mistigri");
-
jsKataEx.assert(cat1.names().length == 1, "cat1 contains 1 cat : " + cat1.names().toString());
-
-
// Use another instance
-
var cat2 = new Cats();
-
jsKataEx.assert(cat2.names().length == 1, "cat2 contains Mistigri added in cat1 : " + cat2.names().toString());
-
-
// Add another cat in the other instance
-
cat2.add("Felix");
-
jsKataEx.assert(cat2.names().length == 2, "cat2 contains Mistigri and Felix" + cat2.names().toString());
-
jsKataEx.assert(cat2.names().length == 2, "cat1 also contains Mistigri and Felix" + cat1.names().toString());
-
}
Get the code on GitHub and see it live in action.
In short, you can use private variables when you return another scope when declaring a class.
-
function Cats() {
-
var nameList = []; // private var
-
-
// This is where you define another scope!
-
return {
-
add:function(name) {
-
nameList.push(name);
-
}
-
}
-
}
How does it work?
The magic lies in creating a different scope at the end of the class definition that does not include private variables. Then, private members are available in this scope and not outside of it, thanks to the power of closures.
Differences between private and public
These two classes definition shows the difference between the a class where all members are public versus a class where some members are private.
This is a class where all members are public.
-
function PublicCats() {
-
// This is the list of cat names
-
this.nameList = [];
-
-
// This is a method that I would like to be private but can’t
-
// It returns the last cat of the list
-
this.lastCat = function() {
-
return this.nameList[this.nameList.length-1];
-
}
-
-
// Return the list of names
-
this.names = function() {
-
return this.nameList;
-
}
-
-
// Add a name to the list
-
this.add = function(name) {
-
this.nameList.push(name);
-
-
// Return the last cat just added
-
return this.lastCat();
-
}
-
}
This is the corresponding class where some members are private.
-
function PrivateCats() {
-
// This is the list of cat names
-
var nameList = [];
-
-
// This is a private method
-
var lastCat = function() {
-
// Note : I don’t use "this" to access private variables
-
// thanks to the power of closures!
-
return nameList[nameList.length-1];
-
}
-
-
// These are our public methods!
-
// This is where we create another scope to
-
// avoid external objects to use the private variables.
-
return {
-
add:function(name) {
-
// Note : once again, I don’t use "this"
-
// to access the private variables and methods
-
nameList.push(name);
-
return lastCat();
-
},
-
names:function() {
-
return nameList;
-
}
-
}
-
}
In the above code, line 15 makes all the difference between the two classes.
On GitHub
Get all the code on GitHub and see it live in action on my GitHub page.
This post is an update from the old post. A lot of things changed since it was written and the information in the old one is a bit outdated.
First of all, you should never use an eval() when using JSON because of security reasons that I will talk about later in another post. [edit : jQuery uses eval() but there's a work-around that will be talked about in another post.]
JSON and jQuery
The simplest way to use JSON is though jQuery. I have been using for more than 2 years and I never was disappointed.
Let’s say I want to call Flickr search with JSON. It’s simple :
-
$.getJSON(
-
"http://api.flickr.com/services/rest/?jsoncallback=?",
-
{ method : "flickr.photos.search",
-
api_key : "4ef2fe2affcdd6e13218f5ddd0e2500d",
-
format : "json",
-
tags : "landscape",
-
},
-
ajaxCallBack
-
);
-
The $.getJSON takes 3 parameters.
1. The URL
The URL of the remote call.
2. The parameters
The parameters to complete the call. On the documentation page about this Flickr method, you have a list of all the parameters you can use. For a JSON call on Flickr, you have to send the api_key and the format. I added the parameter tags to send me all photos that are tagged landscape.
3. The callback
Most API services now requires a callback, a method that will be called when the JSON is loaded. It is more secure and easier to work with. At the end of the first parameter (the URL), I added jsoncallback=? (flickr called this parameter jsoncallback but it could be named differently on other services). This is the jQuery-way of saying “When you finish loading the JSON, call the method specificied by the third argument”.
You may wonder how Flickr knows which function to use on callback. It’s because in jQuery, there’s a special case for that. In the URL, you can see that the jsoncallback is written like that jsoncallback=?. The ? is replaced by your own callback method (in my case, I called it ajaxCallback)
The callback method
The callback method I used looks like this :
-
function ajaxCallBack(data) {
-
// Loop throught all photos and display them
-
// it uses the jquery.each method
-
// doc at http://docs.jquery.com/Utilities/jQuery.each
-
$.each(data.photos.photo, function(photoIdx, photo) {
-
// Build the thumbnail url
-
var thumb_url = ["http://farm", photo.farm, ".static.flickr.com/",
-
photo.server, "/", photo.id, "_", photo.secret, "_t.jpg"].join("");
-
-
// Build the photo url
-
var photo_url = ["http://www.flickr.com/photos/",
-
photo.owner, "/", photo.id].join("")
-
-
// Build HTML
-
$("body").append(
-
$("<a>")
-
.attr("href", photo_url)
-
.attr("target", "_blank")
-
.append(
-
$("<img>").attr("src", thumb_url)
-
)
-
)
-
});
-
}
-
If you know jQuery a little, it simply creates the HTML to show the thumbnails and a link to the photo.
Get the code
You can get the complete code for this example on GitHub and a working example.
Posted
on May 12, 2009, 10:24 am,
by Dan,
under
white belt.
There’s something bugging me with javascript for loop : the extra work to loop though all elements of an array. Suppose I want to alert each element of an array, there are three ways of doing it.
First, you loop with an index and assign the element to a variable.
-
var items = ["a", "b", "c"];
-
for (var i = 0; i < items.length; i++) {
-
var item = items[i];
-
alert(item);
-
}
You always have to have that extra assignment at the beginning of the loop.
Second, you loop with a for each.
-
var items = ["a", "b", "c"];
-
for (var i in items) {
-
var item = items[i];
-
alert(item)
-
}
In javascript, the for each loops though the index of the array instead of looping though the elements, like in most other languages. Thus, you also have to make the extra assignment at the beginning of the loop.
The easiest way of doing it is the third one.
-
var items = ["a", "b", "c"];
-
for (var i = 0, item; item = items[i]; i++) {
-
alert(item);
-
}
How does it work? First it uses multi-assignment on one line. In javascript, you could write var i = 0, j = 1; and it would create two variables, i and j.
The second part of the for is confusing : it assigns the item but it never check if i it is out of bounds of the array (using i < items.length). It works because when javascript tries to assign an item after the end of the array (in our case items[3]), it returns null which is considered by javascript as false.