简体   繁体   中英

Backbone.js I want to do model.fetch and have the data reflected back in the source collection

I'm really looking to understand the concept here (as opposed to receiving a code solution).

I have a collection that was populated by a fetch. I want to take a single model from the collection, fetch the latest data from the server, then have the data that came from the server put back into the collection's version of the model.

Restating with terms from Backbones docs: I'd like to ensure that I have the latest server state. I won't care about "change" events that are triggered because I'm expecting the model to change almost every time. Fetch resets the model's state from the server , so I should just be able to do something like this, right?:

[pseudo]

model.fetch();

in the fetch success handler call one of these:

this: collection.add(model, {merge: true});
..or: collection.set(model);         

If that's not enough to accomplish my task, what concept am I missing?

EDIT - adding details

I call fetch():

controller.model.fetch({
    success: function(model){
        console.log(model);
        updateView();
    },
    error: function(){
        console.error('error fetching contact model');
    }
});

The success callback is fired after the fetch(). I can see that the model has new data and that the Image has been modified and needs to be re-downloaded:

ImageDateLastUpdated已更改

When I call my function that updates the view, nothing changes visibly because the latest data is still in the "changed" member...it seems. What's the standard way to get the latest data from "changed" into the "attributes" member? And is this made clear in the documentation?

There is no "collection's version of the model"

If you refer to a model in the collection and call fetch, there's nothing else needs to be done. This model is already a part of the collection and the new data will populate.

Objects in javascript are passed by reference, so unless you clone it seeing something like model.clone() , you are referring to the same object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM