按回车后,我无法将名称添加到列表中,但单击“添加名称”时仍会添加。有任何想法吗?
问问题
2183 次
5 回答
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,后者更适合通用作品的名称。
于 2012-09-06T21:07:13.353 回答
1
考虑提交绑定 http://knockoutjs.com/documentation/submit-binding.html
它避免了需要进行自定义绑定来捕获 keycode 13 你也不需要 valueUpdate
html
<form data-bind="submit:pushPeople">
<input type="text" data-bind="value: addPeople, valueUpdate: 'afterkeydown'"/>
<input type="submit" value="Add Name" />
</form>
于 2013-04-04T15:14:45.070 回答
0
于 2012-09-06T21:19:59.897 回答
0
这段代码的问题是 pushPeople() 中的 self.people 是未定义的(因为this
指向输入元素而不是视图模型)。
试试这个:http: //jsfiddle.net/WWpcC/22/
改为value.call(this);
_value.call(ko.dataFor(this));
于 2012-09-06T21:12:05.947 回答
0
于 2012-09-27T15:09:18.807 回答