简体   繁体   English

可以在Backbone中扩展多个视图吗?

[英]Possible to extend multiple views in Backbone?

I have 3 backbone views ( Month , Day , Week ). 我有3个主干视图( MonthDayWeek )。

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. 然后有一些常见的代码, DayMonth共享,我将放入DayAndMonthBase视图和其他常用代码, DayWeek共享,我将放入DayAndWeekBase视图。 Both the DayAndMonthBase and the DayAndWeekBase will extend the Base . DayAndMonthBaseDayAndWeekBase都将扩展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. DayAndMonthBaseDayAndWeekBase这样的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM