Skip to content Skip to sidebar Skip to footer

Adding To A Function Through Another Javascript File

Hey I was wondering how I could add on to my function draw(); draw is used in my canvas engine to update everything within it. What I want to do is create a standalone engine tha

Solution 1:

I think inheritance is a bit too complex for this... you can achieve all of what you want with just hooks.

Try something like this:

var postDrawHooks = [];
var draw = function(){
    // do stuff
    postDrawHooks.forEach(function(hook){hook()});
}

var playerUpdate = function(){...};
postDrawHooks.push(playerUpdate);

Solution 2:

Basicaly it is a prototype. If you do not wish to complicate yourself with prototypeing you can use a "home made" inheritance:

Function.prototype.method = function(name, func) {
        this.prototype[name] = func;
        returnthis;
    };

  Function.method('inherits', function(parent) {
        var d = {}, p = (this.prototype = newparent());
        this.method('uber', functionuber(name) {
            if(!( name in d)) {
                d[name] = 0;
            }
            var f, r, t = d[name], v = parent.prototype;
            if(t) {
                while(t) {
                    v = v.constructor.prototype;
                    t -= 1;
                }
                f = v[name];
            } else {
                f = p[name];
                if(f == this[name]) {
                    f = v[name];
                }
            }
            d[name] += 1;
            r = f.apply(this, Array.prototype.slice.apply(arguments, [1]));
            d[name] -= 1;
            return r;
        });
        returnthis;
    });

Now for a "class" (there is no such thing in js but this is the correct term ) you can make it inherit another "class" by using myCls.inherits(parentCls)

Solution 3:

is there a reason you couldn't trigger events for these framework actions? that way anything listening for a 'draw' event could just hook their logic in that way? if not actual eventing, something like the hooks suggested by @sudhir jonathan would work, though i would suggest creating a method to register generic hooks, this way you could call something like

game.register('draw',myFunctionReference);

and in game object

register : function (hook,func) {
    registeredHooks.push({'name' : hook, 'callback': func});
}

and in draw:

function draw(){
    gameloop();
    cameraWrapper();
    context2D.clearRect(0,0,canvas.width, canvas.height);
    for (i=0; i < registeredHooks.length; i++) {
        var hook = registeredHooks[i];
        if (hook.name == 'draw') hook.callback();
    }
}

Post a Comment for "Adding To A Function Through Another Javascript File"