How do I add a resize event to the window in a view using Backbone?

前端 未结 2 1740
日久生厌
日久生厌 2021-02-08 01:33

I have been trying to attach a handler to the resize event in one of my Backbone views. After doing some research I have discovered that you can only attach events to the view\'

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-08 02:13

    You might let window.onresize trigger a custom backbone.js event and then let Views or Models listen to that to have custom responses for various elements.

    Case 1. A view listens to the window event directly.

    window.onload = function() {
    
      _.extend(window, Backbone.Events);
      window.onresize = function() { window.trigger('resize') };
    
      ViewDirect = Backbone.View.extend({
    
        initialize: function() {
          this.listenTo(window, 'resize', _.debounce(this.print));
        },
    
        print: function() {
          console.log('Window width, heigth: %s, %s',
            window.innerWidth,
            window.innerHeight);
        },
    
      });
    
      var myview = new ViewDirect();
    
      }
    

    Case 2. You may want to retain the window size without inspecting it each time you need it, hence you store the window size in a backbone model: in this case the window model listens to the window, while the view listens to the window model:

    window.onload = function() {
    
      _.extend(window, Backbone.Events);
      window.onresize = function() { window.trigger('resize') };
    
      WindowModel = Backbone.Model.extend({
    
        initialize: function() {
          this.set_size();
          this.listenTo(window, 'resize', _.debounce(this.set_size));
        },
    
        set_size: function() {
          this.set({
            width: window.innerWidth,
            height: window.innerHeight
          });
        }
    
      });
    
      ViewWithModel = Backbone.View.extend({
    
        initialize: function() {
          this.listenTo(this.model, 'change', this.print);
          ...
        },
    
        print: function() {
          console.log('Window width, heigth: %s, %s',
            this.model.width,
            this.model.height);
        },
      });
    
      var window_model = new WindowModel();
      var myview = new ViewWithModel({model: window_model});
    
    }
    

提交回复
热议问题