سؤال

Consider e.g. the following scenario: we give some entry point URL (something like https://our.server/customer-name/entry-point.js) to our customer, so that they're able to include our product on their page by simply writing

<script language="Javascript" src="https://our.server/customer-name/entry-point.js"/>

in the place they want to put our product (yes, I know, this is an ugly solution, but it is not something I could change).

So here we face the problem: our entry-point.js should somehow know from where (https://our.server/customer-name/) it should load the other files. So it seems that the answer is to generate entry-point.js dynamically so that it will contain e.g.

var ourcompany_ourproduct_basepath = "https://our.server/customer-name/";

The obvious way to do this is to construct an entry-point.js manually, something like this:

res.write("var ourprefix_basepath = \"" + basepath.escape() + "\";");
res.write("function ourprefix_entryPoint() { /*do something*/ }");
res.write("ourprefix_entryPoint();");

As you can see, it is just too bad.

Is there any template engine that will allow e.g. for the following:

var basepath = "https://our.server/customer-name/";
var export = {
    ourprefix_basepath: basepath.escape(),
    ourprefix_entrypoint: function() { /* do something */ }
};
templateEngine.render(export);

or

view.vw:
    ourprefix_basepath = rewrite("{#basepath}");
    function ourprefix_entrypoint() { /* do something */
    ourprefix_entrypoint();

App.js:
    templateEngine.render("view.vw", { basepath: "https://our.server/customer-name/" });

or something like this (you've got the idea), which will write the following to the response stream:

var ourprefix_basepath = "https://our.server/customer-name/";
function ourprefix_entrypoint() { /* do something */ };
ourprefix_entrypoint();

?

هل كانت مفيدة؟

المحلول

It seems that Node.js supports reflection, though i can't find if it is explicitly stated somewhere.

So, by exploiting the fact JSON is the subset of JS, the following cleaner code without using a template engine is possible:

var entrypoint = function(data) {
    /* do something with data.basepath and data.otherparam here... */
}

exports.processRequest = function(request, response) {
    var data = {
        basepath: computeBasepath(request),
        otherparam: "somevalue"
    };
    response.send("(" + entrypoint.toString() + ")(" + JSON.stringify(data) + ")");
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top