Create a custom binding handler to initialize and update the jScrollPane instance:
ko.bindingHandlers.jScrollPane = {
init: function(element, valueAccessor) {
var o = valueAccessor() || {};
// initialize
$(element).jScrollPane(o.options);
var reinit = function() {
var scroll = $(element).data("jsp");
if (scroll) {
scroll.reinitialise();
}
};
// handle window resize (though not really necessary if your chat box has a set pixel width)
$(window).resize(reinit);
// add subscription to observable if passed in
if(o.subscribe) {
o.subscribe.subscribe(function() {
// use setTimeout so the DOM finishes updating before reinitialising
setTimeout(reinit, 0);
});
}
}
};
Call the new jScrollPane
handler on the #chat-content
div, passing in the messages
observable so it knows when to refresh the scroll bar. Put the foreach
binding handler in a child element to prevent it from interfering with the DOM changes that jScrollPane
makes.
<div id="chat-content" data-bind="jScrollPane: { subscribe: messages }">
<div data-bind="foreach: messages">
<div data-bind="text: messageText"></div>
</div>
</div>
JSFiddle: http://jsfiddle.net/aZpgY/7/
jScrollPane binding handler adapted from here: http://jsfiddle.net/rniemeyer/NgNvf/