This example also shows how you can respond to notifications by adding or removing interests from a connection.
Here is the interface for TSpecialShapeView. Besides the handlers, it has a setter for the shape in which it is interested. It also has a message that changes when a matching shape is added or removed.
class TSpecialShapeView : public TSimpleView, public virtual VViewInitialize { public: MCollectibleDeclarationsMacro(TSpecialShapeView); TSpecialShapeView(TShapeList* shapeList, const TGPoint& size, const TGPoint& locationInParent = TGPoint::kOrigin); TSpecialShapeView(const TSpecialShapeView&); virtual ~TSpecialShapeView(); const TShape& GetSpecialShape() const; virtual void SetSpecialShape(const TShape&); protected: virtual void DrawContents(TGrafPort&) const; virtual void SetMessage(const TText&); virtual void HandleAddedSpecialShape(const TNotification&); virtual void HandleRemovedSpecialShape(const TNotification&); private: TShapeList* fShapeList; TShape* fSpecialShape; Boolean fShapeWasInList; TTextDisplay fMessage; TMemberFunctionConnectionTo<TSpecialShapeView> fConnection; };
When SetSpecialShape changes the shape that the view is interested in, the view informs the connection. First it removes any interests for the old shape, then adds the appropriate interests for the new shape.
void TSpecialShapeView::SetSpecialShapeID(const TGlobalID& shapeID) { if (fShapeID == shapeID) { return; } if (fSpecialShape) { if (fShapeWasInList) { fConnection.RemoveInterest( fShapeList->GetRemovedThisShapeInterest(*fSpecialShape)); } else { fConnection.RemoveInterest( fShapeList->GetAddedThisShapeInterest(*fSpecialShape)); } } fSpecialShape = ::Copy(fSpecialShape); fShapeWasInList = fShapeList->Member(*fSpecialShape) != NIL; if (fShapeWasInList) { fConnection.AddInterest(fShapeList->GetRemovedThisShapeInterest(*fSpecialShape), &TSpecialShapeView::HandleRemovedSpecialShape); } else { fConnection.AddInterest(fShapeList->GetAddedThisShapeInterest(*fSpecialShape), &TSpecialShapeView::HandleAddedSpecialShape); } SetMessage(TStandardText("New Special Shape")); }
void TSpecialShapeView::HandleAddedSpecialShape(const TNotification& /* notification */) { fConnection.RemoveInterest(fShapeList->GetAddedThisShapeInterest(*fSpecialShape)); fConnection.AddInterest(fShapeList->GetRemovedThisShapeInterest(*fSpecialShape), &TSpecialShapeView::HandleRemovedSpecialShape); fShapeWasInList = TRUE; SetMessage(TStandardText("Added Special Shape")); }