Search code examples
javascriptoopstatic-librariesencapsulation

call the function in function of custom library in Javascript


I have a library which looks like the following

(function (bindDropdownAndSetValue) {
    function allFunction() {
        function bindDropDownValue(response, dropdownObject) {
            $.each(response, function (i, e) {
                $('#' + dropdownObject.id).append('<option value=' + e[dropdownObject.value] + '>' + e[dropdownObject.text] + '</option>');
            });
        }

        function dropdownValues(id, value, text) {
            this.id = id;
            this.value = value;
            this.text = text;
        }
    }
    bindDropdownAndSetValue.allFunction = allFunction;
} (bindDropdownAndSetValue));

in the above example when I call bindDropdownAndSetValue.allFunction I want to excess the functions inside allFunction but it didn't appear to work

and when I changed the library to like the following

(function (bindDropdownAndSetValue) {
    function bindDropDownValue(response, dropdownObject) {
        $.each(response, function (i, e) {
            $('#' + dropdownObject.id).append('<option value=' + e[dropdownObject.value] + '>' + e[dropdownObject.text] + '</option>');
        });
    }

    function dropdownValues(id, value, text) {
        this.id = id;
        this.value = value;
        this.text = text;
    }
    bindDropdownAndSetValue.bindDropDownValue = bindDropDownValue;
    bindDropdownAndSetValue.dropdownValues = dropdownValues;
} (bindDropdownAndSetValue));

this works fine, but the problem here is that I need to right extra line of code, to assign function one by one to bindDropdownAndSetValue.

Is there any other better way to right this code?


Solution

  • Keep it short and simple:

    bindDropdownAndSetValue.bindDropDownValue = function(response, dropdownObject) {
        $.each(response, function (i, e) {
            $('#' + dropdownObject.id).append('<option value=' + e[dropdownObject.value] + '>' + e[dropdownObject.text] + '</option>');
        });
    };
    bindDropdownAndSetValue.dropdownValues = function(id, value, text) {
        this.id = id;
        this.value = value;
        this.text = text;
    };