English 中文(简体)
要求JS:我如何处理浏览器和服务器之间共享代码的不同模块依赖关系?
原标题:RequireJS: how do I handle different module dependencies for code shared between the browser and server?

我在浏览器和服务器上加载了一个需要的 JS 模块, 以实施一些共享功能 。

然而,该模块在每种环境中具有不同的依赖性:

  • In node, it needs the fs module in order to be able to load files
  • In the browser it needs JQuery AJAX or some other AJAX library to be able to fetch those files as HTTP resources.

处理在浏览器和服务器之间共享但每个模块有不同依赖性的模块的最佳方式是什么?

最佳回答

依赖关系并不需要不同。 相反, 使您的模块具有“ 或 模块作为依赖性。 相反, 您需要为两个不同案例的模块进行对称, 从服务器和浏览器特定代码中通过正确的参数来处理这些案例。 一种方法是要求在使用任何方法之前在模块上设置特定属性, 而对于提供所需文件装入功能的对象来说, 此属性是 :

mymodule.fileLoader = fswrapper;

mymodule.fileLoader = ajaxWrapper;

(obviously, the above two fragments will appear in server and browser specific code respectively). Another alternative would be to pass the relevant object to the construct或 of the class exp或ted from the module (if that s how your module is exposed) 或 assign it as a property of the created object. E.g.

var v = new MyClass(fswrapper);
//或
var v = new MyClass();
v.fileLoader = ajaxWrapper;

There are lots of variations on these ideas, but the point is that you should abstract the file system difference away from the shared module, and instead pass it an object that handles the access f或 the environment in question.

问题回答

暂无回答




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签