Skip to content

Instantly share code, notes, and snippets.

@oguzhaneren
Created December 10, 2014 18:29
Show Gist options
  • Save oguzhaneren/457aa26c83208016ddd6 to your computer and use it in GitHub Desktop.
Save oguzhaneren/457aa26c83208016ddd6 to your computer and use it in GitHub Desktop.
Knockout markdown and ellipsis (less,more) handler , depended to https://code.google.com/p/pagedown/
<p data-bind="markdown: content></p>
or
<p data-bind="markdown: {text:content,options: { maxLength:500 }}></p>
var _markdownHandler = function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var options = {
maxLength: 100,
moreText: "more",
lessText: "less",
moreClass: "markdown-more-text",
lessClass: "markdown-less-text",
};
var binding = ko.unwrap(valueAccessor());
var text = "";
if (binding === null) {
binding = "";
}
if (typeof binding === "string") {
text = binding;
} else {
text = ko.unwrap(binding.text);
if (binding.options) {
options = ko.unwrap(binding.options);
}
}
var converter = new Markdown.getSanitizingConverter();
var truncate = options.maxLength && options.maxLength != 0 && text.length > options.maxLength;
var el = $(element);
var fullText = converter.makeHtml(text);
if (truncate) {
converter.hooks.chain("preConversion", function(text) {
var truncatedValue = text.length > options.maxLength ? text.substring(0, Math.min(text.length, options.maxLength)) + " ..." : text;
return truncatedValue;
});
var truncatedText = converter.makeHtml(text);
el.html("").append($("<div class='js-markdown-text'>").append(truncatedText));
el.append(String.format("<a class='js-markdown-toggle' {0}' data-action='more' href='#' >{1}</a>", options.moreClass, options.moreText));
ko.utils.registerEventHandler(el.find('.js-markdown-toggle'), "click", function(ev) {
ev.stopPropagation();
ev.preventDefault();
var t = $(this);
if (t.data("action") == 'more') {
t.removeClass(options.moreClass);
t.addClass(options.lessClass);
t.text(options.lessText);
t.data("action", "less");
el.find(".js-markdown-text").html(fullText);
} else {
t.removeClass(options.lessClass);
t.addClass(options.moreClass);
t.text(options.moreText);
t.data("action", "more");
el.find(".js-markdown-text").html(truncatedText);
}
});
} else {
el.html(fullText);
}
};
ko.bindingHandlers.markdown = {
update: _markdownHandler,
init: _markdownHandler
};
@mmso2016
Copy link

mmso2016 commented Dec 1, 2016

hallo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment