Search code examples
javascriptobjectdecoupling

When two objects are dependent on each other? How to de-couple them?


Bit of a generic question but non the less I am in a situation where I do not know what to do and google has failed me!

I am trying to re-write a grid array collision with canvas that I built.

Now there is a grid object and a block object. The grid cellSize is dependent on being the same size of the block size and vice versa. The reason being is that to work out the grid array to store the blocks into I must first work out how to build it and that is dependent on the size of the block. Example,

var grid = new grid();

function grid() {
    this.cellSize = 50;
    this.cellsX = canvas.width / this.cellSize;
    this.cellsY = canvas.height / this.cellSize;
    this.buildGrid = function() {
        var arr = new Array(this.cellsX);
        for(var i = 0; i < arr.length; ++i) {
            arr[i] = new Array(this.cellsY);
        }
        return arr;
    };
    this.arr = this.buildGrid();
    this.getGridCoords = function(i) {
        return Math.floor(i / this.cellSize);
    };
}

function block() {
    this.size = grid.cellSize; // size of the block is same as cellSize
    this.x = 0;
    this.y = 0 - (this.size * 1.5);
    this.baseVelocity = 1;
    this.velocity = this.baseVelocity;
    this.update = function() {
        this.y += this.velocity;
    };
}

Doing it the way I have done it couples the two objects together and from what I have percieved that is a bad thing. How can I make sure that the two variables are the same size without coupling the objects if that makes sense?


Solution

  • The real issue is that your block() function is taking a value directly from an instance of grid().

    If you want your block() function to be reusable and decoupled, its as easy as changing block() to take the size during construction.

    arr[i] = new block({size: this.cellSize});