简体   繁体   中英

Dojo 1.9 mixin approach

When a widget needs to be decorated with functionality (that may be needed by several different widgets) I have been moving more towards a mixin approach.

For example, for a custom library of widgets, I could see some mixin's being: - L10n support (for example, making it trivial to capture certain keys like F10 by providing a direct function to override like f10Callback()) - Custom theme support (like adding certain css classes for domain-specific situations that span many different widgets)

I kind of like the idea of just slapping a mixin on a widget, which to me seems to be simply adding functions and properties following the widget lifecycle of the widget that is doing the mixin.

Some questions: - Am I over-using this mixin idea? - How do you prevent mixins being applied multiple times to the same widget (like when - modules you are extending already have mixins)? - Should mixin's ever hold state? - How should mixin's expose functionality? By providing functions that their widgets need to override? Or a more pub/sub approach?

Really just looking for general advice with dojo mixins.

I think you're right on with how to use mixins: they are meant to be small, portable, and specific adjustments to the behavior of other objects.

There is no built-in mechanism for mixin idempotency: you would need to manage that on your own. I have never run into this situation in the field, as I tend to declare classes on the fly and the mixin happens right before use. For example, if I were using a mixin for theming, I would do that in my top-level "interface" (responsible for gluing all the widgets together) rather than in each class that can be themed.

Mixins can and do hold state. See for example dijit/form/_FormWidgetMixin.js

How should mixin's expose functionality? Well, I would say this depends upon the overall design and that there is no right way. My mixins generally just extend the API of the base class transparently: that is they add to the class behavior without adding to the API. There are scenarios where the the base class is an abstract interface and mixins are required to implement the behavior (mostly when I have strategy or builder patterns to implement).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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