g_m g_m - 1 year ago 47
Javascript Question

Function call from within nested object failing

In the code below I want to make generic functions available through the constructor. The object is for handling calls to an API. But if I call this._isEmpty(obj) from events.POST it always returns false. Placing the body of the _isEmpty() function does give the desired result. How do I solve this?
Any tips on improving this structure are welcome ofcourse.
I looked up some similar questions on SO but the questions/answers I found do not have similar nesting.

I make the following call:

var assystBridge = new global.assystBridge();
response.setStatus(assystBridge.events.POST(request, response));


Object:

var assystBridge = Class.create();
assystBridge.prototype = {
initialize: function() {
// Generic functions go here
function _isEmpty(obj){
// Checks whether an object has properties
// Used for checking whether any data was posted or not
// Returns true or false
return Object.keys(obj).length === 0;
}
},
events: {
POST: function(request, response){
var data = request.body.data;
var responseText = '';
if(this._isEmpty(data)){
//if(Object.keys(data).length === 0){
response.setBody({"response":"NO data was posted", "data": data});
return 400;
} else {
return 201;
}

},
GET: function(request, response){

},
DELETE: function(request, response){

}
},
type: 'assystBridge'
};

Answer Source

If you move the generic function out of the initialize() method and have it be one of the properties of the prototype, then you can reference it via assystBridge.prototype._isEmpty().

For example:

assystBridge.prototype = {
    _isEmpty: function(obj) {
        // Checks whether an object has properties
        // Used for checking whether any data was posted or not
        // Returns true or false
        return Object.keys(obj).length === 0;
    },
    events: {
        POST: function(request, response){
            var data = request.body.data;
            var responseText = '';
            if(assystBridge.prototype._isEmpty(data)){
                response.setBody({"response":"NO data was posted", "data": data});
                return 400;
            } else {
                return 201;
            }

        },
    },
    type: 'assystBridge'
};