How can I get size (height/width) information in B

2019-04-15 23:50发布

问题:

In the render function of my backbone app, I want to fill the rest of the table with empty rows for the alternating row look, but I dont know how many rows to add. I tried this.el.clientHeight, $(this.el).height(), and all other permutations of such functions to have them all return 0. Does anyone know how to do this? I also dont want to add too many in order not to introduce a scroll bar.


var bar = Backbone.View.extend({
    initialize: function(){
        _.bindAll(this, "render");
    },

    render: function(){
        var html = "<h1>Hi!</h1>";
        $(this.el).html(html);
        var myWidth = this.el.width();
        alert(myWidth);
        return this;
    }

});



var foo = Backbone.View.extend({
    el: $('#myElement'),

    initialize: function(){
        _.bindAll(this, "render");
        this.subview = new bar();
    },

    render: function(){
        $(this.el).append(this.subview.render().el);
        return this;
    }

});




Solution for those stuck with the same problem as I had: You have to wait for the elements to be fully attached to the dom in order to get height/width info. In order to resolve this I added a postrender call after the render is fully done which went back and handled any small details.

回答1:

Try getting the height after you attach it, (so in "foo" as opposed to "bar").

For example in "foo"

    render: function(){

    $(this.el).append(this.subview.render().el);
    alert($(this.subview.el).height());
    return this;
}


回答2:

On some browsers, the width and height information will not be immediately available right after setting the html. The reason for this is that you have updated the DOM, but the browser may not have laid out the new page yet.

In the past I have resorted to deferring the call by a tick so that the browser has time to catch up before you measure it. You can use underscore.defer() for this. For example:

render: function(){
  var html = "<h1>Hi!</h1>";
  $(this.el).html(html);
  _.defer(_.bind(function() {  
    alert($(this.el).width());
  }, this);
  return this;
}

Also, jQuery.width() will probably give you better compatibility than clientWidth. Good luck!



回答3:

Your view should look something like this:

var myView = Backbone.View.extend({
    el: $('#myElement'),

    initialize: function(){
        _.bindAll(this, "render");
    },

    render: function(){
        var myHeight = this.el.height();
        alert(myHeight);
        return this;
    }

});

Hope that helps