I have an observable array, bound to the list of contenteditable divs. I have an 'add' button. On click I add an object to array and want to give focus to the corresponding div.
<ul id='list' data-bind="foreach: array">
<li>
<div contenteditable="true" data-bind="text: $data.text"></div>
</li>
</ul>
<div id="add">+</div>
javascript
var viewModel = {
array: ko.observableArray([])
};
ko.applyBindings(viewModel, document.getElementById('list'));
document.getElementById('add').onclick = function (evt) {
var newObject = {text : ''};
viewModel.array.push(newObject);
// give focus to the newly created div
};
It is possible to get the observable data having DOM element ko.dataFor(dom)
. How to get DOM by data?
http://jsfiddle.net/5rxdZ/
Thanks
To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.
The "data-bind" attribute contains a collection of comma-separated options for how Knockout should bind a view model property to an HTML element. The two examples above use only a single option: the "value" binding handler.
KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.
In a data binding process, each data change is reflected automatically by the elements that are bound to the data. The term data binding is also used in cases where an outer representation of data in an element changes, and the underlying data is automatically updated to reflect this change.
You can't get the DOM element from the data itself. In this scenario though, you could use the hasfocus
binding to move focus to the new element. Docs here: http://knockoutjs.com/documentation/hasfocus-binding.html
Even just placing hasfocus: true
on a new element will do the trick.
Otherwise, if you don't want the focus to be applied for the initially rendered elements, then you could pass in a flag for the newly created element like:
<ul id='list' data-bind="foreach: array">
<li>
<div contenteditable="true" data-bind="hasfocus: $data.focused, text: $data.text"></div>
</li>
</ul>
<div id="add">+</div>
view model:
var newObject = {text : '', focused: true};
viewModel.array.push(newObject);
Sample: http://jsfiddle.net/rniemeyer/jnHK8/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With