DotnetShadow
DotnetShadow

Reputation: 778

Javascript function pass object or use data attributes?

I'm wondering which of the following would be the best way to pass server data and use it in a function, especially if the function is to be used by a component

Method 1

function doSomething(elm, serverTime) {
   // Do something
}

<script>
doSomething('foo', '<% php server time %>');
</script>

vs

Method 2

<div id="foo" data-server-time="<% php server time %>"></div>
function doSomething(foo) {
    var serverTime = getElementById("server-time").dataset.servertime;
    // Do something
}

<script>
doSomething('foo'); 
</script>

Method 3

Other suggestions? Would like to do something like the following but not sure how?

document.getElementById("foo").doSomething() ?

Upvotes: 0

Views: 124

Answers (4)

vol7ron
vol7ron

Reputation: 42099

You are at a crossroads looking for common practice, to which one isn't more prevalent over another. Any great sage may tell you, which you choose isn't as important as making the same choice again; that is, be consistent.

Depending on the type of information, I would either pass it in the:

  • HTTP header (e.g., via HTTP Cookie)
  • Querystring (if redirection is used)
  • External JSON file (e.g., server.json), loaded via JS
  • Embedded JSON object (e.g., window.SERVER = {'server_time': <%php ...%>};)

In your case, keeping it closer to the JavaScript makes more sense and is easier to maintain, if the JS is the main place you're working. Therefore, Method 1 is both cleaner and easier to make changes in the future. Method 2, would require sifting through the HTML and making sure you are modifying the correct line.

Though, I'm somewhat partial to keeping server data as an external JSON, or embedded JSON object. So if you needed to track other server data/metadata, it's easy to add to it.

Upvotes: 1

jperelli
jperelli

Reputation: 7197

For me, case 1 would be better.

  • code would have less coupling
  • code would not use global vars (document.getElementById)
  • you could reuse your function in other places that do not have DOM, like in the server.

Upvotes: 1

Amir H. Bagheri
Amir H. Bagheri

Reputation: 1426

I would argue that all of them are the same and depending on your coding manner, they woulh have the same performance performand.

Let's not forget that nowadays, the most common way is to attach event listeners to elements (jQuery, Angular and .., use heavily event listeners).

Upvotes: 0

Lime
Lime

Reputation: 13532

I would argue in this case the 1st is better in this simple example because sever time isn't really attached to any specific div element.

Just make sure no matter what you do that there are no XSS security holes.

Upvotes: 1

Related Questions