I was having issues idAttribute causing .save() to report a bad isNew() value when I wanted to add a new model to the server with the ID pre-populated.. which led me to keep it off and set the model.id manually.
Here’s my View:
RecordListItemView = Backbone.View.extend({
initialize:function () {
var record = this.model.attributes;
if (record.user_id) {
this.model.id = parseInt( record.user_id );
record.id = parseInt( record.user_id );
// Added this so ID would show up in model and .attributes
}
this.model.bind("change", this.render, this);
this.model.bind("destroy", this.close, this);
},
render:function (eventName) {
$(this.el).html(this.template(this.model));
console.log(this);
return this;
}
});
At this point I am unable to retrieve any records using collection.get(id), though I am able to do so via collection.getByCid(cid) just fine.
Here’s my console.log output:
d
$el: e.fn.e.init[1]
cid: "view36"
el: HTMLLIElement
model: d
_callbacks: Object
_escapedAttributes: Object
_pending: Object
_previousAttributes: Object
_silent: Object
attributes: Object
id: 15
user_id: "15"
user_name: "Test"
__proto__: Object
changed: Object
cid: "c8"
collection: d
id: 15
__proto__: x
options: Object
__proto__: x
Is there a way to fix collection.get(id) without having to alter my database to include an id field? (Currently using user_id as the pk)
As posted below by Benjamin Cox: (with parseInt() removed as unnecessary)
Replace
this.model.id = record.user_id;
with
this.model.set({ id: record.user_id });
.. to avoid bypassing the Model’s change event which in turn updates the Collection’s internal_byId[] array.
After testing both, I wound up using mu is too short’s parse suggestion..
parse: function(response) {
return {
id: response.user_id,
user_id: response.user_id,
user_name: response.user_name
};
}
The reason that calling collection.get(id) doesn’t find your model is that you’re bypassing Backbone’s event mechanism when you do:
If you do this instead:
then the Backbone event code in the model’s set() method will fire a “change:id” event. The collection, in turn, listens for this event and updates it’s internal _byId[] array variable. Later, when you call collection.get(id), this array is used to search for the matching model.