How to work with the input and output handers in famo.us? - famo.us

In order to build clean code, Famo.us is using events to communicate to modules. Most of the Event guide shows example about EventHandler. Now we are supposed to build robust view with input and output events, how to actually work with it ? i.e. what is the purpose of the input and output handlers ?

In order to build robust modules is is convenient to separate the code into Widgets which are only responsible for the function they are built for. Here is the official way of building a widget:
function Widget(){
this.eventOutput = new EventHandler();
this.eventInput = new EventHandler();
EventHandler.setInputHandler(this, this.eventInput);
EventHandler.setOutputHandler(this, this.eventOutput);
}
var widget = new Widget();
To summarise the function above it does create an object with 2 EventHandler, one for the input and another one for the output.
Their purpose is trivial:
all the incoming events i.e. the events triggered from outside of the widget object will be triggered to the eventInput handler.
all the outgoing events i.e. events generated by the widget to the outside are triggered through the eventOutput.
To understand a little better, you will very likely be listening to an eventInput handler from inside of the widget and trigger to an eventOutput handler still from inside of the widget code.
Here is an example:
function Widget(){
// here we are inside the Widget code scope
var self = this; // just to keep the root "this" somewhere
this.eventOutput = new EventHandler();
this.eventInput = new EventHandler();
this.eventInput.on("sayHello", function()
{
alert("Hello")
});
function didSomething()
{
self.eventOutput.trigger("didSomething");
}
}
You might then use the widget as follow:
var widget = new Widget();
widget.eventOutput.on("didSomething", function(){alert("The widget did something!")})
widget.eventInput.trigger("sayHello"); // will alert "Hello" from inside the widget
Now we might not be willing to know the internal structure of a widget to use it. Here we are calling and listening on the eventOutput and eventInput which might actually have any name. For the clarity of the code, we can bind those events functions to the widget itself adding the following lines into the widget:
... code ...
EventHandler.setInputHandler(this, this.eventInput);
EventHandler.setOutputHandler(this, this.eventOutput);
... code ...
Now the widget can be listened and triggered in the following way:
widget.on("didSomething", function(){alert("The widget did something!")});
widget.trigger("sayHello"); // will let the widget alert "Hello"
What about piping ?
This is quite simple, while piping a widgetA to a widgetB
widgetA.pipe(widgetB);
All the events triggered by widgetA.eventOutput are piped (read triggered) to widgetB.eventInput
Note: The same principle can be applied on subscription, the following will achieve exactly the same result:
widgetB.subscribe(widgetA);

Related

Senders objectName is absent | QT & Cpp

I have created a little UI with a simple toolbar. I am initing the toolbar within the initToolbarfunction. This function is within a Class inheriting from QMainWindow.
void Main_Frame::initToolBar() {
rectangle.setText(rectangle_text);
circle.setText(circle_text);
triangle.setText(triangle_text);
triangle.setObjectName(triangle_id);
circle.setObjectName(circle_id);
rectangle.setObjectName(rectangle_id);
toolBar.addAction(&triangle);
toolBar.addAction(&circle);
toolBar.addAction(&rectangle);
connect(
&toolBar, &QToolBar::actionTriggered, this, [=]() {
process_toolbar_ac_evt(*sender());
});
}
I want any tool bar events to be processed through process_toolbar_ac_ect(QObject obj). Within that method, I want to decide what action (within the toolbar) has been triggered.I want to do this by the objectname. Therefore I have given any action an object name. But when I call sender().objectName() I get an empty QString.
My suggestion is, that sender returns a pointer to on of my actions that I put to the toolbar. If this is the case, why I get an empty QString on the sender()?
void Main_Frame::process_toolbar_ac_evt(QObject &evt) {
if (evt.objectName() == circle_id) {
// If circle action has clicked, to this ...
}
}
As you are connecting to one of QToolBar's signals the sender() will be your tool bar object.
Simply use the QAction argument that is passed in the QToolBar::actionTriggered signal. That's what it is for.
NB: Avoid QObject::sender() wherever possible. It virtually breaks the desired decoupling achieved by signals and slots.

C++/QML: How to define and handle multiple contexts for dynamically created components?

Basically my situation is like this:
I've got a class that extends QQuickView and that exposes certain objects from C++ to QML by setting context properties. The views that are shown are created from QML and are all different istances of the same custom made component; new views are created when certain events occur, and when that happens the existing views should show the objects that were initially assigned to them in the C++ side, and the new ones should show the things assigned to them.
So, in the C++ side I've got something like this:
WindowManager::WindowManager(QQuickView *parent) :
QQuickView(parent)
{
// Setting the source file to use
this->setSource(QUrl("qrc:/qml/main.qml"));
// Exposing the istance of this class to QML for later use
this->rootContext()->setContextProperty("qquickView", this);
// Calling the method that will create dynamically a new view that will be child of main.qml; the parameter is not important, just a random number to start with
this->prepareNewView(3)
this->showFullScreen();
}
WindowManager::prepareNewView(int stuffId)
{
MyDatabase db;
// Getting something to show in QML from somewhere based on the parameter received
SomeStuff stuff = db.getStuff(stuffId)
// Exposing the object I need to show in QML
this->rootContext()->setContextProperty("someStuff", stuff);
QObject *object = this->rootObject();
// Here I'm invoking a function from main.qml that will add a new view dynamically
QMetaObject::invokeMethod(object, "addView");
}
Now, in the QML side I've got a main file like this:
// main.qml
Rectangle {
id: mainWindow
width: 1000
height: 1000
// This function adds a component to mainWindow
function addView()
{
// Creating the component from my custom made component
var component = Qt.createComponent("MyComponent.qml");
// Creating an istance of that component as a child of mainWindow
var newView = component.createObject(mainWindow);
// ... Now I would be doing something with this new view, like connecting signals to slots and such
}
}
Then I've got my custom component, which is the view that will be created dynamically:
// MyComponent.qml
Rectangle {
id: customComponent
// Here I would be using the object I exposed from the C++ side
x: someStuff.x
y: someStuff.y
width: someStuff.width
height: someStuff.height
// Here I'm creating a MouseArea so that clicking this component will cause the creation of another view, that will have to show diffrent things since the parameter I'm passing should be different from the starting parameter passed in the constructor of WindowManager
MouseArea {
anchors.fill: parent
onClicked: qquickView.prepareNewView(Math.random())
}
}
Now, with everything as it is, at first it will show "the stuff" with id 3, that was exposed as a context property of the main context.
But then, if I click on the MouseArea, assuming that an id other than 3 will be passed, a new context property with the same name will be exposed, causing the override of the old property. This means that the first view will now show "the stuff" just exposed, not "the stuff" based from the stuffId equals to 3, while what I need is the first view to keep showing what it was supposed to show ("the stuff" with id = 3), and any other view that will come later the things corresponding to their ids.
This happens because I'm defining a property in the context that is common to every component, while I should be defining a property that is visible ONLY by the new istance of the component that is being created dynamically. But how do I do that?
In the documentation I read that it's possibile to create a component directly from C++ and defining the context that it should use... something like this (snippet taken from here):
QQmlEngine engine;
QStringListModel modelData;
QQmlContext *context = new QQmlContext(engine.rootContext());
context->setContextProperty("myModel", &modelData);
QQmlComponent component(&engine);
component.setData("import QtQuick 2.0\nListView { model: myModel }", QUrl());
QObject *window = component.create(context);
I think that this would work for what I intend to do. Whenever I create a new view from C++ (caused by the click on the MouseArea) I create a new context with "someStuff" as its property, so that each view has its own "stuff"... but I need to have access to the newly created view from QML, because after I create it in the addView() function inside main.qml I access the view in order to do certain thins (not important what exactly), and if I create the istance of the component from C++ I don't know how to access it from QML... is there a way maybe to pass the component from C++ to QML in order to access it?
I'm out of ideas on how to resolve this or to find another way to have dynamically created views with custom contents all visible at the same time... any suggestions are appreciated.
I actually found out that it is possible (and easy) to directly pass a component created in C++ to QML.
So right now, I modified the code pretty much like this:
WindowManager::prepareNewView(int stuffId)
{
MyDatabase db;
// Getting something to show in QML from somewhere based on the parameter received
SomeStuff stuff = db.getStuff(stuffId)
// Creating the new context, based on the global one
QQmlContext *context = new QQmlContext(this->rootContext());
// Exposing the object I need to show in QML to the new context
context ->setContextProperty("someStuff", stuff);
// Creating the component
QQmlComponent component(this->engine(), QUrl("qrc:/qml/MyComponent.qml"));
// Creating the istance of the new component using the new context
QQuickItem *newView = qobject_cast<QQuickItem*>(component.create(context));
// Getting the root component (the Rectangle with it mainWindow)
QObject *object = this->rootObject();
// Manually setting the new component as a child of mainWIndow
newView->setParentItem(qobject_cast<QQuickItem*>(object));
// Invoking the QML that will connect the events of the new window, while passing the component created above as QVariant
QMetaObject::invokeMethod(object, "addView", Q_ARG(QVariant, QVariant::fromValue(newView)));
}
In QML the function in the main.qml is now like this:
// Function called from C++; the param "newView" is the last component added
function addView(newView)
{
// ... Here I would use the new view to connect signals to slots and such as if I created "newView" directly in QML
}
So I managed not to change the code too much after all.
I think you can pass your component instance (QObject) by setting an object as a context property as you did in your code.
class ViewInstance : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE QObject* getCurrentViewInstance() {
...
QObject *window = component.create(context);
return window;
}
};
int main(int argc, char *argv[]) {
...
QQuickView view;
ViewInstance data;
view.rootContext()->setContextProperty("viewInstance", &data);
}
Then, in your qml, you can get the component instance by calling viewInstance.getCurrentViewInstance(). Hope this helps.

Meteor Dynamic Template Events

I'm new to Meteor, I could not find a sufficient answer to this but how does one go about referencing a Template's event handlers programmatically.
For example I would like to add or update or trigger an event defined in a template without actually as an example (pressing or clicking a button).
In the Template object I can see the events object below and can I access it but is this the right way?
Template.myTemplate._tmpl_data.events[]
Thanks!
You can define the handler outside the event map and call it as a function:
someHandler = function(this, evt,tpl) {
// do something with this, evt, and tpl
}
Template.myTemplate.events({
'click .myButton': function(event,template) {
var self = this;
return someHandler(self, event,template);
}
});
// Call someHandler whereever you want passing in whichever args you want
This is not a complete example, but should be able to get you going on some workable direction. If it works, please edit this answer to reflect a more complete example.

How do I properly set up generic QT actions for a menu constructed at run time?

I am populating a sytem tray icon menu (QMenu) from entries in an xml file which is read when my application starts up.
I am unsure of how to properly set up the SLOT end of the action:
QList<CMenuItem> menuItems = m_layout->getMenuItems();
QListIterator<CMenuItem> iter(menuItems);
while (iter.hasNext())
{
CMenuItem menuItem = iter.next();
QAction *action = new QAction(menuItem.qsTitle, this);
connect(action, SIGNAL(triggered()), this, SLOT(launchMenuItem()));
trayIconMenu->addAction(action);
}
How does my "launchMenuItem()" SLOT know which menu item was triggered? I can't make a SLOT for each menu item as I don't know how many items will exist until run time.
I can think of some ugly ways to do this, but I am looking for the RIGHT way.
What I usually do is to use QAction::setData(const QVariant&) to store whatever action ID I need. Then on slot side I retrieve ID with QAction::data() and behave accordingly.
Note that QVariant obviously accepts much more than basic int (which is what I use to identify actions), you can pass any QVariant-compatible info.
edit : oh! btw, this is somehow ugly because I make use of QObject::sender() to cast triggered action back. Sorry for that, but it works anyway.

Configuring new document in MFC

When the user creates a new document in my SDI-application, I need to present a dialog specifying details on the document to be created (think: resolution, bit-depth, etc.) I initially put the code for displaying this dialog in OnNewDocument() (I don't need it when opening an existing document), but putting user-interface code in the document-class just doesn't feel right (also, I don't have any CWnd* to use as a parent for the dialog).
Is there a better place to do this in MFC?
You're right, the document class is no good place for UI.
CDocTemplate::[OpenDocumentFile][1](pszPath) looks like a better candidate:
pszPath==NULL means 'create a new document'.
The method is virtual -> Just derive CMySingleDocTemplate from CSingleDocTemplate and use an instance of this class in CMyWinApp::InitInstance().
This class is responsible for creating docs, frames and views, hence I think it's a good place to put a UI operation.
BOOL CMyWinApp::InitInstance()
{
...
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CMySingleDocTemplate( // <--Derives from CSingleDocTemplate
IDR_MAINFRAME,
RUNTIME_CLASS(CMyDoc),
RUNTIME_CLASS(CMainFrame),
RUNTIME_CLASS(CMyView));
AddDocTemplate(pDocTemplate);
...
}
CDocument* CMySingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName,
BOOL bMakeVisible)
{
CDocument *pDoc =
CSingleDocTemplate::OpenDocumentFile(lpszPathName, bMakeVisible);
if (lpszPathName==NULL)
{
// GUI to get user info
// update doc
m_pOnlyDoc->Blah(input);
// update view
m_pOnlyDoc->UpdateAllViews(NULL,...,...);
}
}
This might not be ideal though: In SDI, there is one and only doc object. It's re-used accross File/Load and File/New operation.
This function will then be called a first time before the initial mainframe is created. You may not want to have a dialog presented to user before the frame is created. Ouch! It's a little more complicated:
Instead of popping up a GUI in in OpenDocumentFile(NULL) as above, just post a custom message/command to the main frame. Then add a handler that will react by the sequence pop up GUI/update doc/update views. That way, the main frame will be displayed before the GUI is popped up and your user will be happier.
This also solves your problem where you don't have a CWnd parent: the main frame is already created and your dialog will use it byt default.
BTW, another solution consists in adding a command handler for ID_FILE_NEW in your CMyWinApp's message map and add your own override of OnFileNew(). But when you write OnFileNew(), I believe you'll quickly find out that it's an ugly solution :-(