这是我的代码。
<input type="text" placeholder="Add New Tag" data-bind="value: tagToAdd, valueUpdate: 'afterkeydown', event: { keypress: addOnEnter }" />
这是我的淘汰代码。
self.addOnEnter = function (event) {
console.log(event.which);
var keyCode = (event.which ? event.which : event.keyCode);
if (keyCode === 13) {
self.addTag();
}
return true;
};
当我在输入字段中输入内容时,我会记录该事件,并继续获取未定义的内容。我不知道为什么我无法捕捉到哪个事件被解雇。
你可以在jsFiddle上测试我的代码。 http://jsfiddle.net/GBLNR/6/
只需在输入字段中输入任何内容,然后从控制台中查看结果。
答案 0 :(得分:4)
Knockout将当前数据上下文作为处理程序的第一个参数传递。 event
是第二个参数。
因此,您的功能的签名必须是:
self.addOnEnter = function(data, event) {
}
或者,处理此问题的一种好方法是通过自定义绑定:
//a custom binding to handle the enter key (could go in a separate library)
ko.bindingHandlers.enterKey = {
init:function (element, valueAccessor, allBindingsAccessor, data, context) {
var wrappedHandler, newValueAccessor;
//wrap the handler with a check for the enter key
wrappedHandler = function (data, event) {
if (event.keyCode === 13) {
valueAccessor().call(this, data, event);
}
};
//create a valueAccessor with the options that we would want to pass to the event binding
newValueAccessor = function () {
return { keyup:wrappedHandler };
};
//call the real event binding's init function
ko.bindingHandlers.event.init(element, newValueAccessor, allBindingsAccessor, data, context);
}
};
现在,您只需对enterKey
函数使用此addOnEnter
绑定,它只需要处理您的数据。
答案 1 :(得分:0)
修改了Niemeyer对以下代码的回答,以防止输入键事件冒泡。当您想要避免textarea
元素中的换行符时有用。
ko.bindingHandlers.enterPressed = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
// Wrap the handler with a check for the enter key.
var wrappedHandler = function (data, event) {
if (event.keyCode === 13) {
valueAccessor().call(this, data, event);
return false;
} else {
return true; // Allow event to bubble.
}
};
// Create a valueAccessor with the options that we would want to pass to the event binding.
var newValueAccessor = function () {
return { keypress: wrappedHandler }; // Using keypress instead of keyup.
};
// Call the real event binding's init function.
ko.bindingHandlers.event.init(element, newValueAccessor, allBindingsAccessor, viewModel);
}
};