andrescabana86
andrescabana86

Reputation: 1788

update view model with ajax dom elements

Im working with knockout, i want to update a div content with ajax this is the code:

$.ajax(
    {
        type: 'GET',
        url: url,
        success: function(datos)
        {
            $(div).empty();
            $(div).append(datos);
        },
        error: function(xhr,tipo)
        {
            alert('Ajax error!');
        }
    })

the ajax gives me this div appened with jquery to a "div"

<div class="span12">
    <a data-bind="click:transicion.bind($data,'/newPage')" class="w8-button green pull-left">Cargar un nuevo Producto</a>
</div>

the problem is that knockout didnt recognize the data-bind of the new element... can anybody explain me a better solution??

tnx!!

Upvotes: 0

Views: 114

Answers (1)

go-oleg
go-oleg

Reputation: 19480

At some point in your code after your page has loaded and you have created your view model, you are calling ko.applyBindings() and passing in your view model.

When your ajax call comes back and you append the contents to a div, knockout doesn't automatically know about it. You need to call ko.applyBindings() passing in your view model and the element you want knockout to look for data-bind attributes in:

ko.applyBindings( yourViewModel, document.getElementById( "yourDivId" ) )

Or you can use any other way of getting your div (like jQuery selectors ).

Here is the documentation on the ko.applyBindings() behavior.

Upvotes: 1

Related Questions