SimDion
SimDion

Reputation: 1080

requirejs / backbone : declare a global function / variable

Is it possible to declare a global function in a backbone / marionnette app, that calls a precise module's function?

This question may sound weird since I personally would suggest not to do this at all, because using modules is awesome and keep app structure clean. I need a global function because there is a module / function that I use everywhere, in all single view / template of my app. The function is lang.item(). For example:

lang.item(ID, p1, p2, p3, ... )

I use this everywhere, with a module I called "lang". Example :

define([ 'backbone', 'lang'], function(Backbone, lang){
   return Backbone.View.extend({
       ...
       template: _.template('<%= lang.item("welcome") %> <%=username%>'),
       onError: function(){
            this.ui.error.html(lang.item('wrong_login'));
       }
       ...
   });
});

I always have to include the "lang" module so I can use it. Since I call it and use it everywhere, I would love to use a simple global function like lang(ITEM_ID), anywhere, when I need it, without having to include the "lang" module everytime.

define(['Backbone'], function(Backbone){
   return Backbone.View.extend({
       ...
       template: _.template('<%= lang("welcome") %> <%=username%>'),
       onError: function(){
            this.ui.error.html(lang('wrong_login'));
       }
       ...
   });
});

Someone have a solution?

Upvotes: 0

Views: 227

Answers (1)

mvpasarel
mvpasarel

Reputation: 785

I suggest using this in your main javascript file, used by requireJS:

define('init', function (require) {
    ...
    window.lang = require('lang');
    ...
});

// Initialize the application.
require(['init']);

Personally, I do not find this offensive to any coding standards. Let me know if it worked.

Upvotes: 1

Related Questions