I have bound a DOM element to a viewModel using knockout. When I change a property on the underlying model it changes the DOM - all ok.
However, is there a way to get to the bound DOM element so I can add a class to it when the underlying model gets updated externally?
I have used custom binding which gives me access to the DOM element but I was wondering if there is a simpler way directly from the viewModel's bound property?
Thanks
sample code (TypeScript)
SetMyCell(row: number, newValue: any) {
var ditem = this._DataItems[row];
// update the actual value
ditem.Producer(newValue);
// Now I wish to decorate the DOM item this Producer property is
// bound to with a class. How to go about that?
}
unwrapObservable(item) Looking at the code, that call basically checks to see if item is an observable. If it is, return the value(), if it's not, just return the value.
For example, ko. applyBindings(myViewModel, document. getElementById('someElementId')) . This restricts the activation to the element with ID someElementId and its descendants, which is useful if you want to have multiple view models and associate each with a different region of the page.
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.
Binding Values The binding value can be a single value, literal, a variable or can be a JavaScript expression.
You can abuse the visible binding for example to execute a function passing the $element and $data.
<span data-bind="visible: func1($element, $data)">Test span</span>
look at this fiddle
I know you mention above that you don't want to use a custom binding but i still want to point out this option. although i am using a custom binding the logic for modifying the element will still happen in the viewmodel when the external changes happen.
ko.bindingHandlers.widget = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var elemObservable = valueAccessor();
if (ko.isObservable(elemObservable)) {
elemObservable(element);
}
}
};
var vm = function () {
var self = this;
.....
self.spanElement = ko.observable();
self.btnClick = function (){
var elem = self.spanElement();
$(elem).html("This is the span element");
};
......
};
and the html would be
<button data-bind="click: btnClick">change element text or something else</button>
<span data-bind="widget: spanElement"></span>
I have updated the fiddle so you can see it in action
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