George Mauer
George Mauer

Reputation: 122212

Does knockout.js expose change events on the model?

I would like to watch the ViewModel for any changes to any properties. Is this possible with knockout.js?

Upvotes: 1

Views: 521

Answers (2)

Tom W Hall
Tom W Hall

Reputation: 5283

Ryan Niemeyer has an excellent walk-through on implementing a generic dirty flag for your Knockout view models:

http://www.knockmeout.net/2011/05/creating-smart-dirty-flag-in-knockoutjs.html

The basic approach arrived at is to use ko.toJSON to compare JSON representations of the entire view model to determine if any property value has changed, which is simple and powerful, so long as you keep in mind that if your view model becomes large and nested this may become an expensive operation.

Upvotes: 2

Max Shmelev
Max Shmelev

Reputation: 3770

How about this code:

function subscribeToModelChange (viewModel)
{
    for (var prop in viewModel)
    {
        if (ko.isObservable (viewModel[prop])
            viewModel[prop].subscribe (function (newValue) { onModelChanged (viewModel[prop], newValue); });
    }
}

function onModelChanged (observable, newValue)
{
    alert ("Hooray!");
}

You'll be notified about changes to any knockout observable in your view-model.

Upvotes: 1

Related Questions