Many:Many with YUI and Model-Relate
MVC or MVP? I'm really not sure…
Tue 01 May 12
The YUI MVC framework allows you to related models (with the Model-Relate plugin), however many:many relationships aren’t part of the package. Here’s one way to go (here’s a JsFiddle to play with):
YUI({}).use('gallery-model-relate', function(Y) { // example using recuiters and candidates, recruiters can have // many candidates and vice versa Y.RecruiterModel = Y.Base.create('recruiterModel', Y.Model, [Y.ModelRelate], {}, { ATTRS: { name: {} }, RELATIONSHIPS: { candidates_map: { type: 'toMany', key: 'id', relatedModel: 'RecruiterToCandidateModel', relatedKey: 'recruiterFK' } } }); Y.CandidateModel = Y.Base.create('candidateModel', Y.Model, [Y.ModelRelate], {}, { ATTRS: { name: {} }, RELATIONSHIPS: { recruiters_map: { type: 'toMany', key: 'id', relatedModel: 'RecruiterToCandidateModel', relatedKey: 'candidateFK' } } }); Y.RecruiterToCandidateModel = Y.Base.create( 'recruiterToCandidateModel', Y.Model, [Y.ModelRelate], {}, { ATTRS: { recruiterFK: {}, candidateFK: {} }, RELATIONSHIPS: { recruiters: { type: 'toOne', key: 'recruiterFK', relatedModel: 'RecruiterModel', relatedKey: 'id' }, candidates: { type: 'toOne', key: 'candidateFK', relatedModel: 'CandidateModel', relatedKey: 'id' } } }); var acme = new Y.RecruiterModel({ id: 1, name: 'ACME Recruiters' }); var foo = new Y.RecruiterModel({ id: 2, name: 'Foo Recruiters' }); var joe = new Y.CandidateModel({ id: 1, name: 'Joe McFoo' }); // TODO add these to a modelList, add the modelList as an // eventTarget for candidate and recruiter modelLists and // send updates between the two lists from this one new Y.RecruiterToCandidateModel({ recruiterFK: acme.get('id'), candidateFK: joe.get('id') }); new Y.RecruiterToCandidateModel({ recruiterFK: foo.get('id'), candidateFK: joe.get('id') }); Y.log('Joe\'s Recruiters:'); Y.log('------------------'); // returns a modelList of linking models, which we then // loop over joe.getRelated('recruiters_map').each(function(m, i) { Y.log(m.getRelated('recruiters').get('name')); }, this); Y.log(' '); Y.log('ACME\'s Candidates:'); Y.log('------------------'); // returns a modelList of linking models, which we then // loop over acme.getRelated('candidates_map').each(function(m, i) { Y.log(m.getRelated('candidates').get('name')); }, this); });
