Created
August 5, 2016 04:34
-
-
Save patorash/b79ecda1c0615b5d9d3c52151991102a to your computer and use it in GitHub Desktop.
knockout.jsでエスケープ処理を行った上でnl2brするカスタムバインディング
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ko.bindingHandlers.nl2br = { | |
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { | |
var field = ko.utils.unwrapObservable(valueAccessor()); | |
var lines = field.split(/\r\n|\r|\n/).map(function(line) { return document.createTextNode(line) }); | |
var div = document.createElement('div'); | |
lines.forEach(function(line, idx, lines) { | |
div.appendChild(line); | |
if (idx !== lines.length - 1) { | |
div.appendChild(document.createElement('br')) | |
} | |
}); | |
ko.bindingHandlers.html.update(element, function() { return div.innerHTML; }); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment