我正在使用 jQuery UI SelectMenu 插件(https://github.com/fnagel/jquery-ui),它允许的事情之一是它呈现列表项的方式的“格式”。描述如下;
format: null, Accepts a function with a single argument that can be manipulated and returned with any level of manipulation you'd like
所以我的问题是 - 我怎样才能将 Knockout 模板作为函数返回,以便我可以使用该模板作为渲染源?
这是一个您也可以玩弄的 fiddle ,但我还包含一些代码
jsFiddle
这基本上就是我的 viewModel 的样子;
$(document).ready(function(){
function User(id, name, points) {
this.Id = ko.observable(id);
this.Name = ko.observable(name);
this.Points = ko.observable(points);
}
var viewModel = {
Users: ko.observableArray([
new User("users/1", "Stacey", 27),
new User("users/2", "Ciel", 30)
]),
Selected: ko.observable()
};
ko.applyBindings(viewModel);
$template = $('#user-template');
$('select').selectmenu({
format: $template
});
});
以及匹配的 HTML - 请注意,我有一个模板,我希望将其绑定(bind)到 User
。我试图在 JavaScript 中调用模板并将其作为格式参数传递 - 但它显然不起作用。
<select id="users"
data-bind="options: Users,
optionsCaption: 'select a user...',
optionsText: 'Name',
value: Selected,
valueUpdate: blur">
</select>
<span data-bind="with: Selected">
<div data-bind="text: Name"></div>
<div data-bind="text: Id"></div>
</span>
<script type="text/html" id="user-template">
<h1 data-bind="text: Id"></h1>
<h3 data-bind="text: Name"></h3>
</script>
最佳答案
我检查了该插件,它不太适合使用 Knockout。您需要创建自定义绑定(bind)。问题是您用作格式的函数不会接收每个选项的实际 View 模型,它将接收选项文本和选项本身
您可以做的一个技巧是让选项文本成为 JSON 中的实际对象,然后在格式函数中反序列化为该对象并将其传递给渲染引擎,例如
function(text, opt){
var item = ko.mapping.fromJSON(text);
ko.renderTemplate(rowTemplate, bindingContext.createChildContext(item), **problem here**, "replaceChildren");
}
在编写示例时,我刚刚意识到另一个问题,ko.renderTemplate 想要一个 html 元素来应用模板,我认为它不能仅在内存中创建一个 html 元素,它必须附加到 DOM让它发挥作用。
编辑:这是一种执行此操作的方法,请注意,它不是太多测试人员,因此可能存在错误。
format = function(text, option) {
var index = option[0].index;
if(index == 0 && caption !== undefined) return text;
if(caption !== undefined) index--;
var dummy = $("<div />");
ko.renderTemplate(template, bindingContext.createChildContext(items[index]), null, dummy[0], "replaceChildren");
return dummy.html();
};
关于jquery-ui - KnockoutJS - 返回模板作为函数结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13899050/