[英]Possible to extend multiple views in Backbone?
I have 3 backbone views ( Month
, Day
, Week
). 我有3个主干视图(
Month
, Day
, Week
)。
There is some common code all 3 share that I'll put in a Base
view. 我将在
Base
视图中放置一些共同的代码共3个共享。
Then there is some common code that Day
& Month
share which I'll put in a DayAndMonthBase
view and other common code that Day
& Week
share which I'll put in a DayAndWeekBase
view. 然后有一些常见的代码,
Day
和Month
共享,我将放入DayAndMonthBase
视图和其他常用代码, Day
& Week
共享,我将放入DayAndWeekBase
视图。 Both the DayAndMonthBase
and the DayAndWeekBase
will extend the Base
. DayAndMonthBase
和DayAndWeekBase
都将扩展Base
。
Finally, my Month
view will extend DayAndMonthBase
and my Week
view will extend my DayAndWeekBase
. 最后,我的
Month
视图将扩展DayAndMonthBase
,我的Week
视图将扩展我的DayAndWeekBase
。 However with my Day
view, how can I extend BOTH the DayAndMonthBase
view as well as the DayAndWeekBase
view? 然而,随着我
Day
观点,我怎么能延长两个DayAndMonthBase
视图还有DayAndWeekBase
看法?
I like to solve this sort of problem using mixins rather than inheritance, because there is no clear hierarchical structure here. 我喜欢使用mixins而不是继承来解决这类问题,因为这里没有明确的层次结构。 Constructs like
DayAndMonthBase
along with DayAndWeekBase
are rigid and inextensible. 像
DayAndMonthBase
和DayAndWeekBase
这样的DayAndMonthBase
是僵硬且不可DayAndWeekBase
的。 What i like to do is define the common behavior as objects, and then inject the behavior into the views using _.extend
and not Backbone.View.extend
. 我想要做的是将常见行为定义为对象,然后使用
_.extend
而不是Backbone.View.extend
将行为注入到视图中。
Define your mixin objects 定义mixin对象
var mixin1 = {
....
}
var mixin2 = {
....
}
var mixin3 = {
....
}
Then inject these mixins into each View that needs the functionality. 然后将这些mixin注入到需要该功能的每个View中。
var Day = Backbone.View.extend({
....
})
_.extend(Day.prototype, mixin1);
_.extend(Day.prototype, mixin2);
_.extend(Day.prototype, mixin3);
var Week = Backbone.View.extend({
....
})
_.extend(Week.prototype, mixin1);
var Month = Backbone.View.extend({
....
})
_.extend(Month.prototype, mixin2);
It's easier to reason about this way, because you don't have the mental load of remembering what DayAndWeekBase
actually does. 这种方式更容易推理,因为你没有记住
DayAndWeekBase
实际做什么的心理负担。 If you name your mixins appropriately, it's clear to see what kind of functionality you're injecting into the views. 如果你恰当地命名mixins,很明显你会在视图中注入哪种功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.