Line breaks in a text binding

3,372 views
Skip to first unread message

ma...@cloudaloe.org

unread,
Sep 9, 2012, 5:36:54 AM9/9/12
to knock...@googlegroups.com
Hi,

I bind a string to a Knockout text (you know... http://knockoutjs.com/documentation/text-binding.html).
I build my string with plain javascript concatenation (using += to compose it from many strings. Each += produces a line break in my string, which is exactly what I intend).
I notice (in Chrome) that, courtesy of Knockout, this results in a <br> being added in the DOM per each line break included in my string. 
In chrome, the text shows well with new lines as expected.

In firefox however, the text shows as one long string, no new lines are being produced (rather, only a space is added instead).
The containing element to which the variable is bound to is a div, if it matters.

How can I get a more uniform behavior across the two browsers?

Thanks,
Matan

gvas

unread,
Sep 9, 2012, 7:29:40 AM9/9/12
to knock...@googlegroups.com, ma...@cloudaloe.org
Knockout's text binding uses the innerText or textContent DOM properties, depending on which one is supported by the browser. These behave differently.

You can use a more consistent behavior by using createTextNode() in a custom binding handler: http://jsfiddle.net/fUsb5/6/

Unfortunately this won't replace the line breaks to <br>s, so you also have to use some other method to accomplish that (in the jsfiddle above the white-space CSS property is set to pre).

Best regards
G

Matan Safriel

unread,
Sep 10, 2012, 8:06:56 AM9/10/12
to gvas, knock...@googlegroups.com
Thanks. 
I'll check it out, when I go back to that project.
I understand then that it's possibly better to create a DOM node for each line rather than rely on the browser or knockout.js to automatically guess how to handle new lines, which obviously they don't accomplish in a very uniform way.

Michael Best

unread,
Sep 10, 2012, 4:09:27 PM9/10/12
to knock...@googlegroups.com, ma...@cloudaloe.org
Version 2.2 of Knockout will be coming out in about a month and will include an update to the text binding to use createTextNode.

The CSS style to use is generally white-space: pre-wrap

Matan Safriel

unread,
Sep 11, 2012, 4:15:41 AM9/11/12
to Michael Best, knock...@googlegroups.com
Coolness. I'll just wait for that new version.
Reply all
Reply to author
Forward
0 new messages