Skip to content

Commit

Permalink
Added event listener 'attributes'.
Browse files Browse the repository at this point in the history
  • Loading branch information
5cript committed Oct 22, 2023
1 parent e9bfa9e commit d99b7ef
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
50 changes: 50 additions & 0 deletions nui/include/nui/frontend/attributes/impl/attribute_factory.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,52 @@ namespace Nui::Attributes
char const* name_;
};

class EventFactory
{
public:
explicit constexpr EventFactory(char const* name)
: name_{name}
{}

// Dont use this class like a value
EventFactory(EventFactory const&) = delete;
EventFactory(EventFactory&&) = delete;
EventFactory& operator=(EventFactory const&) = delete;
EventFactory& operator=(EventFactory&&) = delete;

constexpr char const* name() const
{
return name_;
};

Attribute operator=(std::function<void()> func) const
{
return Attribute{
[name = name(), func = std::move(func)](Dom::ChildlessElement& element) {
element.addEventListener(name, [func](Nui::val) {
func();
globalEventContext.executeActiveEventsImmediately();
});
},
};
}

Attribute operator=(std::function<void(Nui::val)> func) const
{
return Attribute{
[name = name(), func = std::move(func)](Dom::ChildlessElement& element) {
element.addEventListener(name, [func](Nui::val val) {
func(std::move(val));
globalEventContext.executeActiveEventsImmediately();
});
},
};
}

private:
char const* name_;
};

inline namespace Literals
{
constexpr AttributeFactory operator""_attr(char const* name, std::size_t)
Expand All @@ -346,6 +392,10 @@ namespace Nui::Attributes
{
return PropertyFactory{name};
}
constexpr EventFactory operator""_event(char const* name, std::size_t)
{
return EventFactory{name};
}
}
}

Expand Down
6 changes: 6 additions & 0 deletions nui/include/nui/frontend/dom/childless_element.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ namespace Nui::Dom
element_.set(Nui::val{std::string{key}}, Nui::val{static_cast<double>(value)});
}

void addEventListener(std::string_view event, std::invocable<Nui::val> auto&& callback)
{
element_.call<void>(
"addEventListener", Nui::val{std::string{event}}, Nui::bind(callback, std::placeholders::_1));
}

// TODO: more overloads?
void setAttribute(std::string_view key, std::string const& value)
{
Expand Down

0 comments on commit d99b7ef

Please sign in to comment.