Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind existing DOM elements to a KnockoutJS viewModel

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!

like image 249
NickGreen Avatar asked Oct 03 '11 15:10

NickGreen


1 Answers

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.

like image 103
Mark Robinson Avatar answered Sep 18 '22 17:09

Mark Robinson