4imble
4imble

Reputation: 14416

How to efficiently persist Creates / Updates / Deletes to data when using KnockoutJs?

I have been playing round with knockoutjs and so far i have in my view a list of items.

I can update, create and delete these using various buttons.

I also have the ability to save, when this happens, my viewmodel gets sent to the server as json and i deal with it there.

I am worried that at this point it gets slightly inefficient.

I currently have a foreach loop that looks at each of the items.

I then query for each item 1 at a time, if it doesnt exist i assume it's new and add it, if it has a _destroy = true, i delete it and finally if it does exist i just replace it with what got sent back from the server this is where updates are persisted.

This seems quite wasteful to me.

1) i am sending every row back from the view.

2) i am then retrieving every row when it gets to the server even if nothing has changed.

Is there a way of flagging a row for "attention" and only sending those rows back to the server.

For example, lets say i have 4 rows displaying in my view. I add a new one to the viewmodel, edit an existing one and delete another.

I would like to only send those 3 rows back to the server... ignoring the ones that are unchanged.

Maybe i could add and check for specific flags similar to how _destroy works currently?

So Adding items would add a _create flag and editing would add an _update flag etc.

Sorry, I hope this doesnt seem too much like waffle.

How would you suggest dealing with this?

Thanks, Kohan.

Upvotes: 3

Views: 995

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

Here is a sample that might help: http://jsfiddle.net/rniemeyer/gfkej/

It is based on this: http://www.knockmeout.net/2011/05/creating-smart-dirty-flag-in-knockoutjs.html

The basic idea is to add a dirty flag to each item, then create a dependentObservable that represents all of the dirty items. When filtering for dirty items, this also checks to see if _destroy is set on the item. When adding a new item, the dirty flag let's you pass in a boolean to indicate that it should immediately be considered dirty. In my example, I just pass id === 0, since I am initializing the id to 0 for any new items.

Upvotes: 2

Related Questions