NickGreen
NickGreen

Reputation: 1752

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!

Upvotes: 6

Views: 2217

Answers (2)

Mark Robinson
Mark Robinson

Reputation: 13278

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.

Upvotes: 6

ryudice
ryudice

Reputation: 37446

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.

Upvotes: 2

Related Questions