Follow me: @D_mitar

Most read posts recently



Nov 9th 2011 × Using MooTools class mutators to log method calls

When you are debugging a huge web app, comprised of many classes and many methods, it can be really tedious and difficult. Having to go and edit code and add `console.log` calls all over the place is hardly productive and can involve a lot of typing. Fortunately, you can use a lesser known feature of MooTools called ‘Class Mutators’ to change the prototype of your class and automatically log calls to your methods of interest.

// define the mutator as 'Monitor', use as Mointor: ['methodname', 'method2'...]
Class.Mutators.Monitor = function(methods){
    if (!this.prototype.initialize) this.implement('initialize', function(){});
    return Array.from(methods).concat(this.prototype.Monitor || []);
};

Class.Mutators.initialize = function(initialize){
    return function(){
        Array.from(this.Monitor).each(function(name){
           var original = this[name];
           if (original) this[name] = function() {
               console.log("[LOG] " + name, "[SCOPE]:", this, "[ARGS]", arguments);
               original.apply(this, arguments);
           }
        }, this);
        return initialize.apply(this, arguments);
    };
};

What this does is defines a class mutator called ‘Monitor’, which can be added to any class declaration. It accepts either a single method name (as string) or an array of method names that you would like to log.

In your class, this will look like this:

var foo = new Class({

    Monitor: 'bar',

    initialize: function() {
        this.bar("mootools");
    },

    bar: function(what) {
        alert(what);
    }

});

var f = new foo();
f.bar.call({hi:"there from a custom scope"}, "scope 2");

When the code runs, you will see in your console the 2 calls to the monitored method, indented by method name, the scope and the arguments it has received.

This can save your life. Play on jsfiddle: http://jsfiddle.net/BMsZ7/2/ :)


Nov 2nd 2011 × mooGrowl: a lightweight growl style class for mootools 1.4

There was notiMoo and I am sure there have been other javascript/mootools Growl notification solutions already. Yet, none of them were CSS3 and mootools 1.4 friendly, so I created a new Class instead.

Check out mooGrowl on GitHub
https://github.com/DimitarChristoff/mooGrowl

View the demo on jsfiddle:
Full screen or normal jsfiddle

Screenshot of some Growls:

no

Oct 31st 2011 × mooPlaceholder revisited: a flexible placeholder input solution for IE and older browsers

Creating some javascript that can mimic the HTML5 behavior of a placeholder= attribute on an input element can be simple. Unfortunately, getting a single solution you can work with that fits all browsers and have little overhead to work with is not that easy.

The following are the requirements when making it universal:

  • work as progressive enhancement for browsers that don’t support it only (feature-detect)
  • respect initial values
  • be able to attach and detach the placeholder behavior on demand

Since the progressive enhancement only works by using the value property of the input in older browsers, it presents a problem for form validation. You don’t want your form submission to go through with fields that have the placeholders assigned as the actual values. This is not what the native placeholder behavior is so you need a way to remove the enhancement prior to your form validation and submission. You also need to be able to re-attach it, should validation fail and submission be stopped pending user action.

http://jsfiddle.net/dimitar/bYQ8P/ is the updated mooPlaceholder class. I suggest you view it in IE6/7/8 to actually experience the difference. It should act *exactly* how the placeholder works in say, FireFox 7. To get around the jsfiddle issues with IE, view it under the full /show/ url here

So, to recap: if you want to validate a form that has child elements managed by the class, you’d do the following when using my Class:

var placeholders = new mooPlaceholder().attachToElements(); // add it.
formElement.addEvent("submit", function(e) {
    // remove placeholder while validating...
    placeholders.detachFromElements();
    // run validation code here.
    if (failed) {
        e.stop(); // stop submit
        placeholders.attachToElements(); // restore placeholders
    }
});

I think this overhead is quite acceptable, considering. It can be done automatically on your form submits by doing a element.getParent(“form”) but this way is also fine. Hope it helps somebody.


Oct 18th 2011 × Working with dynamic Class names in MooTools

This is somewhat trivial but is also useful and is a common question that a lot of people ask. The problem is in 2 parts: How to instantiate a Class based upon a dynamic name/variable and how to identify the Class name that has created a MooTools Class instance (the prototype, really).

First of all, to make a dynamic instance based upon a variable name, you simply need to know the name and context of execution (scope) of the Class you want to instantiate.

// define the class in the current scope / global object
this.foo = new Class();

// define the class in a namespace
var namespace = {
    foo: new Class()
};

// get the variable class name we need to use from any source into a variable...
var dynamic = 'foo';

// make the instances
var instance1 = new this[dynamic]();
var instance2 = new namespace[dynamic]();

So far, so good. This is pretty standard javascript and is self explanatory.

The harder bit comes when you have an instance and you are trying to find what Class name it is an instance of. We will create a small function that can help:

function getClassNameOfInstance(mootoolsClassInstance, context) {
    // query the context (this or custom object) for the instance we are working with
    return Object.keyOf(context || this, mootoolsClassInstance.constructor);
}

// use it on the global object
console.log("instance1 is: ", getClassNameOfInstance(instance1)); // foo

// use it on the namespace object
console.log("instance2 is: ", getClassNameOfInstance(instance2, namespace)); // foo

This function will check the context object for the constructor of the instance and return the ‘key’ if it matches, which will be MooTools Class name.

I hope it helps someone out there. Check it on JSFIDDLE: http://jsfiddle.net/dimitar/S4rR6/2/


Aug 24th 2011 × So long and thanks for all the fish

This is one of these posts that you write with your heart sunk and a feeling of regret… After 4+ fabulous years with WebTogs, I am moving on to pastures new.

It has been an absolute blast. I got the chance to start with a simple whiteboard idea and built a e-commerce start-up from the ground-up. A chance that I dare say took and did well out of, considering the lack of resources and other developers. Today, WebTogs is no longer a mere start-up site: it is a widely recognised and award-winning brand name, probably one of the biggest in the outdoors e-commerce industry. I cannot help but step back and marvel at our accomplishment with pride.

I got the chance to work with all aspects of the development process, from server administration, mysql structure and optimisation, PHP code, HTML 5, CSS3, javascript, SEO and SEM. I also got to discover the wonderful world of MooTools and have not looked back since.

But it is now time to pursue a career in what I have discovered that I enjoy doing the most: Front-End development with JavaScript and MooTools in particular. To that end, I am happy to say I have joined a new startup by QMetric and am looking forward to whatever new challenges that brings as well as whatever new skills and practices working there will allow me to develop.

I will continue helping out the guys at WebTogs as much as I can and hope we can continue our relationship together. Some of the people at Webtogs I have known and worked with for over 10 years and that’s a loooong time indeed. Thank you for all the great moments and the incredible mutual respect, flexibility and understanding that allowed us to create the site and build the business.

no

Jul 6th 2011 × Lazyloading multiple sequential javascript dependencies in MooTools

We all know and love Asset.js from MooTools-more. It affords you lazyloading by providing Asset.javascript, Asset.image, Asset.images and Asset.css. However, sometimes you need more precision when bringing in external scripts as dependencies.

Hence I created my own Asset.javascripts – based losely on a coupling of Asset.images and Asset.javascript but providing sequential asynchronous loading.

Asset.javascripts = function(sources, options) {
    // load an array of js dependencies and fire events as it walks through
    options = Object.merge({
        onComplete: Function.from,
        onProgress: Function.from
    }, options);
    var counter = 0, todo = sources.length;

    var loadNext = function() {
        if (sources[0])
            source = sources[0];

        Asset.javascript(source, {
            onload: function() {
                counter++;
                options.onProgress.call(this, counter, source);
                sources.erase(source);

                if (counter == todo)
                    options.onComplete.call(this, counter);
                else
                    loadNext();
            }
        });
    };

    loadNext();
};

Eg. usage with Arian’s DatePicker class, which uses multiple files that need to be loaded in their right order:

if (!window.Picker) {
    new Asset.javascripts([
        "/js/mylibs/Locale.en-US.DatePicker.js",
        "/js/mylibs/Picker.js",
        "/js/mylibs/Picker.Attach.js",
        "/js/mylibs/Picker.Date.js"
    ], {
        onComplete: function() {
            new Asset.css("/js/mylibs/datepicker.css");
            new Asset.css("/js/mylibs/datepicker_dashboard/datepicker_dashboard.css");

            doDates();
        }
    });
}
else {
    doDates();
}

Have fun.


Jul 6th 2011 × MooTools pattern fun: Class Implements + Extends at the same time

Update: Thanks to @CarstenSchwede, who pointed out that the MooTools Class Constructor expects the Extends mutator __before__ the Implements one, meaning you don’t need to worry about any of the stuff I had to come up with (described in this post). Upon further investigation with Arian, it turns out that MooTools 2.0 will NOT be dependent on order of Extends and Implements declarations in classes, thanks to this change by Kamicane.

The neverending debacle of Extends vs Implements, which one to use and how to use them together – has been a source of discomfort for me in MooTools for a while so I thought I’d write up parts of my experiences with it in the hope it may help somebody else.

I came to have a need to write a class that serves as my new mixin and brings a new method ‘kill‘ – (say, Class ninja) to another class (Class badass) that extends Class human. Pretty crazy, right?

The problem is, the pattern of:

var ninja = new Class({
    kill: function() {
        alert("kill!");
    }
});

var human = new Class({
    initialize: function(){
        alert("i r human!");
    }
});

var badass = new Class({
    Implements: [ninja],
    Extends: human,
    initialize: function() {
        alert("i r badass and.. ");
        this.parent();
        this.kill();
    }
});

new badass(); // i r badass, i r human, this.kill is not a function exception.

… simply does not work. The Extend here means the human prototype is the base and it lacks the kill method. Wut?

The main practical difference in subclassing approaches is that the `Implements` (mixin) does not instantiate the subclass whereas `Extends` does, so there can be only one class that is extended whereas implemented ones just copy the methods from the prototypes. How to get around being able to extend a single class only? You need class human to implement ninja instead and class badass to simply extend human. Aside from the side-effect of humans getting a new kill method (which they may or may not know about), it will mean that badass will be able to use .kill as well as call upon his direct parent human.

The whole point is, you may not always be at liberty to rewrite / refactor classes the way you want them without creating complications with other parts of your web app. You could also be be extending a Mootools native class like Request.JSONP and then decide to mixin a new storage class into your extended one (true story!)…

An interesting pattern (or rather, the only pattern I have found to work… ) to overcome this goes something like this:

var ninja = new Class({
    kill: function() {
        alert("kill!");
    }
})

var human = new Class({
    initialize: function(){
        alert("i r human!");
    }
});

human.implement(new ninja);

var badass = new Class({
    Extends: human,
    initialize: function() {
        alert("i r badass and.. ");
        this.parent();
        this.kill();
    }
});

new badass(); // this.kill works.

You could even write this as:

Extends: human.implement(new ninja),

Obviously, you can simply modiy the prototype of the parent class and do:

human.implement({
    kill: function() {
        alert("kills!");
    }
});

But this means the code you already have in ninja needs to be duplicated and this will go for all methods or properties you want to gain access to.

A practical example with Request.JSONP and an example caching class, created to allow use of localStorage. Why would you want to do that? Well, having a class that can allow you to cache replies from Request or Request.JSONP or anything at all is handy. And doing things that fetch non-volatile data through a rate-limited API is expensive, you are encouraged to cache. In other words, if you read a particular user’s Twitter profile / timeline, you should not have to request it again on a reload within the session. Same applies if you are expanding tiny URLs like bit.ly – the URL won’t change for any given hash so there’s no point in continuously fetching it.

In the following example, we cache the response for a user profile JSONP request via the Twitter API:

View the full fiddle here: http://jsfiddle.net/dimitar/AjP5A/.

For a real detailed explanation of Extends vs Implements in MooTools, grab a copy of Pro Javascript with MooTools by keeto.


May 13th 2011 × mootools flickr api class via Request.JSONP

updated for mootools 1.3.2

I needed to bring some images into a thumbnail/gallery and decided to use flickr’s API for easy access. The result is a mini-api which allows you to control your options and parse the images that flickr sends back.

// the class
Request.flickr = new Class({
    Extends: Request.JSONP,
    options: {
        callbackKey: "jsoncallback",
        url: "http://www.flickr.com/services/rest/?",
        log: true
    },
    initialize: function(params, options) {
        this.parent(options);
        this.options.url = this.options.url + Object.toQueryString(params);
    },
    success: function(data, script) {
        this.parent(data, script);
    },
    imageURL: function(obj) {
        return "http://farm{farm}.static.flickr.com/{server}/{id}_{secret}.jpg".substitute(obj);
    }
});

// how to use
new Request.flickr({
    format: 'json',
    api_key: "e7df6c74d2545f55414423463bf99723", // your api here
    per_page: 4,
    tags: "mountains",
    method: "flickr.photos.search"
}, {
    onSuccess: function(data) {
        target = $("action");
        var self = this;
        data.photos.photo.each(function(el) {
            new Asset.image(self.imageURL(el), {
                onload: function() {
                    this.inject(target);
                }
           });
        });
    }
}).send();

Want to see it in action? Here’s an embedded jsfiddle:



May 12th 2011 × CKeditor blues: when it fails to pass on the data via AJAX

CKeditor is a good WYSIWYG content editor and is very popular in various CMS and on-page editing tools. It _tends_ to work and is helpful to those who cannot use HTML natively.

However, from a developer standpoint – it can cause some headaches and it lacks proper API (or otherwise documentation). All you get is a brief reference and you can explore the prototypes and guess.

The problems start when you have a form that you handle through AJAX (XHR) that contains CKEDITOR instances for textareas. Intermittently, the submitted data would fail to update the database without any apparent reason.

After some digging, I came to write a fix (through MooTools 1.3) that is incorporated at the form handler prior to the AJAX call. The idea is simple: find any CKEDITOR instances, retrieve them, get the formatted HTML data out and set it as the value of the original textarea element so that the form will save correctly.

document.id("myform").addEvent("submit", function(e) {
    e.stop();
    // find instances, loop through them
    Object.each(CKEDITOR.instances, function(instance, key) {
        // find a form element that has the same id or name attribute
        var el = document.id(key) || document.getElement("name=[" + key + "]");
        if (el) {
            // set matching original element's value to data
            el.set("value", instance.getData());
        }
    });

    // continue with form processing now.
});

I hope it helps somebody as it has been a nuisance for me for a while.


May 10th 2011 × Just a quick heads-up: updated site live header to new sprite animation

It’s been an year since I last touched on the live header malarkey and though the old one was OK, it was more to do with playing with the idea and developing a basic parallax effect in javascript. Oh, and learning more MooTools.

The new one is a complete (or near enough) rewrite of the lemming class. Each lemming is a simple referenced object by the instance, with its own properties and controllable by the instance. The array index of each lemming is the key to a number of pre-defined methods that can help do the storyboard example (along with events the instance or the lemmings fire).

You can view the source and play with them here on jsfiddle: http://jsfiddle.net/dimitar/bYtLz/. The storyboarding was a bit messy but the code is fairly simple. Change var letters = [] to spell something else. Have fun!