Get last item view from CompositeView in Marionette
Asked Answered
E

1

6

Is it possible to get the last ItemView from a Backbone CompositeView? I've found a lot of documentation for getting the last model in a Collection, but not that last View in a Collection of Views.

The reason I would like to do this is so I can render the last row in a table slightly differently.

The following is the code I'm using right now, it works fine, but it would be less "hacky" if I could get the correct ItemView from the CompositeView that created and rendered it. It uses jQuery to search the entire part of the DOM contained by the CompositeView for the last element, then manipulates that element.

B.ListControl.View = Backbone.Marionette.CompositeView.extend({
    itemView: ...,
    itemViewContainer: ...,
    template: ...,
    // ON RENDER
    onRender: function(){
        // Add button to the last element in the list
        this.$el.find('div:last').text('Custome stuff goes here');
    }
});

Thanks!

Ermeena answered 1/9, 2013 at 5:18 Comment(0)
N
10

When your collection is fetched you can get last item in this way:

this.children.findByIndex(this.children.length - 1);

Babysitter plugin provides a lot of useful methods for you:

findByModel, findByCollection, findByCustom, findByIndex, findByCid

Numeration answered 1/9, 2013 at 6:15 Comment(2)
Backbone.BabySitter documentation for finding views from a ChildViewContainer (which .children is an instance of): github.com/marionettejs/backbone.babysitter#retrieving-viewsJacquiline
n.b. Marionette's CompositeView has a property called .childViewContainer but it's unrelated: Marionette expects it to be a jQuery selector string which it will use to determine where to put instances of the childView class it makes. github.com/marionettejs/backbone.marionette/blob/master/docs/…Jacquiline

© 2022 - 2024 — McMap. All rights reserved.