0

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 ..

Ravi Ram
  • 24,078
  • 21
  • 82
  • 113

2 Answers2

2

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>
Paul Manzotti
  • 5,107
  • 21
  • 27
1

There are a few libraries around to minimize or eliminate the need for bindings in the markup.

My contribution to this cause is the Convention over configuration library https://github.com/AndersMalmgren/Knockout.BindingConventions

It uses conventions rather than explicit bindings, you will be amazed how seldom you need to explicit declare bindings when using a library like this, your css example still needs to be bounded with standard bindings, or if you create your own convention.

As an example, with vanilla KO:

<button data-bind="click: save, enable: canSave">Save</button>

My lib:

<button data-name="save">Save</button>

http://jsfiddle.net/3Ajnj/

Anders
  • 17,306
  • 10
  • 76
  • 144