How to create data structure in JavaScript?

时间:2015-06-30 13:29:01

标签: javascript html5 architecture include

I am a C# developer that is trying to get his hands on JavaScript as well.

For a data handling program, I want to create a data structure like:

id,
begin,
end,
organiser,
    name,
    city,
    postalcode,
    street,
venue,
    name,
    city,
    postalcode,
    street

Coming from C#, I would create a "class" (gig.js) for the main structure:

function Gig(gig)
{
  this.id = gig.id;
  this.begin = gig.begin;
  this.end = gig.end;
  this.organiser = gig.organiser;
  this.venue = gig.venue;
}

and a "class" (address.js) for organiser and venue:

function Address(a)
{
  this.name = a.name;
  this.city = a.city;
  this.postalcode = a.postalcode;
  this.street = a.street;
}

As I need to refer to the Address-class in the Gig-class, I wanted to reference the address-class in the main class, like

include address.js

I have searched through the web and to my huge surprise, there seems to be no include mechanism at all. HTML5 introduced a way to include JavaScript in another JavaScript, but is seems like no browser is supporting this so far I red some possible solutions here but they all look like hacks for a (from what I expected) simple one line code.

So, how do you do using another JavaScript-File nowadays? Do I need to use an other architectural approach for this? Do I simply include them in the calling html and when I write the code for the main class, I simply hope, that the address class was loaded as well?

Thanks in advance,
Frank

2 个答案:

答案 0 :(得分:2)

简单方法:将类嵌入HTML:

<script src="path/to/address.js"></script>
<script src="path/to/gig.js"></script>
<script>
    // address is loaded before gig (sync loading), and now can use both
</script>

更复杂的依赖关系:一种常见的方法是使用browserify

捆绑模块

编辑: 由于后者似乎是你正在寻找的,这里有一个例子:

的src / gig.js:

// require dependencies
// one of your source files
var Address = require('./src/address');
// npm package dependency as installed by npm i someLib --save-dev
var someLib = require('someLib');

var Gig = function() {
    this.address = new Address();
}
// provide dependency
export.Gig = Gig;

main.js:

var exampleStuff = require('src/Gig');
go();

您可以通过npm安装browserify和其他模块,然后捆绑:

browserify main.js -o dist.js

然后在您的html <script>标记

中加入dist.js

答案 1 :(得分:1)

使用RequireJS。 Requirejs是一个为处理依赖项提供了一个很好的接口的库。有一个很好的教程here。除此之外,你是对的,目前还没有实现的方法来强制JS中的依赖,除了希望使用你的JS文件的人在html中添加了正确的源元素。这就是JavaScript库通常压缩到一个文件的原因。