Question

When I fetch models or collections from the server, I am not able to access properties of the model unless I stringify then re-parse. Presumably the models themselves have some extra overhead from backbone.js? Note that in the below code I can perform stringify/parse sequentially, which is supposed to give the same result as I started with. However, clearly I have killed off some superfluous info by performing these two steps because my model's properties are now exposed differently from before. Surely I do not need to go through these two steps to access my model properties, right?

Eg.  
thismodel = /// assume this came from server fetch
alert(thismodel.name);    // DOES NOT WORK - undefined

jsonmodel = JSON.stringify(thismodel);
var providerprefslistJSON = jQuery.parseJSON(jsonmodel);
alert(providerprefslistJSON.name);     // WORKS
Was it helpful?

Solution

Backbone Model objects are not plain old JavaScript objects. They keep their attributes in an internal hash. To access the name attribute you can either do this:

alert(thismodel.attributes.name);

Or better yet use the get() method:

alert(thismodel.get("name"));

The reason it works when you convert the model to JSON and then back again is because JSON.stringify calls the toJSON() method, which creates a JSON string from the internal attributes hash, meaning when you parse that string you get a plain old JavaScript object - which is not the same as a Backbone Model object.

OTHER TIPS

First, are you trying to access the property of the model or response?

From alert(thismodel.name) it would seem that you're going for a property of the model not the attribute. If you're looking for the model attribute then perhaps you want alert(this.model.get('name'))

If you're indeed going for model.name, then basically the problem may lie in how you're parsing the data. Say for example the JSON from your server is like this {'name':'Jimmy'}.

While the model.response the raw JSON sent has "Jimmy" namespaced under object.name, Backbone will automatically take that and turn it into a model attribute unless instructed otherwise (e.g. modelObj.attributes.name) at which point you'd use the get() function.

You should be able to access model data fairly simply if everything works.

E.g. Fetch

var model = new MyModel();
    model.id = 1;
    model.fetch({
        success: function(model, response) {
            console.log(model.get('name'));  // The model name attribute
            console.log(response.name);  // The RAW response name property
        }
    });

Or maybe your server isn't sending the data back as JSON data. Is the server response content-type="application/json" ?

Some things to check.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top