Module for defining reusable reactive functions that can be imported into LiveViews.
Usage
Create a module with defrx functions:
defmodule MyApp.Validators do
use Lavash.Rx.Functions
defrx valid_email?(email) do
String.length(email) > 0 && String.contains?(email, "@")
end
defrx valid_phone?(phone) do
String.match?(phone, ~r/^\d{10}$/)
end
endThen import them in your LiveView:
defmodule MyAppWeb.UserLive do
use Lavash.LiveView
import Lavash.Rx
import_rx MyApp.Validators
calculate :email_valid, rx(valid_email?(@email))
calculate :phone_valid, rx(valid_phone?(@phone))
endHow it works
When you use Lavash.Rx.Functions:
- The
defrxmacro becomes available for defining functions - At compile time, all
defrxdefinitions are collected - A
__defrx_definitions__/0function is generated that returns all definitions - Other modules can import these definitions using
import_rx
Important constraints
defrxfunction bodies must be single expressions- No intermediate variable assignments (e.g.,
x = 1is not allowed) - All code must be transpilable to JavaScript (see
Lavash.Rx.Transpiler)
Example with nested functions
You can call other defrx functions from within a defrx body:
defmodule MyApp.CardValidators do
use Lavash.Rx.Functions
defrx expected_length(is_amex) do
if(is_amex, do: 15, else: 16)
end
defrx valid_card_number?(digits, is_amex) do
String.match?(digits, ~r/^\d+$/) &&
String.length(digits) == expected_length(is_amex)
end
end