I have two datasets returning to two different backbone collections each using a different model. Both models share a field that could be used to link them.
The second ajax call is made after the first has loaded, as a sort of pre-loader.
Upon the second collection being successfully fetched (on ‘reset’ event), I’d like to somehow bind/join models (or simply copy the JSON in, it’s a one way read only thing) with the same value for the common field to a property on each of the other models where there is a match.
Just re-read that and I don’t think it reads very well, but hopefully you understand…
Collection 1
[
{
foo: 'text',
bar: 'xxx'
},
{
foo: 'text',
bar: 'yyy'
}
]
Collection 2
[
{
prop1: 'a',
prop2: 'b',
bar: 'xxx'
}
]
Whether the raw data is added or a binding established, I desire the collection 1 JSON to be able to read like this
[
{
foo: 'text',
bar: 'xxx',
prop1: 'a',
prop2: 'b',
},
{
foo: 'text',
bar: 'yyy'
}
]
Or
[
{
foo: 'text',
bar: 'xxx',
extraProps: {
prop1: 'a',
prop2: 'b'
}
},
{
foo: 'text',
bar: 'yyy'
}
]
Any help greatly appreciated. All the ways I’m thinking it could be achieved don’t seem very backboney
PS: I’ve just noticed a backbone-relational tag while tagging this question. I’ll have a read there and post back if I see anything useful. It’s quite a hard question for form a good search phrase for…
EDIT
Thanks for the replies, I popped away to write a quick script and noticed that I had some replies before I’d even finished. Anyway, just for reference I will add my initial, perhaps quite bodgy script. Please ignore the fact that mailing/mailing_id don’t have the same field name, I am not in control of the data sources at this time…
<script>
var matches = 0;
_.each(clicks.models, function(click) {
_.each(mailshots.models, function(mailshot){
if(click.get('mailing') == mailshot.get('mailing_id')){
matches++;
click.set('subject',mailshot.get('mailing_subject'));
}
});
});
if(matches) clicks.trigger('reset');
</script>
Anyway, that works. But I’m just going to test the first reply and have a glance at backbone-relational. Might be more than I need now but looks interesting…
when the two collections have been loaded you can do something like this
and to be more dynamic