我有一个observableArray用于插入消息。我想使用knockout显示所有消息。我想使用自定义滚动条图形 - jScrollPane。 (plugin LINK)
如何修复我的示例以显示来自jScrollPane的自定义滚动条?
示例:http://jsfiddle.net/aZpgY/3/
HTML:
<h2>Chat with knockout binding</h2>
<div id="chat-content" data-bind="foreach: messages">
<div data-bind="text: messageText"></div>
</div>
<br />
<form data-bind="submit: sendMessage">
message: <input data-bind="value: message" placeholder="Insert your massage" /><br />
<button type="submit">Add</button>
</form>
<h2>Example content - without knockout binding</h2>
<div id="example-content">
<div>Text</div>
<div>Text</div>
<div>Text</div>
<div>Text</div>
<div>Text</div>
<div>Text</div>
<div>Text</div>
<div>Text</div>
</div>
CSS:
#chat-content, #example-content{
width: 300px;
height: 100px;
overflow: auto;
}
JS:
function Message(data) {
this.messageText = ko.observable(data.messageText);
}
function ChatViewModel() {
// Data
var self = this;
self.messages = ko.observableArray([]);
self.message = ko.observable();
// Operations
self.sendMessage = function() {
self.messages.push(new Message({ messageText: this.message() }));
self.message("");
};
self.removeTask = function(task) { self.tasks.remove(task) };
}
ko.applyBindings(new ChatViewModel());
$(function(){
$('#chat-content').jScrollPane();
$('#example-content').jScrollPane();
});
答案 0 :(得分:1)
创建自定义绑定处理程序以初始化和更新jScrollPane实例:
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);
});
}
}
};
调用jScrollPane
div上的新#chat-content
处理程序,传入messages
observable,以便知道何时刷新滚动条。将foreach
绑定处理程序放在子元素中,以防止它干扰jScrollPane
所做的DOM更改。
<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绑定处理程序改编自此处:http://jsfiddle.net/rniemeyer/NgNvf/