Follow me: @D_mitar

Most read posts recently



Apr 27th 2012 × StrongPass: A password strength helper class

Good news, everyone (I miss Futurama).

Three years ago I wrote a mootools plugin for password strength checking, based upon a stack overflow jquery post. I just had cause to revisit this for work at QMetric and refactored it (read, rewrote from scratch) for MooTools 1.4+

The Class is on the forge, it’s fairly flexible and can either be styled to use the default strength indicator or to output whatever you like based upon pass/fail events and scores.

You can check it out here: http://mootools.net/forge/p/strongpass or if you prefer, head to the GitHub repo directly here instead: https://github.com/DimitarChristoff/StrongPass

Links to demos are in the README.md as well as a basic buster.js test suite. Use responsibly!


Mar 23rd 2012 × mailcheck for mootools: suggestive email auto correction

Every now and then, a plugin comes about that has a good idea. Recently, this has been the mailcheck jquery plugin by Kicksend. According to their claims, it has reduced typos in emails during user signups by over 50%.

The plugin works by comparing the domain typed vs a list of pre-configured popular TLDs for email, such as gmail.com, hotmail.com and so forth – and providing recommendations based upon string similarity. As a result, typing ‘foo@gnail.com’ ought to offer a suggestion ‘Did you mean foo@gmail.com?’

We decided to implement it at work and I sat down to convert it to mootools. Regretfully, none of the code of the original plugin remains, including the string distance algo ‘sift3′, which proved inaccurate and failing in IE7.

The result? A brand-spanking-new mootools.mailcheck.js (on github) for your pleasure (specific github project pages here

The mootools version now features a few improvements over the original, namely:

  • choice of method for determining string distance between Levenstein (the default choice) and sift3
  • more performant
  • look-up cache – any strings compared that return a match are cached
  • shared cache – any new instances created will benefit from old lookups, useful for use in single page applications
  • automated testing via buster.js – all included with a kick start guide.

Visit the repo and give it a go, it’s a solid idea now. I have even included a jsfiddle demo and it comes with little mysql query that will grab the most popular email domains from your existing user database so you can set it up to suit your own target audience.

View a video of CI auto testing via buster.js on this plugin:

no

Feb 13th 2012 × MooTools plugins round-up

Time for a round-up of interesting / quality plugins on the MooTools forge or github. Again.

First off, my favourite find over the last month has to be the MooTools Router. What it does is handle application paths for hashes in the style of the Backbone.js router but it’s really a normal MooTools class. It can tackle dynamic parameters rather well and raises some warnings / events you can work with. For example:

BO.Router = Router.implement({
    // routes definition
    routes: {
        '#!customer/:id/'           : 'loadCustomer',
        '#!customer/:id/cancel/'    : 'cancelCustomer',
    },

    // router init
    init: function(){
        console.log('init')
    },

    loadCustomer: function() {
        console.log("loading customer with id " + this.param.id);

        BO.user.model.set({
            id: this.param.id
        });

        BO.user.model.on("change", function() {
            BO.user.view.render();
        });

        BO.user.model.fetch({
            success: function() {
                BO.user.model.off("change");
                BO.user.model.trigger("fetch");
            }
        });

    }
});

Second. Twipsy – It’s a port of the Twitter Bootstrap Twipsy tooltip plugin (now renamed in BootStrap 2.0 to bootstrap-tooltip.js). Rather nice and just works. Also, extendible so you can implement the boostrap-popover.js through it.

Third. A plugin by yours truly and Arian from mootools-core – it’s scrollspy. That’s not David Walsh’ scrollspy, it’s a port of the Twitter Bootstrap scrollspy instead. It allows you to react to elements of interest that come into view and do things to them or your nav items that are somehow related.

Fourth. “MooStrap offers the initialization function of large-scale application from middle-scale. Every one initialization processing is performed and it secures that initialization of application is ensured.” – well, perhaps english is not their strong part but if you can get past things like ‘paturn’, it does provide a nice platform to build on.

Last but not least. Composer.js is a nice alternative to Backbone.js in MooTools. It is early days but it’s looking promising for the lyonbros plugin. There are some differences in terms of approaches vs Backbone or Spine but it gets the job done. Only downside is, not mature enough and lack of tests supplied make it difficult to build on it and contribute. Hopefully, easily fixed.


Feb 8th 2012 × Manage lazy-loading handlebars / mustache / other templates via MooTools

I have started using Backbone.js but with handlebars templates (like in Ember.js) that I parse through Underscore.js. Anyway, to cut a long story short – I did not want to have a bunch of flat script tags with HTML in the document body on page load so I thought of a way to lazyload and bring the templates from an external repository.

The result is Asset.templates – written in the style of MooTools more’s Asset.images/javascript or whatever. The idea is: it uses Request.HTML to fetch the template file; it then injects it as a script tag into the document.head; it sets the correct type (text/x-handlebars in the example but it’s an option) and a property that lets you use a selector engine to reference and load it (data-template-name in the example, but it can be anything, including id – if you like).

It loads the files asynchronously and firess onProgress and onComplete events – as well as onFailure. If any template is missing and onFailure fires, it won’t fire the onComplete so you can recover early.

Loading a template a second time will NOT inject a new script tag but will update the existing template instead.

Here’s a gist with the code and an example case:

Full gist here: https://gist.github.com/1768949


Feb 2nd 2012 × Using overloadSetter / overloadGetter to make flexible functions in mootools

This is a really helpful feature of MooTools that a few people know and use. Basically, there is a pair of 2 Function prototypes called ‘overloadGetter‘ and ‘overloadSetter‘. They are very simple in what they can provide. Say, you have a function that is a private property setter in a Class that takes 2 arguments: key & value. After a while, you may get bored having to call it all the time for every property you wish to add or having to write object loops for longer updates.

By defining using the Function decorator overloadSetter, you can – without any code adjustment – make your single key/value pair setter take an object and automatically iterate through the properties for you.

Similarly, by using the decorator overloadGetter, you can pass on multiple properties to retrieve that you are interested in – and it will return a single object with all your properties of interest as key.

Pretty cool?

Here’s a real world example. Let’s say, you are making a MVC Model Class that you’d like to use to deal with data objects and dispatch events.

(function() {

    // private real setter functions, not on prototype, see note on .set
    var _set = function(key, value) {
        // needs to be bound the the instance.
        if (!key || typeof value === undefined)
           return this;

        // no change? return. better rely on _.js _.eq but this is crude and works for primitives.
        if (this._attributes[key] && this._attributes[key] === value)
           return this;

        if (value === null) {
            this._attributes.delete(key); // delete = null.
        }
        else {
            this._attributes[key] = value;
        }
        // fire an event.
        return this.fireEvent("change:" + key, value);
    }.overloadSetter();   

    this.Model = new Class({

        _attributes: {}, // initial private object,

        Implements: [Options, Events],

        initialize: function(data, options) {
            data && typeOf(data) === 'object' && this.set(data);
            this.setOptions(options);
        },

        set: function() {
            // call the real getter. we proxy this because we want
            // a single event after all properties are updated
            _set.apply(this, arguments);
            this.fireEvent("change");
        },

        get: function(key) {
            // and the overload getter
            return (key && typeof this._attributes[key] !== undefined)
                ? this._attributes[key]
                : null;
        }.overloadGetter()

    });

})();

// now make an abstraction of your Model class for users
var User = new Class({

    Extends: Model,

    _attributes: {
        name: "Please enter your name",
        email: "Enter your email address"
    }

});

// initialise your User Model with default data and set some property change events
var user = new User(null, {
    "onChange:email": function(value) {
        // can dispatch to controller/view the change
        console.log("new email now is", value);
    },
    "onChange:name": function(value) {
        console.log("new name now is", value);
    },
    onChange: function() {
        console.log("data has changed!");
    }
});

// let's test this. initial set via single value set:
user.set("email", "dimitar@securemail.com");

// now let's try multiple properties at the same time:
user.set({
    "email": "dimitar@securemail.com",
    "name": "coda"
});

// get the name
console.log(user.get("name")); // coda;

// get multiple properties in a single object
console.log(user.get(["name","email"]));
// Object { name="coda",  email="dimitar@securemail.com"}

View and play with this on http://jsfiddle.net/dimitar/39x7T/

That’s about it. Please note that this Class was only created for the purposes of a demo and is not meant to be used in a real MVC pattern – look at Composer.js (for MooTools), Backbone.js or Ember.js – formerly Sprout Core – if you are interested in doing serious event-based application development.


Feb 2nd 2012 × MooTools in a distant future: how to write to better survive the changes

You may have already heard this, or maybe not. But this won’t change the fact that javascript is changing and the way people write it and specifically, how they write the libraries, modules and widgets we all share and use is slowly being edged towards an AMD pattern. This stands for Asynchronous Module Definition, pioneered by the DOJO framework with a one main goal in mind: being able to define and load any module and its dependencies asynchronously. Whereas it is not a standard yet, it is considered as a step towards the module system proposed in ES Harmony. I also won’t go into any possible shortcomings of this dependency system and the dangers of remote dependencies (bloat), that’s an entirely different topic.

Anyway, with that out of the way, what is the single most important thing to take away from the message that MooTools 2.0 (aka, Milk) will be AMD compliant? In order to become truly modular and compartmentalised into the small parts that have been the building blocks of the framework for years, MooTools is going to stop changing and extending the javascript natives Types’ prototypes. Only then does it guarantee that any of its modules can co-exist with any other AMD module without any conflicts.

When I say ‘stop changing’ natives, it does not mean it won’t ever modify an existing method (Function.bind comes to mind as an example) but in all likelihood, it won’t be doing much of that. You can start to treat bits of it like a microjs library. Even mix-n-match your favourite components from around the web, eg, take Class and use it on top of jQuery (if you really have to!), or bring Sizzle into MooTools instead of Slick with the utility functions of Underscore.js.

Sounds like a win. Now, the unpleasant part. Not being able to modify Element.prototype (for example) means a likely end to code like this:

document.id("someid").addEvent("click", function(e) {
    this.addClass("open");
    var divsWithImages = this.getElements("li").filter(function(el) {
        return !!el.getElement('img');
    });
    // I know you can use a reverse combinator selector for this. not the point.
});

Though the team will probably do a function wrapper like jquery that can allow the above in part, document.id() will stop returning the element itself but will return a function instead. The modified code may look the same but how it’s interpreted will be different. For instance, this.addClass(“open”); won’t work at all. Instead, it will probably need to go through either $(this) / document.id(this) or via the native Type or Slick.

Basically, all Array, Element, String etc methods (see the popular MooTools Types) are still available on the native object instead. You _could_ write the above like so:

Element.addClass($(this), 'open');

The Array / Elements.filter can be called like this:

var divsWithImages = Array.filter(document.id(this).getElements("li"), function(el) }
    return !!document.id(this).getElement("img");
});

Although I honestly have no idea what the new API will really look like, one thing is certain: even as of MooTools version 1.4.3 (time of writing), you can dual use most methods on the host object or through the prototype.

eg,

var strTest = "dimitar was here";
// old way via String.prototype
console.log(strTest.capitalize()); // Dimitar Was Here
// new way, same result.
console.log(String.capitalize(strTest));

It’s a small shift in the way we write code. Since both work already, I would advise you to use the latter one so you have less of a refactor to do if you ever hope to drive your existing code base with the future versions of mootools.

Now, how do you create a String method that will work with both the prototype and the host object? Seems simple. The scope is the host object so, here is a sample rot13 method that can work as both…

(function() {
    var n;
    String.implement({
        rot13: function() {
            return String(this).replace(/[a-z]/gi, function(match) {
                return String.fromCharCode((n = match.charCodeAt() + 13) > 122 || n < 104 && n > 90 ? n - 26 : n);
            });
        }
    });
})();

console.log(strTest.rot13());
console.log(String.rot13(strTest));

I suspect Type.prototype will become protected in the sense that implement will not affect them, making implement behave like Object.extend does at present. If you swapped .implement for .extend in the above code block and then String(this) to String(namedArg), you get a simple and safe-ish native type method.

This is all too similar to how you extend the Object Type (prototyping Object itself has always been a bad idea as everything in javascript inherits from Object):

// extend, not implement.
Object.extend({
    getPropertiesCount: function(object) {
        var props = [],
            hasOwnProperty = this.prototype.hasOwnProperty;
        for (var prop in object) {
            if (hasOwnProperty.call(object, prop))
                props.push(prop);
        }
        return props.length;
    }
});

console.log(Object.getPropertiesCount(this)); // return your global variables count!

I am certain these will not be the only changes but they will certainly be the most difficult to get used to. On the upside, there will be a compatibility layer as usual, including the ability to ‘install’ the prototype methods where possible. Even so, don’t be naive and write code that won’t outlive mootools 1.x without a lot of changes.

In conclusion, things are looking up for MooTools – it is headed in the right direction, even if slowly. My only gripe with this is that we need somebody from the core team to give news of how the release of Milk is coming along every so often. So we can get ready or even help…

*note: parts of this post are based on hearsay and sporadic data from various mootools members over IRC and Twitter. Don’t go writing any books on MooTools 2.0 just yet, you may even have to change the title (cough-Aaron-cough)*


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 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