Nahydrin
Nahydrin

Reputation: 13517

JavaScript: Backbone.js fetch json and load it into a collection of models?

So far i have the following code, but it doesn't seem to be working, and I don't know when the asynchronous fetch is completed:

var item = Backbone.Model.extend({
    defaults: {
        id: 0,
        an_id: 0,
        strval: null,
        th_id: 0,
        text: null
    },
    url: 'page.php',
    options: {
        success: function(data) {
            alert('s: ' + dump(data));
            // the dump function is my way of dumping objects into a string,
            // use console.log if you want, as I have that disabled
        },
        error: function(x, t, e) {
            alert('e: ' + t + ', ' + e);
        }
    }
});

var coll = Backbone.Collection.extend({
    model: item
});

var options = new Options();
Backbone.sync("create", coll, item.options); // 'undefined' is not an object (evaluating c.url) in backbone-min.js

Update

I have modified the original code to what I have now, and the backend can now tell the difference between New, Update, Save and Delete requests.

I still cannot find out how to populate the collection coll.

Upvotes: 1

Views: 941

Answers (2)

Lucas
Lucas

Reputation: 3491

you can add a success handler to your fetch call. try this:

coll.fetch({
        success: function() {
            alert("success");
            console.log(coll.toJSON());
        },
        error: function(){
            alert("error")}
    });    

Upvotes: 0

Scott Weinstein
Scott Weinstein

Reputation: 19117

Backbone.Collection is for keeping multiple items - you seem to be trying to have your Collection "inherit" from your model, which isn't the right approach.

Collections are ordered sets of models. You can bind "change" events to be notified when any model in the collection has been modified, listen for "add" and "remove" events, fetch the collection from the server, and use a full suite of Underscore.js methods.

Upvotes: 1

Related Questions