Search code examples
htmlknockout.jsmarkup

Too much markup in HTML from Knockout JS


I am learning knockoutjs and noticed my pages contain a lot of markup that seems .. well not sure what it seems.

  • Unnecessary - its necessary for KO to work
  • Excessive - data-bind= needs data to work
  • Code Clutter - lots of markup ..

Maybe I am doing things 'in-line' rather than using the View properly This code:

<tr data-bind="css: {'checked':Active,'unchecked':!Active,}">
            <td data-bind="text: Name, class: Active"></td>
</tr>

Generates:

<tr data-bind="css: {'checked':Active,'unchecked':!Active,}" class="checked">
  <td data-bind="text: Name, class: Active">Aaron46</td>
</tr>
<tr data-bind="css: {'checked':Active,'unchecked':!Active,}" class="checked">
  <td data-bind="text: Name, class: Active">Abigail</td>
</tr>
<tr data-bind="css: {'checked':Active,'unchecked':!Active,}" class="unchecked">
  <td data-bind="text: Name, class: Active">Adrienne</td>
</tr>
<tr data-bind="css: {'checked':Active,'unchecked':!Active,}" class="checked">
  <td data-bind="text: Name, class: Active">Aimee</td>
</tr>

Does this seem like 'Clutter Code'? Or should I not worry about it ... :)

I am loving KnockOutJS so far ..


Solution

  • I must admit that, after years of making Html as sparse as I possibly can, putting a lot of stuff into data-bind felt wrong.

    But, after a few weeks with it, the power of it has gotten me over the issue. It does all at least make sense.

    Saying that, if you're not actually binding to some data, I wouldn't use Knockout to set the CSS on your tds. So I'd go for this:

    <tr data-bind="css: {'checked':Active,'unchecked':!Active,}">
                <td class="Active" data-bind="text: Name"></td>
    </tr>