sandrooco
sandrooco

Reputation: 8716

Proper way to bind in tree structure with KnockoutJS

So I have the following "target/goal"-structure:

<p data-bind="text: Title" class="commentContent">
  <a class="removeComment" data-bind="attr: {'data-commentId':Id}">x</a>
</p>

The anchor tag has to be in the paragraph. Now, as you can imaginge, the anchor tag is overwritten by the paragraph content.

What's the proper way to bind such stuff?

Upvotes: 3

Views: 31

Answers (1)

Jeroen
Jeroen

Reputation: 63729

Here's how you could do that, using the containerless syntax to avoid extra DOM cluttering your page:

ko.applyBindings({ Title: "My fancy title", Id: 42 });
.commentContent { background: lime; padding: 10px; }
a { color: red; font-weight: bold; background: blue; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>

<p class="commentContent">
  <!-- ko text: Title --><!-- /ko -->
  <a class="removeComment" data-bind="attr: {'data-commentId':Id}">XanchorX</a>
</p>

You could also not use the containerless syntax, but use a span with a specific class instead, if you do need the extra markup to target it with certain CSS.

Upvotes: 2

Related Questions