组合优于继承,这是向视图添加额外功能而不诉诸继承的更好方式
Composition over inheritance, what is a nicer way to add additional functionality to a view without resorting to inheritance
我过去读过很多关于可组合性优于继承的文章,我完全接受了这个概念,并在我的代码中大量使用了这个原则。
然而,在我的日常工作中,我遇到了一些问题,其中继承倾向于潜入视图,我努力寻找如何实现更可组合的东西(在我的日常工作中使用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);
是否有更可组合的方式来写这个?或者在这种情况下,通过继承来终止是正确的?
对于这种特殊情况,继承工作得很好。关于可组合性优于继承的争论是徒劳的,使用最适合当前情况的方法。
但是,仍然可以做出改进来简化继承。当我创建一个要继承的主干类时,我尽量使它对子类不可见。
实现这一目标的一种方法是将父类的初始化放入构造函数中,将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);
},
});
同时,主干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;
},
});
相关文章:
- 添加文字和评论功能更新Div
- JavaScript打印功能使日历停止工作
- 每当您在选择器内移动鼠标时,悬停功能就会重复
- 如何防止网页加载后自动启动功能
- 除修剪外的其他功能
- 悬停功能触发器
- 使用angularjs向浏览器发送servlet响应(下载功能)
- 删除CKEditor工具栏按钮,但不删除功能
- 异步facebook功能
- 如何将chrome扩展功能移植到移动设备(特别是jquery和trello)
- 从控制器继承了隔离的作用域以生成可重用的指令
- Javascript-经理是一个人,但不是经理本身?功能/原型继承
- KnockoutJS 通过 ko.utils.extend 继承功能
- 功能继承
- 农业网格继承功能
- 在基于Crockford's的功能继承
- 组合优于继承,这是向视图添加额外功能而不诉诸继承的更好方式
- Javascript继承具有父级父级的功能
- Javascript继承:用模块模式和$.extend覆盖功能
- 是否有一种方法可以访问从基本模块继承的dojo功能