Reputation: 26291
Is it possible to get associated input for property? I need to focus input after model is added to array:
var newItem = new ChildModel();
this.childItems.push(newItem);
// and then something like this:
newItem.observableProperty.focusInput();
Upvotes: 1
Views: 72
Reputation: 7194
You could look at the hasfocus
binding. If you are willing to add a selected
property to your ChildModel
you can do something like this: http://jsfiddle.net/jearles/sZnbU/
When I push an item into the observable array I set its selected
property to true
. This gives it focus. Each row also has a Select
button to allow you to select it.
When I add a new item I log the items so you can see the selected
property changing. Finally, if you click in the input textbox, giving it focus, and then click Log
and you'll see no "selected" items.
--
<span>
New Item: <input data-bind="value:newItem" />
<button data-bind="click: addItem">Add</button>
<button data-bind="click: logItems">Log</button>
</span>
<div data-bind="foreach: items">
<p>
<input data-bind="value: text, hasfocus: selected" />
<button data-bind="click: selectItem">Select</button>
</p>
</div>
--
var ChildItem = function(text) {
var self = this;
self.text = ko.observable(text);
self.selected = ko.observable(true);
self.selectItem = function() {
self.selected(true);
}
};
var ViewModel = function() {
var self = this;
self.items = ko.observableArray();
self.newItem = ko.observable('');
self.addItem = function() {
if (self.newItem().length > 0) {
self.items.push(new ChildItem(self.newItem()));
self.newItem('');
self.logItems();
}
};
self.logItems = function() {
console.log(ko.toJSON(self.items));
}
}
ko.applyBindings(new ViewModel());
Upvotes: 1