Created
October 19, 2015 05:44
-
-
Save swaroopsm/8069f7f019a7a49d20c0 to your computer and use it in GitHub Desktop.
Backbone has-many
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var BaseModel = Backbone.Model.extend({ | |
_relations: { | |
hasOne: {} | |
}, | |
parse: function(data) { | |
var model; | |
if(_.isFunction(this.hasOne)) { this._createRelation('hasOne'); } | |
if(this._hasRelationType('hasOne')) { this._setRelationOnModel('hasOne', data); } | |
return data; | |
}, | |
_hasRelationType: function(_type) { | |
return typeof this._relations[_type] !== 'undefined'; | |
}, | |
// Create a relation | |
_createRelation: function(_type) { | |
var relation = this.hasOne(); | |
_.each(relation, function(obj) { | |
var data = _.clone(obj), | |
modelObj = new obj['className']; | |
_.extend(data, { modelObj: modelObj }); | |
this._relations[_type][data['key']] = data; | |
}.bind(this)); | |
}, | |
// TODO | |
// Needs refactoring for `hasMany` collection that will create collection | |
// of models | |
// Set relation data on the model | |
_setRelationOnModel: function(_type, data) { | |
var model, | |
relations = this._relations[_type], | |
reltion; | |
for(var key in relations) { | |
relation = relations[key]; | |
model = relation['modelObj']; | |
model.set(_.clone(data[relation['key']])); | |
data[relation['name']] = model; | |
// Delete the data for this relation that came from the server | |
// Be cautious / need to find a better solution | |
delete data[relation['key']]; | |
} | |
return data; | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var UserModel = BaseModel.extend({ | |
hasOne: function() { | |
return [ | |
{ name: 'admin', className: oudux.store.UserModel, key: 'original_admin' }, | |
{ name: 'weblink', className: oudux.store.WeblinkModel, key: 'primary_weblink' } | |
]; | |
}, | |
url: function() { | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment