I'm using KnockoutJS to update the DOM if a JS value is changed (Knockout gives us this functions).
A default Knockout viewModel looks something like the following block:
Javascript:
var viewModel = {
price: ko.observable(109)
}
Html:
<span data-bind="text: price"></span>
Now when the price changes, the view is automatically updated by Knockout.. But what I'd like to have is the following:
var viewModel = {
price: ko.observable(jQuery("#price"))
}
<span id="price">99.00</span>
So, I want to bind a DOM element to my viewModel. The price attribute in the model is initialized with the value 99.00. When the price is changed (in Javascript) the DOM value of #price should also be updated.
I hope the question is clear to you guys.
Thanks a lot for your time!
Your view model should be initialized as follows:
var viewModel = {
price: ko.observable(jQuery("#price").text())
}
<span id="price" data-bind="text: price">99.00</span>
After that you should be using javascript to update the model, not the view. So instead of:
jQuery("#price").text('some new value');
.. you should be writing...
viewModel.price('some new value');
This approach would be more in keeping with the MVVM pattern.
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