C # code that generates javascript on the fly

Is it possible to generate code like this on the fly? Or is it the main smell of the code? How can this be improved?

I'm new to the net, but I stumble about this all the time and I don't understand why.

// Create a js function that applies foo to each group of controls
foreach (KeyValuePair<string, Dictionary<Control, string>> pair in maps)
{
    js.Append(pair.Key);
    js.Append("=function(grid){Prm.remove_endRequest(");
    js.Append(pair.Key);
    js.Append(");if(grid && grid._element)"); //   ... blah blah blah

}
page.ClientScript.RegisterClientScriptBlock(page.GetType(), key + "Ajax", 
    js.ToString(), true);

      

+2


source to share


1 answer


I can't smell it until you start doing it all over the place.

Let's consider these changes, however, it will help in the future:



  • Write data driven JS functions and only dynamically generate the data they need. This way, all your JS can be hidden in a fast static file and your server only sends data. This is a better design change than (2) and (3) and it really isn't that hard. Just think about the data your current code generator needs, serve that data instead of JS code, and then wrap the JS code into "factory functions" that take that data as input.

  • Use templates for JS code the same way you use templates for HTML. This way you don't have to toss around in your C # control flow / data control code when you really want to change some variable names. I would like to suggest the filenames of the templates with the name of the view it helps. If you do , perhaps you will be JS-code patterns , . You can write a simple templating engine or use one of the many that exist. Home.aspx

    Home_DoCrazyGridThing.js

    Home_DoOtherCrazyThing.js

  • Create a thin layer on top of the generation code so that it can understand what you are doing with the maintainer. That is, there is a class JSCodeGenerator

    with different levels of intelligence (understands the language OR simply allows you to dump a line in it or interacts with the template engine from (2)).

+4


source







All Articles