flynfish
flynfish

Reputation: 5867

Backbone.js model

Am I doing something completely wrong here? I am populating a backbone model from a jsonp response. When I view the first console statement in firebug, the 'current' object has 'icon' under attributes. However, when printing console.log(current.has("icon")) it returns false and therefore current.get("icon") will return undefined.

var Current = Backbone.Model.extend({
    url: "A_valid_url",
    sync: function(method, model, options) {
        options.timeout = 10000;
        options.dataType = "jsonp";

        return Backbone.sync(method, model, options);
    },
    parse: function(response, xhr) {
        return response.current_observation;
        }
});

var current = new Current({test: "blah"});
    current.fetch();
    console.log(current);//under attributes there is a "icon"
    console.log(current.has("icon")); //false
    console.log(current.get("icon")); //undefined
    console.log(current.has("test")); //true

Upvotes: 0

Views: 1241

Answers (2)

Thilo
Thilo

Reputation: 262504

current.fetch();
console.log(current);//under attributes there is a "icon"
console.log(current.has("icon")); //false
console.log(current.get("icon")); //undefined
console.log(current.has("test")); //true

Is that the real code? If so, all this logging will take place before the asynchronous loading of the data has completed. You need to do this in a callback (or bind to the "change" event on the model).

console.log(current);//under attributes there is a "icon"

That the data still shows up in the console log is a "feature" of the log when you log objects (instead of strings): It will only pass a reference, and the actual printing happens later (when the data might already be loaded).

Upvotes: 0

timDunham
timDunham

Reputation: 3318

fetch() is asynchronous. Try the following:

var current = new Current({test: "blah"});
current.fetch({
    success: function(){
        console.log(current.get("icon"));
    }
);

Upvotes: 2

Related Questions