Backbone Collection Sync

Asked By: Anonymous

I’m trying to figure out how to keep a collection of models in sync with my server. At the moment, my code looks like this, but it’s clearly got a few problems…

var myCollection = Backbone.Collection.extend({
    url: '/api/block',

    ...

    sync: function() {
        _.each(this.models, function(model) {
            model.sync('create', model);
        });
    }

});

At the moment, when I call sync on my collection, it iterates through all of the models, and calls sync on each of them. I’m surprised, firstly that this isn’t the default behaviour of a Backbone.Collection.sync method. Or am I misunderstanding what ‘syncing collections’ should do?

Secondly, my model.sync('create', model); line is a bit odd. Why do I have to pass model in when I’m calling the method on the model itself? Also, I’m manually calling ‘create’ which is clearly wrong. Shouldn’t ‘sync’ be aware of whether it should created or update?

And also, shouldn’t ‘sync’ be intelligent enough to call ‘delete’ on any models which have been removed from my collection?

I’m guessing I should be looking at customising the sync method on my model, but I’m still confused as to what I’m doing that is unusual that would require me to customise these sync methods.

I feel like I’m missing a fairly big point about sync.


Solution

Answered By: Anonymous

For the record, there isn’t really an answer to this question, because it’s an invalid question! I misunderstood what ‘sync’ was for. I am now using save as KiT O has pointed out.

Thanks.

techinplanet staff

techinplanet staff


Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno