javascript - Creating a custom binding for nl2br in knockout.js -


i trying write custom binding replace "/n" "<br />" within "<p>" element.

i understand concept more or less, i'm stuggling going. can suggest i'm going wrong. don't want use computed observable, want keep real value using "/n" rather "<br />".

ko.bindinghandlers.nl2br = {     init: function(element, valueaccessor, allbindingsaccessor, viewmodel, bindingcontext) {         var field = valueaccessor();         field.replace(/\n/g, '<br />');         $(element).val(field)     },     update: function(element, valueaccessor, allbindingsaccessor, viewmodel, bindingcontext) {         var field = valueaccessor();         field.replace(/\n/g, '<br />');         $(element).val(field)     } }; 

tl;dr answer

ko.bindinghandlers.nl2br = {     update: function (element, valueaccessor, allbindingsaccessor, viewmodel, bindingcontext) {         var field = ko.utils.unwrapobservable(valueaccessor());         field = field.replace(/\n/g, '<br />');         ko.bindinghandlers.html.update(element, function() { return field; });     } }; 

full answer

first things first, replace call should be:

field = field.replace(/\n/g, '<br />'); 

otherwise new string gets discarded.

apart that, wouldn't recommend setting element value directly. rely on existing handlers (that presumably tested in various browsers) heavy lifting. see r.p. niemeyer's blog post on subject (specifically item 3).

you can use either the text binding literally render "<br />" or (if trust input!) the html binding if want render newline <br />. latter looks this:

ko.bindinghandlers.nl2br = {      update: function (element, valueaccessor, allbindingsaccessor, viewmodel, bindingcontext) {          var field = ko.utils.unwrapobservable(valueaccessor());          field = field.replace(/\n/g, '<br />');          ko.bindinghandlers.html.update(element, function() { return field; });      }  };    ko.applybindings({ description: ko.observable("this is\nsparta!") });
p, pre { background-color: #dde; margin: 4px 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>    <strong>text version in &lt;p&gt;:</strong>  <p data-bind="text: description"></p>  <hr />  <strong>text version &lt;pre&gt;:</strong>  <pre data-bind="text: description"></pre>  <hr />  <strong>nl2br version in &lt;p&gt;:</strong>  <p data-bind="nl2br: description"></p>


Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

jquery - How would i go about shortening this code? And to cancel the previous click on click of new section? -