Giter Site home page Giter Site logo

messageresource.js's Introduction

#messageResource.js Join the chat at https://gitter.im/suhaibkhan/messageResource.js Built with Grunt

messageResource.js is a simple JavaScript library for reading message resource property files of following format.

#example.properties

home.title = My Tile
home.welcome = Welcome Message
description = This is a brief description message.

##Basic Usage Clik here to download compressed version of messageResource.js.
OR
Clik here to download uncompressed version of messageResource.js. ####HTML

<!-- Include messageResource.min.js in the html -->
<script src="messageResource.min.js"></script>

####JavaScript

// initialize messageResource.js with settings
messageResource.init({
  // path to directory containing message resource files(.properties files),
  // give empty string or discard this configuration if files are in the
  // same directory as that of html file.
  filePath : 'path/messageresource/'
});

// will load the file 'path/messageresource/moduleName.properties'
// and callbackFunction will be executed when loading is complete.
messageResource.load('moduleName', callbackFunction); 
// file name without extension is taken as module name.

// use messageResource.get function to get values from loaded file. 
var value = messageResource.get('sample.key', 'moduleName');

###Loading files with locale. You can also specify locale while loading a file.

// will load the file moduleName_fr_FR.properties.
messageResource.load('moduleName', callbackFunction, 'fr_FR');

// get value based on locale from moduleName_fr_FR.properties.
var value = messageResource.get('sample.key', 'moduleName', 'fr_FR');

###Specifying current locale. You can specify the current locale to remove locale argument from further function calls.

// set current locale
messageResource.setCurrentLocale('fr_FR');

// will load the file moduleName_fr_FR.properties.
messageResource.load('moduleName', callbackFunction);

// get value from file moduleName_fr_FR.properties.
var value = messageResource.get('sample.key', 'moduleName');

If current locale is not set, then default locale which is en_US will be taken can as the current locale. You can change the default locale from en_US to another locale.

// initialize messageResource.js with defaultLocale in settings
messageResource.init({
  filePath : 'path/messageresource/',
  defaultLocale : 'en_GB'
});

Locale in the file name is not necessary for message resource file corresponding to default locale.

// initialize messageResource.js
messageResource.init({
  filePath : 'path/messageresource/',
  defaultLocale : 'en_GB'
});

// will load moduleName.properties and data will be saved.
// corrsponding to defaultLocale en_GB
messageResource.load('moduleName', callbackFunction);

// both value and valueWithLocale will be same.
var value = messageResource.get('sample.key', 'moduleName');
var valueWithLocale = messageResource.get('sample.key', 'moduleName', 'en_GB');

// set current locale 
messageResource.setCurrentLocale('fr_FR');

// since current locale and default locale are different, the 
// below statement will load the file moduleName_fr_FR.properties.
messageResource.load('moduleName', callbackFunction);

###Specifying different file extension. By default the expected file extension for message resource files is .properties. You can change this default extension using the following configuration while initializing messageResource.js.

// initialize messageResource.js
messageResource.init({
  filePath : 'path/messageresource/',
  fileExtension : 'txt' // changes file extension to .txt
});

Building messageResource.js

  1. Ensure that Node.js is installed.
  2. Run the following command to install Grunt's command line interface (CLI) globally, which adds grunt command in your system path.
    npm install -g grunt-cli
    
  3. Change to the project's root directory.
  4. Ensure that package.json and Gruntfile.js are in project's root directory.
  5. Install project dependencies with the following command.
    npm install
    
  6. Run Grunt with the following command, which builds and places messageResource.js and messageResource.min.js in the dist directory.
    grunt
    

API

messageResource

messageResource variable is added to the global scope.


messageResource.init([config])

Initialize messageResource.js with configuration options.

Parameters

config Object : Object with configuration options.

Available configuration options

filePath String : Path(directory) containing message resource files to be loaded. Default value is empty string and it points to the same path as that of html file.
fileExtension String : File extension of message resource files. Default value is .properties.
defaultLocale String : Default locale to be used. Default value is en_US.
fileNameResolver Function : Specify custom file name resolver. Default file name resolver will be used if not specified.
ajaxFunction Function : Specify custom ajax function for loading files. The function should accept only 2 arguments, url/path of the file and callback with response text as argument. Default ajax function will be used if not specified.
debugMode Boolean : Enable or disable debug mode. Default value is false.


messageResource.setCurrentLocale(locale)

Set current locale to be used. This configured locale will be used by load and get functions if locale not specified. If current locale is not set then default locale will be used as current locale.

Parameters

locale String : Locale identifier like en_US.


messageResource.load([module], [locale], [callback])

Loads a message resource file. The file name is constructed based on the given module name and locale. File name is constructed with default configuration in different cases as follows :

  • case 1 : Module name and locale empty or null, then the file name will be _default.properties.
  • case 2 : Module name Home and locale empty, then file name will be Home.properties.
  • case 3 : Module name empty and locale en_US, then file name will be _default_en_US.properties.
  • case 4 : Module name Home and locale en_US, then file name will be Home_en_US.properties.
Parameters

module String | Array : Module name or list of module names to be loaded. By Default it loads module with name _default.
locale String : Locale identifier like en_US. Current locale will be used as default.
callback Function : Callback to be executed after loading message resource.


messageResource.get(key, [module], [locale], [defaultValue])

Get value of a property from loaded message resource files.

Parameters

key String : Message resource property key.
module String : Module name. Default value is _default.
locale String : Locale identifier like en_US. Current locale will be used as default.
defaultValue String : Default value to return if entry corresponding to the given key not found. By default the given key will be used as default value.

Returns

String : Message resource property value corresponding to the key. If entry doesn't exist, then default value will be returned.


Copyright

Copyright 2014 Suhaib Khan. See MIT-LICENCE for details.

messageresource.js's People

Contributors

suhaibkhan avatar hankhero avatar gitter-badger avatar

Stargazers

 avatar José Flávio Dias avatar Gab Stehr avatar  avatar ishida avatar Ryan McQuen avatar  avatar Steve McLeod avatar Martin Desharnais avatar Marcio Alves avatar Mathieu KOMMER avatar  avatar Alejandro Dominichini avatar Giles Winstanley avatar Sean avatar Alexander Petrichkovich avatar Nicolay Ramm avatar HP avatar  avatar Christian Castelli avatar  avatar Eric Bailey avatar

Watchers

James Cloos avatar  avatar  avatar Daniele Alessandro avatar

messageresource.js's Issues

Coherence between load and get

I'm not a Javascript developper, so maybe i don't understood the behavior...

You have written for load function :
"case 2 : Module name Home and locale empty, then file name will be Home.properties."
which is the case if i try to load an "application.properties".

However, if i try to get a key without specify a locale, the script will use the default locale to search in properties file. So the result will be the key and not the value.

Is it an error or a bad use of my part ?

Problem with Internet Explorer 8

Hi there,
I used messageResource in a project and I recently found out that it doesn't work in Internet Explorer 8. I also found where the problem is:
in the init method square bracket are used to read a character in a particular position inside a string.
Old versions of IE don't support this syntax. The correct way to do that should be the charAt method of strings:
http://www.w3schools.com/jsref/jsref_charAt.asp

The code for init method should be changed in this way:

            init : function(config){

                config = config || {};

                // append '/' to file path if not exists
                filePath = config.filePath || '';
                if (filePath && filePath.charAt(filePath.length - 1) !== '/'){
                    filePath = filePath + '/';
                }

                // prepend '.' to file extension if not exists
                fileExtension = config.fileExtension || DEFAULT_EXTENSION;
                if (fileExtension.charAt(0) !== '.'){
                    fileExtension = '.' + fileExtension;
                }

                // configure default locale
                config.defaultLocale = getValidLocale(config.defaultLocale);
                defaultLocale = config.defaultLocale;
                currentLocale = config.defaultLocale;

                // configure file name resolver
                fileNameResolver = config.fileNameResolver || defaultFileNameResolver;

                // custom ajax function
                ajaxFunction = config.ajaxFunction || ajaxGet;

                // enable or disable debug mode
                debugMode = config.debugMode || false;

                // all configurations are valid
                validConfiguration = true;
            },

Loading as file://path/messages.properties in Google Chrome

I'm working on html5 app that works as file:///path/index.html.
When I try to load file://path/messages.properties in Google Chrome I get next error:
XMLHttpRequest cannot load file:///path/messages.properties. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Query

please explain what is 'callbackFunction' which need to be passed in messageResource.load function

Locale (e.g. es_ES) should fall back to parent locale (e.g. es) when child locale not found

[ more context: http://stackoverflow.com/questions/5047298/detecting-browser-locales-languages-and-generating-output ]

Summary of the problem: a user's browser presents a locale which site translations are not available for, and a more appropriate locale than the default is available without their specific e.g. dialect. In other words, if a user comes with locale set to es_ES and we only have es_MX and es, es should be served instead of the default locale.

I was wondering what the best way to implement this would be. I was thinking that it could be if the ajax fails, put some logic in to try the file name with the underscore and everything after removed, but I was also thinking about how to then name that locale appropriately within the messageResource.js API.

Problem with Global Vars and callBackFunction

Hi there,

I've got your service working nicely except...it won't do what I want it too...

my code is simple enough and is shown below:

Summary

Global Vars
messageResource.init
messageResource.load //get two messages into global vars
open a popup using global vars

The code works and the messages are loaded in messageResource.load and can be seen in console.log

BUT when i try to use the global vars in the popup they are empty!!! So why is this happening?

Then I thought, OK I will try moving the popup code to /* 1 */

but then I get a message ...

Uncaught TypeError: Cannot read property 'document' of undefined

How can I use your routine to accomplish what I want, it seems ideal but...

I've also move the callBackFunction from inline to where the popup code is but I don't understand these things.

I assume this is my problem...but how do I get it too work???

Many thanks and best regards
Seán

var propertiesFileName = "propertiesFILE";
var myCompanyDingBatDesc;
var myCompanyDingBatPurp;

function dirtypopup03(DingBat) {

    var module = "dirtypopup03 ";
    var debug = true;

    if (debug == true) { console.log(module + "v01.01"); }
    if (debug == true) { console.log(module + "Arriving"); }

    // initialize messageResource.js with settings
    messageResource.init({
        // path to directory containing message resource files(.properties files),
        // give empty string or discard this configuration if files are in the same directory as that of html file.
        filePath: '../../myCompany/properties'
    });
    console.log(module + "After filePath");

    // will load the file 'path/messageresource/moduleName.properties'
    // and callbackFunction will be executed when loading is complete.

    messageResource.load(propertiesFileName, function () {

        // load file callback 
        // get value corresponding  to a key from config.properties  

        if (debug == true) { console.log(module + "Before Getting Key"); }
        myCompanyTxt = messageResource.get('sample.key', propertiesFileName);
        if (debug == true) { console.log(module + "myCompanyTxt = " + myCompanyTxt); }
        if (debug == true) { console.log(module + "After Getting Key"); }

        if (debug == true) { console.log(module + "Before Getting My Keys"); }
        var DingBatDesc = 'myCompany.' + DingBat + 'DingBat-003';
        var DingBatPurp = 'myCompany.' + DingBat + 'DingBat-004';

        if (debug == true) { console.log(module + DingBatDesc); }
        if (debug == true) { console.log(module + DingBatPurp); }

        if (debug == true) { console.log(module + "After Setting My Keys"); }

        myCompanyDingBatDesc = messageResource.get(DingBatDesc, propertiesFileName);
        myCompanyDingBatPurp = messageResource.get(DingBatPurp, propertiesFileName);

        if (debug == true) { console.log(module + "myCompanyDingBatDesc = " + myCompanyDingBatDesc); }
        if (debug == true) { console.log(module + "myCompanyDingBatPurp = " + myCompanyDingBatPurp); }
        if (debug == true) { console.log(module + "After Getting My Keys"); }

        if (debug == true) { console.log(module + "Leaving"); }

/* 1 */

    });

// popup code
    var generator = window.open('', DingBat, 'height=700,width=500');

    generator.document.write('<html><head><title>DingBat Details</title>');
    generator.document.write('<link rel="stylesheet" href="style.css">');
    generator.document.write('</head><body>');
    generator.document.write('<p></p>');
    generator.document.write('<p><b>' + 'DingBat:</b> ' + DingBat + '</p>');
    generator.document.write('<p><b>' + 'DingBat Desc:' + '</b></p>');
    generator.document.write('<p>' + myCompanyDingBatDesc + '</p>');
    generator.document.write('<p><b>' + 'DingBat Purp:' + '</b></p>');
    generator.document.write('<p>' + myCompanyDingBatPurp + '</p>');
    generator.document.write('<p>DingBat is ' + DingBat + '</p>');
    generator.document.write('<p><a href="javascript:self.close()">Close</a> this window.</p>');
    generator.document.write('</body></html>');

    generator.document.close();

}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.