组合优于继承,在不使用继承的情况下,有什么更好的方法为视图添加附加功能?

4
我之前读过很多与组合优于继承有关的内容,我完全认同这个概念,并在我的代码中经常使用这个原则。但是在我的日常工作中,继承常常出现在视图中,我很难看到如何实现更加组合式的方案(由于我在日常工作中使用的是Backbone框架,这也让问题变得更加困难)。当我想要利用现有的所有Backbone视图功能并在其基础上添加一些额外的功能时,这些问题就会出现。
以下是一个假设性的示例:我们有一个电子商务类型的页面,其中包含多个“Product”视图,每个视图代表特定产品的可选项集合。
var ProductView = (function(Backbone, JST) {
  'use strict';

  return Backbone.View.extend({
    className: 'product',
    template: JST['application/templates/product']

    initialize: function(options) {
      this.options = options || {};
      this.collection.fetch();
      this.listenTo(this.collection, 'loaded', this.render);
    },

    render: function() {
      this.$el.html(
        this.template(this.collection)
      );

      return this;
    },
  }, {
    create: function(el) {
      var endpoint = '/api/options/' + el.getAttribute('data-basket-id') + '/' + el.getAttribute('data-product-id');

      new ProductView({
        el: el,
        collection: new ProductCollection(null, { url: endpoint })
      });
    }
  });
})(Backbone, JST);

假设我们想展示一些需要提示访问者确认的产品(比如由于保险原因,这个特定的产品必须与保险一起销售,所以当用户将其添加到购物篮时,我们需要提示用户):

var InsuranceProductView = (function (_, ProductView) {
  'use strict';

  return ProductView.extend({
    consentTemplate: JST['application/templates/product/insurance_consent'],

    initialize: function (options) {
      this.listenTo(this.model, 'change:selected', function (model) {
        if (!model.get('selected')) {
          this.removeMessage()
        }
      });

      ProductView.prototype.initialize.apply(this, arguments);
    },

    events: function () {
      return _.extend({}, ProductView.prototype.events, {
        'change input[type=radio]': function () {
          this.el.parentElement.appendChild(this.consentTemplate());
        },
        'change .insurance__accept': function () {
          ProductView.prototype.onChange.apply(this);
        },
      });
    },

    removeMessage: function () {
      var message = this.el.parentElement.querySelector('.insurance__consent');
      message.parentNode.removeChild(message);
    },
  });
})(_, ProductView);

有没有更可组合的方法编写这个代码?或者这种情况下通过继承分离是正确的做法?

1个回答

0

针对这种情况,继承很有效。关于组合优于继承的论点是无用的,在手头的情况下使用最佳方案。

但是,仍然可以改进以便更轻松地进行继承。当我制作一个要继承的骨干类时,我尽量让它对子类几乎不可见。

实现这一点的方法之一是将父类的初始化放入构造函数中,将initialize函数全部留给子类。同样的事情也适用于events哈希。

var ProductView = Backbone.View.extend({
    className: 'product',
    template: JST['application/templates/product'],
    events: {},

    constructor: function(options) {
        // make parent event the default, but leave the event hash property
        // for the child view
        _.extend({
            "click .example-parent-event": "onParentEvent"
        }, this.events);

        this.options = options || {};
        this.collection.fetch();
        this.listenTo(this.collection, 'loaded', this.render);

        ProductView.__super__.constructor.apply(this, arguments);
    },

    /* ...snip... */
});

子视图变为:

var InsuranceProductView = ProductView.extend({
    consentTemplate: JST['application/templates/product/insurance_consent'],

    events:{
        'change input[type=radio]': 'showConsent',
        'change .insurance__accept': 'onInsuranceAccept'
    }

    initialize: function(options) {
        this.listenTo(this.model, 'change:selected', function(model) {
            if (!model.get('selected')) {
                this.removeMessage()
            }
        });
    },

    showConsent: function() {
        // I personally don't like when component go out of their root element.
        this.el.parentElement.appendChild(this.consentTemplate());
    },

    onInsuranceAccept: function() {
        InsuranceProductView.__super__.onChange.apply(this);
    },

    removeMessage: function() {
        var message = this.el.parentElement.querySelector('.insurance__consent');
        message.parentNode.removeChild(message);
    },
});

此外,Backbone的extend方法会添加一个__super__属性,其值为其父类的原型。我喜欢使用它,因为它允许我更改父类而无需担心函数中对其原型的使用。

我发现当构建由较小组件组成的视图时,组合非常有效。

下面的视图几乎没有什么内容,除了较小组件的配置外,每个组件都处理大部分复杂性:

var FoodMenu = Backbone.View.extend({
    template: '<div class="food-search"></div><div class="food-search-list"></div>',

    // abstracting selectors out of the view logic
    regions: {
        search: ".food-search",
        foodlist: ".food-search-list",
    },

    initialize: function() {

        // build your view with other components
        this.view = {
            search: new TextBox({
                label: 'Search foods',
                labelposition: 'top',
            }),
            foodlist: new FoodList({
                title: "Search results",
            })
        };
    },

    render: function() {
        this.$el.empty().append(this.template);

        // Caching scoped jquery element from 'regions' into `this.zone`.
        this.generateZones();
        var view = this.view,
            zone = this.zone;
        this.assign(view.search, zone.$search)
            .assign(view.foodlist, zone.$foodlist);

        return this;
    },

});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接