【发布时间】:2013-10-23 06:10:40
【问题描述】:
大家好,
我将 Knockoutjs 与 Jquery UI 小部件结合使用,以显示一个自动完成框,其中每个选定项目具有多个跨度。
我遵循以下方法
1) 在视图模型中有一个可观察数组 (selecteditems) 并将其绑定到声明性模板以显示 SPAN
2) 绑定到 JQUERY UI 自动完成小部件以显示建议的输入框,并在每次选择时使用 CustomBindingHandler 将新项目添加到 selecteditems 数组。
3) 使用 CustomBindingHandler 向绑定到可观察数组 selecteditems 的每个 SPAN 显示 JQUERY UI ToolTip 小部件。
我面临的问题是 JQUERY UI ToolTip 小部件在负载中显示没有任何问题,但是只要 selecteditems 数组发生更改,CustomBindingHandler 中就无法识别 Tooltip 小部件
非常感谢任何帮助。
<div>
<div style="max-height: 105px;" data-bind="foreach: selectedItems">
<span data-bind="text: name, id: id, assignToolTip: id"></span>
<input data-bind="assignAutoComplete: { rootVm: $root }" type="email" value="">
</div>
</div>
<script>
var MyViewModel = function () {
this.selectedItems = ko.observableArray(
[{ name: "eww", id: "ww" },
{ name: "aa", id: "vv" },
{ name: "xx", id: "zz" }]);
};
ko.bindingHandlers.assignToolTip = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
if ($(element) != undefined) {
var currentDataItem = ko.dataFor(element);
$(element).tooltip({
items: 'span',
track: true,
content: function () {
return "<ul><li>" + currentDataItem.name + "</li><li>" + currentDataItem.id + "</li></ul>";
}
});
}
},
};
ko.bindingHandlers.assignAutoComplete = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
if ($(element) != undefined) {
var currentDataItem = ko.dataFor(element);
$(element).autocomplete({
source: function (request, response) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function (data) {
response($.map(data.geonames, function (item) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
};
}));
}
});
},
minLength: 2,
select: function (event, ui) {
var settings = valueAccessor();
var rootVm = settings.rootVm;
rootVm.selectedItems.push({ name: ui.item.label, id: ui.item.label });
return false;
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
}
}
};
ko.applyBindings(new MyViewModel());
</script>
<script src="~/Scripts/jquery-ui-1.10.3.js"></script>
【问题讨论】:
标签: jquery jquery-ui knockout.js