In the context of a Collection, I want to retrive a model instance based on some object containing model data, but I don’t want to hard code the idAttribute.
Backbone makes things easy when you already have a model instance, you can just access its .id property and it sorts things out, but I can’t seem to find a way of going the other way, short of creating a instance of a model just to get at its idAttribute.
For example:
var Cat = Backbone.Model.extend({
defaults: {
name: '',
age: null
},
idAttribute: 'name'
});
var PushCollection = Backbone.Collection.extend({
initialize: function () {
coll = this;
somePushConnection.on('deleted', function (deleted) {
_.each(deleted, function (obj) {
// obj being something like: {name: 'mittens', age: 302}
var model = coll.get(obj[coll.model.idAttribute]); // Can't do this!
if (model) { model.destroy(); }
});
});
}
});
var Cats = PushCollection.extend({
model: Cat
});
You should be able to access it via the model’s prototype:
Or in your sample code