Formatting Post Bind

65 views
Skip to first unread message

t3rse

unread,
Jun 1, 2011, 8:28:35 AM6/1/11
to KnockoutJS
I was wondering: is it possible to format text after it's been bound?
If I bind text that is in a span and want to go through and replace it
with some highlights using css would this be supported? To be more
specific, if I had the following text:

<span> this is foo </span>

And wanted to do something like the following where foo is a keyword:

<span> this is <span class="highlight">foo</span></span>

Thanks!

rpn

unread,
Jun 1, 2011, 11:58:52 AM6/1/11
to knock...@googlegroups.com
This is kind of quick and dirty ,but how about something like this?  http://jsfiddle.net/rniemeyer/A7HDH/

It uses a custom binding that looks like:

ko.bindingHandlers.highlightedText {
    updatefunction(elementvalueAccessor{
        var options valueAccessor();
        var value ko.utils.unwrapObservable(options.text);
        var search ko.utils.unwrapObservable(options.highlight);
        var css ko.utils.unwrapObservable(options.css);  //could be an observable
        var value $('<div/>').text(value).html();  //could do this or something similar to escape HTML before replacement, if necessary and the possibility of HTML injection exists in your value
        var replacement '<span class="' css '">' search '</span>';
        element.innerHTML value.replace(new RegExp(search'g')replacement);
    }
};

Then, you use it like:  

<div data-bind="highlightedText: { text: name, highlight: searchText, css: 'highlight' }"></div>
<hr />

Name: <input data-bind="value: name" /><br/>
Search: <input data-bind="value: searchText" />

text, highlight, and css could all be observables.  

Reply all
Reply to author
Forward
0 new messages