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 li开发者_StackOverflowbraries.
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)
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.
精彩评论