0

Let's say I have an observableArray in my viewModel called movies that contains data similar to this...

[{
    Id: 12345,
    Title: 'Movie1',
    Year: 2010,,
    UserMovies: [{
        Id: 8
        IsWatched: false,
        Rating: 3.5,
        UserId: 'e1e9c075-1ded-4e7d-8d30-d5d1fbd47103'
    }]
},{
    Id: 12345,
    Title: 'Movie2',
    Year: 2010,,
    UserMovies: [{
        Id: 11
        IsWatched: false,
        Rating: 4,
        UserId: 'e1e9c075-1ded-4e7d-8d30-d5d1fbd47103'
    }]
}]

I know I can use the mapping plugin and every property will become an observable but what if I only want to make one property observable. Is it possible to make just UserMovies an observableArray, and how would I go about doing that?

2 Answers 2

1

You can specify properties in your objects that you want the ko.mapping plugin to map as plain values like so:

var mapping = {
    'copy': ["propertyToCopy"]
}
var viewModel = ko.mapping.fromJS(data, mapping);

You will need to do this for each model you have defined. It can be quite tedious and depending on the nature of your model, might very well defeat the major benefit of the plugin in the first place (not having to redefine your data model client-side).

Sign up to request clarification or add additional context in comments.

Comments

0

You can try to loop each item in your array, store the UserMovies in a temp variable, override UserMovies with an observable array. Something like this:

for (var i = 0; i < movies().length; i++) {
        var tempUserMovies = movies()[i].UserMovies;
        movies()[i].UserMovies = ko.observableArray();
        for (var j = 0; j< tempUserMovies.length; j++) {
            movies()[i].UserMovies.push(tempUserMovies[j]);
        }
    }

A little ugly method, but you should get the general idea from it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.