0

In Javascript, there exists a function which inherits the Backbone Model

window.MyModel = Backbone.Model.extend({ .. .. });
window.MyCollection = Backbone.Collection.extend({ .. .. });

In another, JS file we access this function as

var MyModelInstance = new window.MyModel();

Requirement is, all functions needs to be prefixed with specific global namespace (for example, company name 'Google') instead of generic keyword 'window'. How can we achieve it?

I tried the following, but with no success.

var googleNameSpace= defineNamespace("Google");

googleNameSpace.MyModel = Backbone.Model.extend({ .. .. });
googleNameSpace.MyCollection = Backbone.Collection.extend({ .. .. });



var MyModelInstance = new Google.MyModel();
Ravi G
  • 859
  • 1
  • 8
  • 21

2 Answers2

1

in all files add this line at first

window.googleNameSpace = googleNameSpace || {};

update: ok you need google as namespace then have it like this

function defineNamespace(str) {
    window[str] = window[str] || {};
    return window[str];
}



googleNamespace = defineNamespace('Google');

will work now

thecodejack
  • 12,689
  • 10
  • 44
  • 59
  • This looks good. But, what if the Name Space is 'Google.Module1'? – Ravi G Nov 07 '13 at 11:42
  • you may need to write lil bit more code..like split them first and keep checking word by word for the package... – thecodejack Nov 07 '13 at 11:43
  • Its not working.. giving out the error namely 'Uncaught TypeError: Object is not a function:20". At line 20, I am calling var MyModelInstance = new Google.MyModel(); – Ravi G Nov 07 '13 at 12:32
0

you don't need to prefix things with window as this is assumed. you could define

window.myNamespace = Backbone.Model.extend({ .. .. });

and then refer to it only with:

myNameSpace.....

e.g.

window.myModule.helpers = {
    ....
};

can be referenced by:

myModule.helper.{{property/method}}
Adrian Roworth
  • 813
  • 1
  • 7
  • 16