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!
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!
Share Improve this question asked Oct 3, 2011 at 15:37 NickGreenNickGreen 1,75217 silver badges36 bronze badges 1-
1
If I understand correctly, no. You will still need to use
data-bind
inline. – namuol Commented Oct 3, 2011 at 15:52
2 Answers
Reset to default 6Your 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.
Try using a dependant observable
var viewModel = {
price: ko.observable(109)
}
viewModel.priceElement= ko.dependantObservable(function(){
viewModel.price();
return jQuery("#price");
})
This will update everytime you change the price.