Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to the bottom after render a Backbone view

I'm currently working on a messaging system using Backbone. I want to scroll to the last element in a CollectionView on render.

I can get this to work after clicking on link on the page, but I want it to happen on the render of the view.

Here's what I'm using in the link, which works:

document.getElementById('message-new-conversation-dialog').scrollIntoView();

Here's the view definition:

var ConversationView = LSmixBB.CollectionView.extend({

        itemView: MessageView,
        template: "#message-conversation-template",
        onRender: function(){
            document.getElementById('message-new-conversation-dialog').scrollIntoView();
            document.getElementById('global-column-middle-footer1').scrollIntoView();
        }

    });

I presume it doesn't work because there's nothing on the page inside onRender?

I am very new to web development, so be gentle!

Anyway, I'd really appreciate any help!

like image 524
testpattern Avatar asked Jan 26 '26 07:01

testpattern


1 Answers

If you're using Backbone you have access to Underscore's _defer function: http://underscorejs.org/#defer

This will wait until all the DOM manipulations are done and then the function will execute, if you need an internal reference to caller, you can pass this in

_.defer(function(caller){
      //caller is now a reference to the scope where you declared this
}, this);

I use this when I have views that need to create child views asynchronously, but those child views need the parent view to be rendered and in the DOM. If you have full control over the child views then it might be better to have some type of callback though.

Note: you can also use jQuery's .ready function on elements too, but I haven't played with that yet, though it might be a better solution in some cases, since _defer basically waits till the call stack is done executing

like image 100
Clarence Liu Avatar answered Jan 29 '26 11:01

Clarence Liu