Friday 27 February 2015

JS: opinions solicited regarding passing data values from server to client

G'day:
Just quickly.

Almost all of our JS is in separate JS files, and we try to take as much of an OO approach to our JS as is sensible in such a OO-hamstrung language. We do have separate "class" files (methods, stateful properties etc) and then script files which are used for event handlers when bootstrapping the page (creating said objects, etc).

Our JS inclusions would typically be along these lines:

<script src="/me/adamcameron/someapp/somepackage/SomeClass.js"></script>
<script src="/me/adamcameron/someapp/codeThatUsesSomeClass.js"></script>

Where:

// codeThatUsesSomeClass.js
var obj = new SomeClass(initParam, anotherInitParam);

// do stuff with obj


Occasionally though, we need to pass initialisation values from the server to the client. In the example above initParam and anotherInitParam might come from the DB.

So we might simply emit some inline JS along with the rest of the mark-up for the response:

<!--- someAppropriate.cfm --->
<!--- inline in HTML --->
<script>
var initParamForSomething = #serializeJson({"initParam"='"#serverSideValue#"', "anotherInitParam"='"#someOtherServerSiveValue#"'})#;
</script>

Which would obviously resolve to this:

var initParamForSomething = {"initParam":"resolvedValue", "anotherInitParam":"anotherResolvedValue"};

And then codeThatUsersSomeClass.js would instead be:

// codeThatUsesSomeClass.js
var obj = new SomeClass(initParamForSomething.initParam, initParamForSomething.anotherInitParam);

// do stuff with obj

Note: we'd only ever emit variable assignments via the server side code; no actual logic. All the logic is always in JS files.

Now I've been told we ought to be leveraging HTML5's data attributes, eg:

<!--- someAppropriate.cfm --->
<div id="initParamsForSomething" data-initparam="#serverSideValue#" data-anotherinitparam="#someOtherServerSiveValue#"></div>

And then codeThatUsesSomeClass.js is tightly coupled to that mark-up, and uses the DOM to get the variables out.

I am really not convinced this is a good approach:

  • It breaks the semantics of the HTML document (the JS is not relevant to it).
  • It doesn't really reduce any tight coupling between client side and server side code.
  • It does tightly couple client side code to mark-up.

I'm completely cool with the idea of not ever emitting JS logic via server side code, but I really don't see the problem with emitting variable assignments, if one actually needs to get data values from the server to the client.

However I am only a part-time client-side dev, so am not really that sure of my own gut instincts here.

I've googled and looked at some Stack Overflow answers on this topic, and I don't find any of them particularly convincing, TBH. They all position themselves as the "right" or "best" or "preferential" solution without really making a case as to why that's the case.

Thoughts?

--
Adam