Add to list on enter knockoutjs
-
30-06-2021 - |
Question
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?
Solution
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));
OTHER TIPS
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.
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>
try it like this
basically your "self" was a html element, not your view model
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.