I’m using KnockoutJS…
I have an observableArray of movies in my viewModel. The array is updated when a user searches for a movie by title, so a typical json response that would be pushed into the array would look like this…
{data : [{
Id: 12345,
Title: 'Movie1',
Year: 2010,
Character: [{
Name: 'Character1',
Person: { Id: 1, Name: 'Person1' }
},{
Name: 'Character2',
Person: { Id: 2, Name: 'Person2' }
}],
UserMovies: [{
Id: 8
IsWatched: false,
Rating: 3.5,
UserId: 'e1e9c075-1ded-4e7d-8d30-d5d1fbd47103'
}]
}]}
The UserMovies property of each movie represents information specific to that user, like their personal rating or if they’ve watched the movie yet, etc.
I give the user the ability to “Add” the movie to their collection in the database. When they add the movie to their collection a json response is sent back that has the updated UserMovies property for that movie.
I’m trying to update just that property and then have it persist to the knockout template. Here’s my current viewModel…
function viewModel() {
// private properties
var self = this;
// public properties
self.movies = ko.observableArray([]);
self.searchValue = ko.observable();
// public operations
self.search = function () {
self.isLoading(true);
$.getJSON(arguments[0].action, { name: this.searchValue() }, function (data) {
self.movies(data);
});
};
self.add = function (movie) {
$.ajax({
type: 'POST',
url: arguments[1].currentTarget.attributes[1].value,
data: JSON.stringify({ movie: movie }),
contentType: 'application/json',
dataType: 'json',
success: function (data) {
// how to just update UserMovies property and persist to template for the given movie?
}
});
};
}
ko.applyBindings(new viewModel());
I’m not sure how to update the property but as far as persisting the data to the knockout template I think it’s because the UserMovies property of each movie isn’t itself an observable so if it’s updated nothing will automatically change in the template.
I’ve been reading about the mapping plugin which would make every property an observable. This may fix my persistance problem but I’m still unsure how to update just the UserMovies property whether it’s in an observableArray or via the mapping plugin.
Update
I’ve created a fiddle using the mapping plugin. If I return the whole movie instead of just the UserMovies property it will be much easier to update an item in the array. I’m having some issues getting it to work though and I’m struggling to figure out how to create a mapping for ‘key’ against the UserMovies property. http://jsfiddle.net/cmBd9/3/
I was able to get it to work with the mapping plugin using mapping options. I set the key for
UserMoviesto be the Id of eachUserMovieso whenfromJS()is called it will look to the Id of eachUserMovieto tell whether to update or add a newUserMovieHere’s my updated code…