Question

I have a page that contains a bunch of elements like inputs and select boxes that individually need functions added to them that control their specific behaviour.

My code is currently:

var mpp_ui = {
    itemList : document.getElementById('mpp_itemlist')
};

mpp_ui.itemList.clear = function(){
    while(this.length > 0){
        this.remove(0);
    }
};

Where mpp_ui is used as a namespace that contains all the elements that need functions assigned to them and mpp_ui.itemList is a HTML select element.

If at all possible I want to avoid having to type mpp_ui in every function statement. I would like to declare the functions like this (partially pseudo-code because I don't quite know how to go about it):

var mpp_ui = {
    itemList : {
        DEFINE IT AS document.getElementById('mpp_itemlist').
        Then extend it with functions like so:
        clear : function(){
            while(this.length > 0){
                this.remove(0);
            }
        }
    }
}

Or alternatively, if above isn't possible:

var mpp_ui = {
    itemList : document.getElementById('mpp_itemlist'),
    itemList.clear : function(){
        while(this.length > 0){
            this.remove(0);
        }
    }
}

The last code is the first thing I tried, but it gives me a SyntaxError: Unexpected token . on the line where itemList.clear is defined.

Was it helpful?

Solution

After digging trough many options, the closest I've gotten to my desired format is by declaring the elements in the namespace and then extending them with the desired functions, for which I use underscore.js. The result:

mpp_ui = {
    itemList : document.getElementById('mpp_itemlist')
};
_(mpp_ui.itemList).extend({
    clear : function(){
        while(this.length > 0){
            this.remove(0);
        }
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top