JavaScript that is C++

  • Posted by koen
  • Tuesday, March 2, 2010 @ 10:47

Since long, Wt embedded snippets of JavaScript code (e.g. used for implementing the layout managers) directly in the C++ source code as string literals. This was not very developer friendly, and it also did not allow for using a minifier to compress the JavaScript.

The latest Wt git contains the following nice (and hacky!) solution. It is based on the following idea (but more elaborated):

#define JS(...) #__VA_ARGS__

const char *someJs = JS(
  /* This may contain any valid JavaScript */
  var Foo = function(java, script, here) {
    var a, b;

    this.eatCrocodile = function(d) {
       d.innerHTML = "Eating it now";
    }
  };
);

Thus, by defining a macro which takes variable arguments (to allow for ‘,’ in the JavaScript code) and pastes them into a string, you can put multi-line JavaScript statements or expressions inside your C++ code, which are formatted by the compiler into a string literal.

This works (incidently!) because JavaScript also requires that brackets are balanced, and uses the same syntax for comments and string/char literals.

Snippets of JavaScript code are served by Wt piecewise when needed and inline to avoid an additional round-trip. We use this trick to include (minified) JavaScript files directly into C++ code for optimized released builds, while reading the same JavaScript files from disk during debug builds. In this way, we avoid a rebuild when going through trial-and-error cycles trying to make our JavaScript work properly on all browsers, and benefit from a minifier (we are currently using Google Closure compiler) for hassle-free release builds.

Sometimes, we love the preprocessor that we all hate.

Tags:
5 comments
  • Posted by anonymous
  • 8 years ago
As we are web developer if we cannot write our own javascript funcuion so why is that tool useful for us ?
  • Posted by anonymous
  • 10 years ago
this can cause problems with backslashes in JavaScript Regular Expressions syntax:
str = str.replace(/(\d+)\.\d+/, '$1.');
  • Posted by anonymous
  • 14 years ago
That's great! Btw, there are jQueryUI and jQueryTools that can replace ExtJS with very permissive license and high quality widgets :)
  • Posted by anonymous
  • 14 years ago
Hey Koen, Would that work with jQuery's unusual syntax? Example:

$("#whatever").click(function(){ return false; });
  • Posted by koen
  • 14 years ago
Yes that is no problem (in fact we are using jQuery since Wt 3.1.1, which is especially useful for working around IE's ill support for dynamic style rules). So far we have not seen a problem with any esoteric JavaScript syntax.

Contact us for more information
or a personalised quotation