GeekDaddy
GeekDaddy

Reputation: 619

Backbone fetch collection but it won't save

I'm building file browser with backbone and heave problem with saving fetched collection. JSON response from server is triggered and looks like this:

[{"name":".","type":"d"},{"name":"..","type":"d"},{"name":"bolt","type":"d"},{"name":"crm","type":"d"},{"name":"crm_backup","type":"d"},{"name":"parse.php","type":"f"},{"name":"places.txt","type":"f"},{"name":"pyrocms","type":"d"},{"name":"test.php","type":"f"},{"name":"time_test.php","type":"f"},{"name":"wordpress","type":"d"}]

I've checked parse in my collection and it has 11 elements. but when I output my collection it's empty. Here is collection code:

var File = Backbone.Model.extend({
    defaults: {
    'name': '',
    'type': 'f'
    }
});

var FilesCollection = Backbone.Collection.extend({
    model: File,
    url: '<?php echo site_url('files/dir/'); ?>',
    parse: function(response) {
    console.log("In prase " + response.length);
    return response[0];
    }
});

var files = new FilesCollection();
files.fetch({data: {dir: '/home/stamp/public_html/'}}, {rest: true});
console.log(JSON.stringify(files));

Upvotes: 0

Views: 234

Answers (2)

Ming
Ming

Reputation: 4300

The fetch is async function. You should call console.log in the success handler of fetch so that you can see output after the data is loaded.

file.fetch({
    success: function() {
        console.log(...);
    },
    ...
})

BTW, according to the doc, Fetch should only take 1 argument as a hash:

collection.fetch([options])

Upvotes: 1

mu is too short
mu is too short

Reputation: 434805

From the fine manual:

parse collection.parse(response, options)

[...] The function is passed the raw response object, and should return the array of model attributes to be added to the collection.

Looks like your response is exactly the array of objects that your collection wants to see but you're returning a single object:

return response[0];

The collection will be looking for an array, won't find one, and the result is that your fetch call does nothing. Your parse should probably return the whole response as-is:

return response;

Or, if you don't need it for debugging, just drop the parse method from your collection, the default implementation should be sufficient for your needs.

Upvotes: 0

Related Questions