I've found questions like this: Backbone model .toJSON() doesn't render all attributes to JSON by model.set
But they were not solved.
I have a similar problem. Here's a sample code:
Animal = Backbone.Model.extend({
...
...,
initStats:function(){
this.attributes.stats = [];
var that = this;
var type = new Species();
type.store.findAll(type, function(tx, res){
var base = JSON.parse(res.rows.item(that.attributes.did-1).value);
that.set("name",base.name);
that.set("text", base.text);
return that;
}, function(tx,err){console.log(err)}, "");
}
});
type.store.findAll is a function in Species class that connects to DB and return all species.
And on another page I do:
mym = new Animal();
mym.initStats().save(); //see below
mym.store.findAll(mym, function(tx,res){
for(var i = 0;i < res.rows.length; i++){
console.log(res.rows.item(i).value);
}
}, function(tx,err){console.log(err)}, "");
Again, Animal.store.findAll is a function to find all animals. Animal.save() has its SQL generation function as follows:
create: function (model,success,error,options) {
//when you want use your id as identifier, use apiid attribute
if(!model.attributes[model.idAttribute]) {
// Reference model.attributes.apiid for backward compatibility.
var obj = {};
if(model.attributes.apiid){
obj[model.idAttribute] = model.attributes.apiid;
delete model.attributes.apiid;
}else{
obj[model.idAttribute] = guid();
}
model.set(obj);
}
var colNames = ["`id`", "`value`"];
var placeholders = ['?', '?'];
var params = [model.attributes[model.idAttribute], JSON.stringify(model.toJSON())];
console.log(model);
console.log(model.toJSON());
this.columns.forEach(function(col) {
colNames.push("`" + col.name + "`");
placeholders.push(['?']);
params.push(model.attributes[col.name]);
});
var orReplace = WebSQLStore.insertOrReplace ? ' OR REPLACE' : '';
//console.log("INSERT" + orReplace + " INTO `" + this.tableName + "`(" + colNames.join(",") + ")VALUES(" + placeholders.join(",") + ");");
this._executeSql("INSERT" + orReplace + " INTO `" + this.tableName + "`(" + colNames.join(",") + ")VALUES(" + placeholders.join(",") + ");", params, success, error, options);
console outputs are:(I'll just put stringified JSON)
s {cid: "c575", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object…}
{"name":null, "text":null, "id":"5475b1e0-9d6c-48d1-e090-cb84e4e84ca6"}{"name":null, "text":null, "id":"5475b1e0-9d6c-48d1-e090-cb84e4e84ca6"}
id is generated by other functions in the model. The first line is the model(before toJSON), the second line is a JSON object, the third line is SQL select result. Three lines in actual printout order.
I don't know why the name and text are null. In the console output, they all have value under s.attributes.