0

let's say I have javascript class.

function myClass(){

    function someProcess(){
        listeners.init();
    }

    var listeners = {
        init: function(){},
        message: function(){}
    }

    return {
        on: function( prop ) {
            if ( listeners.hasOwnProperty( prop ) ) {
                return listeners[ prop ];
            }
        }
    }

}

and then someone creates object like so and uses my custom event

var c = new myClass();
c.on('init', function(){
    console.log('init executed');
});

now i want to execute init from my someProcess() method(which is in myClass). So idea is that register custom events and then trigger them from inside my class.

1

1 Answer 1

1

I found how to do this

function MyClass(){

    //@private
    var isFunction = function(functionToCheck){
        var getType = {};
        return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
    }



    //@private
    var listeners = {
        init: [],
        message: []
    }





    return {
        on: function( evName, callback ) {
            if ( listeners.hasOwnProperty( evName ) && isFunction(callback) ) {
                listeners[evName].push(callback);
            }
        },
        fireEvent: function(evName){
            if ( listeners.hasOwnProperty( evName )) {
                for(var i in listeners[evName]){
                    listeners[evName][i]();
                }
            }
        }
    }



}



var a = new MyClass();
a.on('init', function(a){
    console.log('a_1 inited')
})

a.on('init', function(){
    console.log('a_2 inited')
})



var b = new MyClass();
b.on('init', function(){
    console.log('b_1 inited')
})

a.fireEvent('init');
b.fireEvent('init');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.