javascriptfunctionoverridingcraftyjs

Override function in craftyjs


I'm new to JS and trying to override a function in Craftyjs, here is my code:

    Crafty.c('TestA', {
        init: function() {                
            Crafty.addEvent(this, Crafty.stage.elem, "mousedown", this._e_clickListener);
        },
        _e_clickListener: function(e){
            this.foo();
        },
        foo: function() {
            console.log('call A foo');
        }
    });

    Crafty.c('TestB', {
        init: function() {
            this.requires('TestA');                
        },
        foo: function(){
            console.log('call B foo');
        }
    });

    Crafty.e('TestB');

The result when i click on the canvas is:

    call A foo

Is there anyway to turn it into 'call B foo' instead? Thanks.


Solution

  • I'm not really familiar with CraftyJS and the documentation could use a little TLC - unless I've missed something it looks as if calling requires is simply amalgamating everying into a single object - last-in takes precedence. No inheritance so no superclass - just one flat object.

    Perhaps there's a better way but I could only get it to "override" the function by simply assigning it inside the init function after you've imported your required components.

    Crafty.c('TestB', {
        init: function() {
            this.requires('TestA');
            this.foo = function(){
                console.log('call B foo');
            }
        }
    });
    

    jsFiddle