Search code examples
javascriptprototype-programming

javascript prototype function gets ignored


I'm having a

"Cannot read property 'bind' of undefined"

issue in my javascript object. How can I force the execution of the binding?

it happens when I call this function:

function ViewportDatasource(mockServer) {
        this.mockServer = mockServer;        
        this.connectionId =this.mockServer.connect(this.eventListener.bind(this));
    }

even if eventListener has been correctly defined in a prototype function

 ViewportDatasource.prototype.eventListener = function (event) {
        switch (event.eventType) {
            case 'rowCountChanged':
                this.onRowCountChanged(event);
                break;
            case 'rowData':
                this.onRowData(event);
                break;
            case 'dataUpdated':
                this.onDataUpdated(event);
                break;
        }
    };

What can I do?

To reply to Daniel's question, the instance gets called here:

 function setRowData($http) {
        // set up a mock server - real code will not do this, it will contact your
        // real server to get what it needs
        var mockServer = new MockServer();
        $http.get('data.json').then(function(response){
            mockServer.init(response.data);
        });

        var viewportDatasource = new ViewportDatasource(mockServer);
        table.api.setViewportDatasource(viewportDatasource);
        // put the 'size cols to fit' into a timeout, so that the scroll is taken into consideration
        setTimeout(function () {
            table.api.sizeColumnsToFit();
        }, 100);
    }

This function gets executed after the ag-grid object in caller is ready


Solution

  • function ViewportDatasource(mockServer) {
        //the this operator here is undefined. function is not of object.
        this.mockServer = mockServer;        
        this.connectionId =this.mockServer.connect(this.eventListener.bind(this));
    }
    

    The this operator should be used only when you are binding the function to an object, in that case the this operator makes sense. In the above example it doesn't.