문제

I am developing a simple web app and I need to update the displayed data after certain events or conditions. This data is scattered in many different places and within completely separate markup structures. I have used classes in the past but found some dangerous cases when using classes to edit data has come to bite me (especially as we are using OOCSS and there are many classes we want to change and should not be bound to js data or behaviour). The solution below should be buletproof in this respect but as I have never seen it used before I fear I may be missing something. Is there any downside to a solution like the following?

Example code below - using jQuery

The follow may be bound to a specific data-change event:

$('.data[data-type=user_data]').each(function(){
    $(this).find('.data[data-type=user_name]').html($.user.userName)
    .end().find('.data[data-type=user_location]').html($.user.userLocation)
    .end().find('.data[data-type=incident_date]').html($.user.incidentDate)
    .end().find('.data[data-type=incident_cost]').html($.user.incidentCost)
    .end().find('.data[data-type=user_hair_color]').html($.user.hairColor);

      //more data will be added here ...

});

Markup will be this in some places:

<div class="data incident_result bubbled_box" data-type="user_data">
<h3>Some heading</h3>
<ul>
    <li>Username:       <span class="data highlight name" data-type="user_name">Igor Wassel</span></li>
    <li>User location:  <span class="data" data-type="user_location">Estonia</span></li>
    <li>Provider:       <span class="data" data-type="incident_date">21/08/11</span></li>
</ul>

Other places the markup will include the other data but within a completely different html structure.

도움이 되었습니까?

해결책

Are there any downsides to using data attribute to edit content with javascript?

No, unless you write to these attributes and read them back with JavaScript. As too many people do, unfortunately. DOM isn't the place to store your JavaScript state.

Otherwise, it's perfectly OK to send data from server to client side via data-attributes. To stay completely failsafe append some common prefix to all your data-attributes.

Only I doubt it's performant to select elements by attribute value. Methods like getElementsByName are optimized for the task.

One could, at least, expand internal jQuery find-loops to iterate over all elements and automatically retrieve their values.

$('.data[data-type=user_data] *').each(function (el) {
    el = $(el);
    type = el.data('type');
    if (type) {
        el.html($.user[type.toCamelCase()]);
    }
});

String.prototype.toCamelCase = function () { /* implement me */ };

And don't forget the HTML5 doctype declaration.

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