我正在创建一个自定义绑定(bind),它将显示一个 anchor ,单击该 anchor 会变成一个文本框。一旦用户输入一个值并按下 Enter 键,该值将被推送到传递给绑定(bind)的 observableArray 中。
大部分绑定(bind)取自 Ryan Niemeyers 示例 - 发现 here
html
<div data-bind="clickToEdit: { data: items, buttonText: 'New Item' }"></div>
绑定(bind)
ko.bindingHandlers.clickToEdit = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, context) {
var options = valueAccessor() || {};
var editing = ko.observable(false);
var newValue = ko.observable();
var button = $('<a class="btn btn-mini" href="#">' + options.buttonText + '</a>').prepend('<span class="icon-plus"></span>').appendTo(element)[0];
var input = $('<input type="text">').appendTo(element)[0];
ko.applyBindingsToNode(button, {
hidden: editing,
click: function () {
editing(true);
}
});
ko.applyBindingsToNode(input, {
value: newValue,
visible: editing,
hasFocus: editing,
//valueUpdate: 'afterkeydown',
onEnter: function(data) {
debugger;
options.data.push(data);
editing(false);
}
});
}
};
问题在于,在绑定(bind)到 onEnter
绑定(bind)的函数中,数据参数始终未定义,因此新值永远不会推送到数组中。
请查看我的fiddle完整示例
最佳答案
有两件事可以提供帮助:
applyBindingsToNode
调用接受第三个参数,您可以在其中提供上下文。在我的一些示例中,上下文是无关紧要的,因为它直接写入可观察对象并且不需要数据。因此,您可以将context
(或viewModel
)作为第三个参数传递给第二个applyBindingsToNode
调用。如果我理解你想要做什么,那么我认为你可以这样做:
options.data.push(new Item(newValue());
并且不需要担心上下文/数据(这将是整体 View 模型,因为您位于顶级范围内)。
关于javascript - 使用 KnockoutJS 的 ClickToEdit 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15571812/