John And with knockout.js,...">

Combination of text and html from knockout

This is how I want to build html

<a href="#">John <i class="person"></i></a> 

And with knockout.js, this is what I did.

 <a data-bind="text:name"><i class="person"></i></a> 

As you can guess, all elements (not just text) of the anchor are deleted due to text binding, in this case, whole tags inside the anchor are deleted. My solution is below.

 <a data-bind="html: name() + '<i class="person"></i>'"></a> 

the concat line with html in data-bind is a solution, but has 2 big drawbacks. "name" is not safe, so we can get an html injection. Sedondly writing html inside data binding attributes is crap.

Another solution.

 <a href="#"><span data-bind="text:name"></span><i class="person"></i></a> 

I know that we are introducing new html markup for a simple solution. This is what I found best.

What is the well-known solution to this problem in knockout.js?

Can we point to just update the text, not the whole elements inside it, before binding the text through the parameters?

Or the best solution?

+6
source share
2 answers

Using a range is the preferred solution. If text binding does not replace all content, then it is difficult for him to know what needs to be updated and not to be updated the next time he changes. If you want to always deal with the first child element of a node element, then you can write a little custom binding for help.

Here is a simple prependText binding. This always replaces the first child of the node element that contains the binding. So, you would like to make sure that the first node was at least a space.

 ko.bindingHandlers.prependText = { update: function(element, valueAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()); //replace the first child element.replaceChild(document.createTextNode(value), element.firstChild); } }; 

Use it as:

 <a href="#" data-bind="prependText: name"> <span> another element</span></a> 

Example: http://jsfiddle.net/rniemeyer/5CfzH/

+9
source

You can also use the KO "no container" notation

 <!-- ko text: YourProperty --> <!-- /ko--> 

The same can be done with other bindings (e.g. foreach): See part 4

+6
source

Source: https://habr.com/ru/post/923665/


All Articles