Follow me: @D_mitar

Most read posts recently



Jan 12th 2012 × A larger MooTools logo

I had to look around and find an up-to date mootools logo of a decent size and I couldn’t find one. Hence, I took an old and small AI file and updated it to the current colours, ending up with the logo at 25cm and 300 DPI!

Whereas I won’t post this size here (see note below), I rendered a smaller version to an alpha PNG. Hope it helps someone to create great MooTools inspired fan art, wallpapers or whatever.

mootools logo - large

**note: apparently, use of the MooTools logo is under the strict control of Valerio Proietti, aka Kamicane. I am not going to post any high res logo and if you end up using this one, you really ought to ask for his permission.**


Dec 25th 2011 × substitutePath – a string method that recursively replaces values from an object

Originally, this was meant to be released as something for String.Extras in mootools-more as an idea by Oskar, coined by myself with input from csuwldcat – but it seems that the pull request is not going anywhere so I will release it here instead.

The idea is to extend the behaviour of String.substitute to be able to work with deep properties of the object that is being passed on, which means easier templating without having to flatten objects beforehand so the properties of interest are on the same level.

View on github as per pull request

String.implement({
    substitutePath: function(object, regexp) {
        return String(this).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name) {
            if (match.charAt(0) == '\\') return match.slice(1);
            if (object[name] != null) return object[name];

            var retStr = "",
                path = name.split('.'),
                length = path.length,
                sub = object;

            if (length <= 1)
                return retStr;

            for (var i = 0; i < length; i++) {
                if((sub = sub[path[i]]) == null) return retStr;
            }
            return sub;
        });
    }
});

The use goes like this:

var foo = "this is a bar called \"{lame.bar.name.here}\"";
var objOK = {
    lame: {
        bar: {
            name: {
                here: 0
            }
        }
    }
};

var objFail = {
    lame: {
        bar: {
            lame: {
                here: "hello"
            }
        }
    }
};

console.log(foo.substitutePath(objOK)); // works
console.log(foo.substitutePath(objFail)); // should fail
console.log(foo.substitutePath({foo:"bar"})); // should fail
console.log("this is a {bar}".substitutePath({bar:"success"})); // should work (legacy as .substitute);

Here's the jsfiddle you can play with: http://jsfiddle.net/dimitar/RtBMm/

Please note that the above will only deal with non-primitives (numbers, strings) and will fail if the key matches a function or an object. To address that, I have made a change in the jsfiddle (still being tested) that deals with it in a reasonable way here: http://jsfiddle.net/dimitar/RtBMm/6/ - though calling the function with the scope of the object and w/o parameters may not be ideal, it should cover a large percentage of cases. For any other types, I guess it will do a .toString() anyway.


Dec 24th 2011 × New mootools plugins released on github/forge

Time to wrap up the year, I think. I released 2 more small plugins of mine on github and the MooTools forge.

mooTagify
GitGub project page: https://github.com/DimitarChristoff/mooTagify
Forge link: http://mootools.net/forge/p/mootagify

A plugin for small tag lists input. Also, provides an ajax auto-completion sub-class that can be used as a standalone anyway.

Screenshot:

Example with ajax tag completion: http://fragged.org/mooTagify/Demo/
The plugin is quite easy to setup and you can style it via CSS only or via the many options available to the 2 classes that run it.

Modal.BootStrap
GitGub project page: https://github.com/DimitarChristoff/Modal
Forge link: hhttp://mootools.net/forge/p/modal_bootstrap

This is a combination of several things: the flexible modal markup experiment by @csuwldcat (Daniel Buchner from Mozila), implemented in the Modal.Base class and the Modal.BootStrap class.

The BootStrpa itself (not to be confused with Twitter’s BootStrap) provides a flexible implementation of content in the Modal window through HTML5 element mark-up only, including support for ajax links, grabbing content from elements on the page or setting pure text, even image support (pseudo-lightbox). It also works with location.hash so you can have page.html#terms_and_conditions as a link, if there’s a matching element managed by the BootStrap instance on the page.html, it will open it automatically for you. The modal will ALWAYS stay in the middle of the screen, it has support for responsive design with minimum width and max width as well as support for CSS3 transitions over js morphing of style properties (if available). Very useful for things like terms and conditions, privacy policies, quick contact forms, questionnaires and so forth. It also has support for buttons in the footer with custom events fired in the instance, so its flexible for scripting.

Screenshot:

Example with location.hash: http://www.fragged.org/dev/Modal/Demo/#interview2

Merry Christmas, everyone and a Happy New Year – unless I release anything in-between.


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.