bredom
9/9/2018 - 10:01 PM

JavaScript Library Example

Example of a JavaScript Library e.g. jQuery

var g = G$('John', 'Doe', 'en');
g.greet().setLang('es').greet(true);

$('#login').click(function(){
    var loginGrtr = G$('John', 'Smith');

    $('#logindiv').hide();

    loginGrtr.setLang($('#lang').val()).HTMLGreeting('#greeting', true).log();
});
(function(global, $) {

    var Greetr = function(firstname, lastName, language){
        return new Greetr.init(firstname, lastName, language);
    }
    
    var supportedLanguages = ['en', 'es'];

    var greetings = {
        en: 'Hello',
        es: 'Hola'
    }

    var formalGreetings = {
        en: 'Greetings',
        es: 'Solados'
    }

    Greetr.prototype = {

        fullName: function(){
            return this.firstName + ' ' + this.lastName;
        },

        validate: function(){
            if (supportedLanguages.indexOf(this.language) === -1) {
                throw "Invalid language";
            }
        },

        greeting: function(){
            return greetings[this.language] + ' ' + this.firstName
        },

        formalGreeting: function(){
            return formalGreetings[this.language] + ' ' + this.fullName()
        },

        greet: function(formal){
            var msg;

            if (formal) {
                msg = this.formalGreeting();
            }
            else {
                msg = this.greeting()
            }

            console.log(msg);

            return this;
        },

        log: function(){
            if (console) {
                console.log(this.language + ': ' + this.fullName());
            }
            return this;
        },

        setLang: function(lang){
            this.language = lang;

            this.validate();

            return this;
        },

        HTMLGreeting: function(selector, formal){
            if (!$) {
                throw "jQuery not loaded";
            }

            if (!selector) {
                throw "Missing selector";
            }

            var msg;
            if (formal) {
                msg = this.formalGreeting();
            }
            else {
                msg = this.greeting()
            }

            $(selector).html(msg);

            return this;
        }

    };

    Greetr.init = function(firstName, lastName, language){

        var self = this;
        self.firstName = firstName || '';
        self.lastName = lastName || '';
        self.language = language || 'en';

        self.validate();
    }

    Greetr.init.prototype = Greetr.prototype;

    global.Greetr = global.G$ = Greetr;

})(window, jQuery);