javascript 主干视图的窗口大小调整事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17879505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:58:03  来源:igfitidea点击:

window resize event for backbone view

javascriptjquerybackbone.jsbackbone-events

提问by codeofnode

I am using Backbone view in javascript.

我在 javascript 中使用 Backbone 视图。

I have created a backbone view as follows :

我创建了一个主干视图,如下所示:

var MaskView = Backbone.View.extend({
      className: "dropdown-mask",
      initialize: function(){

      },
      onClick: function(e){

      },
      hide: function(){

      },
      makeCSS: function(){
        return {
          width  : Math.max(document.documentElement.scrollWidth,  $(window).width()),
          height : Math.max(document.documentElement.scrollHeight, $(window).height())
        }
      }
    });

i want to capture event of window resizing inside the view.

我想捕获在视图内调整窗口大小的事件。

The problem is that, when the window is completely loaded, and mask view is created from the above backbone view. Now when i resize the window, the mask only covers a partial window area. I want each time the window is reloaded, the mask also changes its area according to the current window size dynamically.

问题是,当窗口完全加载时,遮罩视图是从上面的主干视图创建的。现在,当我调整窗口大小时,蒙版仅覆盖部分窗口区域。我希望每次重新加载窗口时,蒙版也会根据当前窗口大小动态更改其区域。

How do i achieve that?

我如何做到这一点?

回答by Vishal Parpia

Backbone relies on jQuery (or zepto) for DOM manipulation. jQuery's .resize()is the event you're looking for, so you'd write something like this:

Backbone 依赖 jQuery(或zepto)进行 DOM 操作。jQuery 的 .resize()是您要查找的事件,因此您可以编写如下内容:

var MaskView = Backbone.View.extend({
    initialize: function() {
        $(window).on("resize", this.updateCSS);
    },

    updateCSS: function() {
        this.$el.css(this.makeCSS());
    },

    remove: function() {
        $(window).off("resize", this.updateCSS);
        Backbone.View.prototype.remove.apply(this, arguments);
    }
});

That said, I'd wager you don't need to use JavaScript for this at all. Any reason why a plain old CSS style wouldn't do the trick? Something like this:

也就是说,我敢打赌您根本不需要为此使用 JavaScript。为什么一个普通的旧 CSS 样式不能解决问题?像这样的东西:

.dropdown-mask {
    width: 100%;
    height: 100%;
    position: fixed;
}