Demo - Namespaces

explanation of namespaces

by David McClelland

HTML

<button>Click to Toggle</button>
<p class="noNameSpace">
</p>
<p class="nameSpace">
</p>

JavaScript

//two 'click' events on the button - we'll stop *only* the namespaced 'click' after three runs, so the normal 'click' keeps going
var x=0, count=0;

//this 'click' event has no namespace - we'll let it toggle forever
$('button').on('click', function(){
    if (x==1){
        $('.noNameSpace').html('our .off unbinding method will only target the namespaced click');
        x=0;
    } else {
        $('.noNameSpace').html('just a normal click event, no namespace');
        x=1;
    };
});

//this 'click' event has a namespace 'myNamespace', which we'll unbind once the event has run three times (count hits three)
$('button').on('click.myNamespace', function(){
    //check if count has reached 3
    if (count>=3) {
        $('button').off('click.myNamespace');
    } else {
    //if not yet 3, keep bound and increment 'count' by 1
        // not how the "on" is not required when referenceing a namespaced event
        // so you can switch all associated events on or off at once
    $('.nameSpace').html('you\'ve clicked the namespaced event ' + (++count) + (count==1? ' time' : ' times'));
    }
});