我无法在输入后将名称添加到列表中,但在点击"添加名称"时仍然会添加。有什么想法吗?
答案 0 :(得分:1)
查看http://todomvc.com/architecture-examples/knockoutjs/
具体而言,http://todomvc.com/architecture-examples/knockoutjs/js/app.js
var ENTER_KEY = 13;
// a custom binding to handle the enter key (could go in a separate library)
ko.bindingHandlers.enterKey = {
init: function( element, valueAccessor, allBindingsAccessor, data ) {
var wrappedHandler, newValueAccessor;
// wrap the handler with a check for the enter key
wrappedHandler = function( data, event ) {
if ( event.keyCode === ENTER_KEY ) {
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 );
}
};
请注意,此扩展程序名为 enterKey ,而不是 addOnEnter ,这是一个更适合通用部分的名称。
答案 1 :(得分:1)
考虑提交绑定 http://knockoutjs.com/documentation/submit-binding.html
它避免了制作自定义绑定以捕获键码13的需要 您也不需要valueUpdate
HTML
<form data-bind="submit:pushPeople">
<input type="text" data-bind="value: addPeople, valueUpdate: 'afterkeydown'"/>
<input type="submit" value="Add Name" />
</form>
答案 2 :(得分:0)
此代码的问题是pushPeople()中的self.people未定义(因为this
指向输入元素而不是视图模型。)
试试这个:http://jsfiddle.net/WWpcC/22/
将value.call(this);
更改为value.call(ko.dataFor(this));
答案 3 :(得分:0)
答案 4 :(得分:0)