Reputation: 259
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?
http://jsfiddle.net/someyoungideas/WWpcC/
Upvotes: 1
Views: 2201
Reputation: 21
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>
http://jsfiddle.net/jnewcomb/umf3f/1/
Upvotes: 1
Reputation: 3277
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.
Upvotes: 0
Reputation: 44316
try it like this
basically your "self" was a html element, not your view model
Upvotes: 0
Reputation: 18061
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));
Upvotes: 0
Reputation: 34369
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.
Upvotes: 1