Backbone.js view inheritance

前端 未结 3 1189
心在旅途
心在旅途 2020-12-02 04:50

I have a view called Pannel which is just a background with a close button. I want to extend that view to one called PannelAdvanced. How would I do

3条回答
  •  庸人自扰
    2020-12-02 05:29

    To piggyback further a bit:

    I liked @JohnnyO's approach but wanted to confirm that a resulting view was still capable of doing everything it's supposed to. Given his approach, I didn't suspect there would be any issues, but I wanted to be a bit more certain.

    So, I took a minute and adapted the Backbone.js Views test suite to the multiple inheritance technique @JohnnyO proposes.

    You can run the results at http://jsfiddle.net/dimadima/nPWuG/. All tests pass.

    My base and extended views:

    var RegularView = function (options) {
      // All of this code is common to both a `RegularView` and `SuperView`
      // being constructed.
      this.color = options && (options.color || 'Green');
    
      // If execution arrives here from the construction of
      // a `SuperView`, `Backbone.View` will call `initialize`
      // that belongs to `SuperView`. This happens because here
      // `this` is `SuperView`, and `Backbone.View`, applied with
      // the current `this` calls `this.initialize.apply(this, arguments)`
      Backbone.View.apply(this, arguments)
    };
    
    RegularView.extend = Backbone.View.extend;
    
    _.extend(RegularView.prototype, Backbone.View.prototype, {
      // Called if a `RegularView` is constructed`,
      // Not called if a `SuperView` is constructed.
      initialize: function () {
        console.log('RegularView initialized.');
      },
    
      say_hi: function() {
        console.log('Regular hi!');
      }
    
    });
    
    var SuperView = RegularView.extend({
      // Called if a `SuperView` is constructed`,
      // Not called if a `RegularView` is constructed.
      initialize: function(options) {
        console.log('SuperView initialized.')
      },
    
      say_hi: function() {
        console.log('Super hi!');
      }
    })
    

    For the test suite, I grabbed the latest views tests from GitHub and replaced occurrences of Backbone.View with RegularView. The tests then use RegularView and the results of RegularView.extend() to make sure both do what they're supposed to.

提交回复
热议问题