如何将javascript封装在服务器端语言组件中?
是否有任何设计模式或其他东西可以用来创建独立的组件,封装一些功能,包括将脚本标签添加到最终的 html 输出?
例如,我在某种程度上成功构建的一个组件是 Modal_Window 包,我可以这样使用它:
$mw = new Modal_Window($template); // $template is the object in charge of rendering the html template
$mw->setContent('Click here')->setBoxContent('<img src... />');
echo $mw;
在内部,Modal_Window 将负责告诉模板对象添加必要的 js 库。
嗯,这就是这个想法。我想知道的是这是否是处理此问题的方法,或者是否有更标准的方法(或者我是否根本不应该封装它)。这有已知的模式吗?是否可以以更加解耦的方式创建这种组件,以便我可以共享它?因为它完全依赖于模板对象,以及它检查js库是否添加多次的方式(假设我有2个组件:Modal_Window和Accordion,并且都需要jquery,并且我不希望它成为添加两次)
Is there any design pattern or something that I can use to create self-contained components, that encapsulates some functionality that includes adding script tags to the final html output?
For example, one component that I have built with some degree of success is a Modal_Window package, that I can use this way:
$mw = new Modal_Window($template); // $template is the object in charge of rendering the html template
$mw->setContent('Click here')->setBoxContent('<img src... />');
echo $mw;
Internally, Modal_Window will take care of telling the template object to add the necessary js libraries.
Well, this is sort of the idea. What I want to know is if this is the way to deal with this, or if there is a more standard way (or if I shoulnd't encapsulate this at all). Is there a known pattern for this? Is it possible to create this kind of component in a more decoupled way so I can share it? Because it is fully dependant on the template object, and the way it checks that the js libraries are not added more than once (suppose I have 2 components: Modal_Window and Accordion, and both need jquery, and I don't want it to be added twice)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议您有一个中央模块管理器(通常称为您的应用程序或框架)。
然后,模块向模块管理器注册,并告诉模块管理器它具有资产 x、y 和 z,在使用该模块时必须适当地包含这些资产。
有关如何处理、存储、呈现或一般处理这些资产的更多信息是特定于框架/应用程序的。
但对于包含 JavaScript,我想说模块只是简单地说明 JavaScript 对模块管理器的依赖关系。然后模块管理器可能会确保满足依赖关系并且依赖关系仅包含一次。
I would suggest you have a central module manager (generally this is called your application or your framework).
A module then registers with the module manager and tells the module manager that it has assets x, y and z that must be included appropriately when that module is used.
Any more information about how these assets are processed, stored, rendered or generally handled is framework / application specific.
But for including JavaScript I would say that a module simply states JavaScript dependencies to the module manager. Then the module manager will probably ensure dependencies are met and dependencies are only included once.