Closure property on event

Issue calling a closure property via jQuery event

by rob Davis

HTML

<input type="button" id="btn1" value="button 1"/><br />
<input type="button" id="btn2" value="button 2"/><br />
Button 1 attempts to immediately execute a callback, generating a popup.<br />
Button 2 will start a timer that will call a function 10 times and then execute a callback, generating a popup.<br />
Note in the code the use of <span>this</span> to define the internal method, <span>this</span> to refer to the private method when exposing it as a public method and the <span>with(this){}</span> syntax around the timer setup that calls the public method.

CSS

span {color:blue;}

JavaScript

// my namespace
var MYNS = MYNS || {};

// my closure 
MYNS.myClosure = (function(){
    var i=10;
    var message = 'unset';
    var callback = null; 
    var handle;
    
    // IMPORTANT 'this' notation
    this.kick = function() {
        console.log('kick called');
        if (i===10) {
            console.log('kick setting interval');
            // IMPORTANT with(this) syntax
            // IMPORTANT Public method being called 'Kick' 
            with(this) {handle = setInterval(function(){Kick();},100)};
        }
        i--;
        if (i<0) {
            console.log('kick ending');
            clearInterval(handle);
            if (this.Callback) {
                console.log('kick attempting callback');
                this.Callback('Interval based callback :'+this.Message);
                i=10;
            }    
        }
    }
    var test = function() {
        if (this.Callback) {
            this.Callback('Direct callback :'+this.Message);
        }
    };
    
    // IMPORTANT private method is exposed via 'this' notation
    return {
        Kick:this.kick,
        Test:test,
        Callback:callback
    };
});

var instance = MYNS.myClosure();
instance.Callback=alertMessage;
instance.Message = 'set';

$('#btn1').click(function() {
    instance.Test();
});

$('#btn2').click(function() {
    instance.Kick();
});

function alertMessage(message) {
    alert(message);
}