如何在Backbone Views中获取大小(高度/宽度)信息?
在我的骨干应用程序的渲染function中,我想用空行填充表格的其余部分以获得交替的行外观,但我不知道要添加多少行。 我试过this.el.clientHeight
, $(this.el).height()
,以及这些函数的所有其他排列让它们都返回0.有谁知道怎么做? 我也不想添加太多以便不引入滚动条。
var bar = Backbone.View.extend({ initialize: function(){ _.bindAll(this, "render"); }, render: function(){ var html = "
Hi!
"; $(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; } });var bar = Backbone.View.extend({ initialize: function(){ _.bindAll(this, "render"); }, render: function(){ var html = "
Hi!
"; $(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; } });
解决那些遇到与我相同问题的人的解决方案:你必须等待元素完全连接到dom才能获得高度/宽度信息。 为了解决这个问题,我在渲染完成后添加了一个postrender调用,然后返回并处理任何小细节。
在你附上它之后尝试获得高度(所以在“foo”而不是“bar”)。
例如在“foo”中
render: function(){ $(this.el).append(this.subview.render().el); alert($(this.subview.el).height()); return this; }
在某些浏览器上,设置html后,宽度和高度信息不会立即可用。 原因是您已更新DOM,但浏览器可能尚未布置新页面。
在过去,我已经使用勾选来推迟呼叫,以便浏览器在测量之前有时间赶上。 您可以使用underscore.defer()
。 例如:
render: function(){ var html = "Hi!
"; $(this.el).html(html); _.defer(_.bind(function() { alert($(this.el).width()); }, this); return this; }
此外,jQuery.width()可能会提供比clientWidth更好的兼容性。 祝好运!
您的视图应如下所示:
var myView = Backbone.View.extend({ el: $('#myElement'), initialize: function(){ _.bindAll(this, "render"); }, render: function(){ var myHeight = this.el.height(); alert(myHeight); return this; } });
希望有所帮助