I am unable to get the names to add to the list after hitting enter, yet it still adds when clicking "Add Name". Any ideas?
5 Answers
Have a look at http://todomvc.com/architecture-examples/knockoutjs/
Specifically, 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 );
}
};
Note this extension is called enterKey and not addOnEnter which is a more suitable name for a generic piece.

- 34,151
- 9
- 98
- 120
-
Great custom handler! Thanks for sharing - saved me time! – Cory House Oct 03 '13 at 20:24
Think about submit binding http://knockoutjs.com/documentation/submit-binding.html
It avoids the need to make a custom binding to catch keycode 13 Also you don't need the valueUpdate
html
<form data-bind="submit:pushPeople">
<input type="text" data-bind="value: addPeople, valueUpdate: 'afterkeydown'"/>
<input type="submit" value="Add Name" />
</form>

- 21
- 1
The problem with this code is that self.people in pushPeople() is undefined (because this
points to the input element instead of the view model).
Try this: http://jsfiddle.net/WWpcC/22/
Changed value.call(this);
to value.call(ko.dataFor(this));

- 17,720
- 10
- 62
- 93
try it like this
basically your "self" was a html element, not your view model

- 43,549
- 15
- 93
- 156
Actually you don't need any custom binding, simple event will be pretty enough!
I've adjusted your example. UPDATED EXAMPLE: JS FIDDLE
Hope it will helps you.
Regards, Dmitry Zaets.

- 3,289
- 1
- 20
- 33