Molecules - ClickItemComponent

Admin私のストア

This article explains Molecules' ClickItemComponent.

ClickItemComponent is a combination of ClickComponent and any Component.

ClickComponent uses std::function<void()> type to execute any function when a click event occurs. ClickItemComponent realizes the behavior when the specified Component is clicked by making any Component a child element of ClickComponent.

Kotaro uses std::function to delegate function processing to event handlers and also to delegate component configuration processing. When implementing a component, you need to understand delegation using std::function.

The delegation idiom is a common one used in JavaScript: you define a function, instantiate it, pass it to another scope, and execute it there.

In the following example, we delegate by passing a JavaScript Closure object to the click event handler.

var click = ()=>{ var hoge="hoge"; return ()=>{console.log(hoge); };

<Button onClick=click()/>

This is the same as passing an object and executing a method on it, but the ownership of the object is transferred to the recipient.

In C++, delegation can be implemented using std::move. Because std::unique_ptr is movable and copy-protected, the delegation idiom can be implemented robustly and efficiently using std::move and std::unique_ptr.

In the javascript example, we don't specify the type of object to delegate to onClick. In C++, we can use std::function to further abstract the delegation, making it easier to implement abstract delegation like in javascript.

class Click{ void operator( )( ){ std::cost << hoge << std::endl; } };

std::function<void()> click = Click{&hoge};

The constructor for the Click object is omitted, but it is actually necessary. Use std::function to erase the user-defined type Click from the click type. Since we pass in a std::function for delegation, the delegate does not need to know what the definition of the object is.

I have never seen a strict definition of the delegation idiom, but I think this idiom is implemented in object-oriented programming by passing a function object through type erasure. Since JavaScript does not have types in the first place, you can delegate to any object just by passing an instance of a function object. I think JavaScript is a powerful language. C++ is a static language that provides new programming styles while expanding language functions.

In the ClickItemComponent test, you can verify the behavior of the click event by passing in a function to increment the count and an ImageComponent as arguments.

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.