How can I set an attribute on specifically the last child view of a Marionette CollectionView?

17 Views Asked by At

I have a Marionette CollectionView with a child view:

const BreadcrumbListView = Marionette.CollectionView.extend({
...
childView: BreadcrumbView,
...
})

const BreadcrumbView = Marionette.View.extend({...})

I want to set the aria-current HTML attribute for the last child in that collection view. How can I do that?

I tried setting it before initializing the CollectionView, like this:

detailCollection = new Backbone.Collection(models);
detailCollection.last().set('aria-current', 'page');
var breadcrumbView = views.BreadcrumbListView({
            collection: detailCollection,
        });

I also tried using the onRender method in the CollectionView:

const BreadcrumbListView = Marionette.CollectionView.extend({
...
onRender: function () {
            const lastChildView = this.children.last();
            lastChildView.model.set('aria-current', 'page');
        }
...
})

But in both cases the HTML attribute doesn't show up.

1

There are 1 best solutions below

0
Addison On

Figured this one out.

I can set a property on the collection before instantiating the CollectionView, like this:

detailCollection.last().set('ariaCurrentPage', true);

You could probably also change the underlying model data to accomplish this.

And then when setting the attributes for the child view I can check that property via options.models:

const BreadcrumbView = Marionette.View.extend({
...
    attributes: function () {
        let attributes = {
            ...
        };
        if (this.options.model.get('ariaCurrentPage')) {
            attributes['aria-current'] = 'page';
        }
        return attributes;
    },
...
})