Is it good practice to create JavaScript objects on the basis of html5 data attribute values? [closed]

StackOverflow https://stackoverflow.com/questions/19908096

문제

I am working on a small HTML/JavaScript application where a user can browse through different content without refreshing the page. I use divs as 'pages' by showing and hiding the divs as the user navigates through the application. Between two pages occurs a small animation (like fading or sliding). When the animation is finished and the 'page' is visible a trigger is fired.

Each page executes his own behavior when triggered (e.g. playing a video/animation/show some text). Each page(div) has his own JavaScript class linked to it. The Class name of the JavaScript class is stored in a data attribute called data-pageClass:

<div id="page1" class="pn-page intro" data-pageClass="IntroPage">
    Page 1: introduction text
</div>
<div id="page2" class="pn-page page2" data-pageClass="VideoPage">
    Page 2: playing a video here
</div>

The class handling the navigation creates the classes of the pages by looping through the html structure and using the data attribute to identify which class to create. I use the 'stringToFunction' function described in this question on StackOverflow

Looping code:

$("#pages .pn-page").each(function (i, el) {
    var PageClass = stringToFunction(el.getAttribute("data-pageClass"));
    var newPage = new PageClass(el);
    _this.pages.push(newPage)
});

For simplicity's sake I left out all the other code. please let me know when it's unclear.

So my question is if it is bad practice to 'dynamically' create objects in this way. I thought it very useful to link divs to custom javascript classes (a bit like DOM does).

도움이 되었습니까?

해결책

I believe that what you are doing is good practice. The data attribute is meant to be used to embed custom data on a page, which is exactly what you are doing. You should obviously take care that potential attackers will not be able to inject custom HTML into your page in order to affect your JavaScript code in malicious ways, but that is nothing new.

An alternative approach I have used in the past is use view classes that run on on both the server (NodeJS) and client side. The server and client side are both able to generate the HTML, and the client side is able to attach the generated objects to the HTML if it was already generated by the server. This saves you the littering of your HTML by inserting data attributes, but otherwise it is not that much different, and it might not be applicable in all situations.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top