-
Notifications
You must be signed in to change notification settings - Fork 1
Components
Components are basically html elements (in our case DOM::Element
) with custom functionality. Although similar to custom elements they don't use any of their features, but instead use the power of Ruby and native wrappers to achieve the same functionality and more.
A simple component is defined like this:
# Inherits from Fron::Component
class MyComponent < Fron::Component
# Defines the tag name (optional)
tag 'my-component'
def initialize
super
self.text = 'Hello there!'
end
end
This defines a custom component, when instantited will create an html element with the tag name my-component
.
And using it is even more simple:
myComponent = MyComponent.new
myComponent >> DOM::Document.body
myComponent.greet
As you see we created an instance of the component and appended it to the body then changed it's text with the greet
method.
Behaviors helps us to define DSLs to our components. Basically they are modules that are included into a component. Two behaviors are included by default into the Fron::Component
: events and components.
( Implementation of this feature was changed in 0.2.0 see the change log )
Changing the example above a little:
class MyComponent < Fron::Component
tag 'my-component'
# This DSL was defined by the events behavior
# When the element is clicked run the greet method
on :click, :greet
def greet
self.text = 'Hello there!'
end
end
As you can see with the DSL we defined how the component (instance) should behave.
Components can inherit from a super class, and it is the same as in Ruby.
Extending the above example:
class MyGreeter < MyComponent
def greet
super
self.style.border = '1px solid #000'
end
end
As you can see the behavior that was defined before is still available and propagated to the subclass.
Components can be composed together with the components behavior:
class Button < Fron::Component
tag 'button Click Me!'
end
class MyGreeter < MyComponent
# This will create a span inside the component
component :text, :span
# This will create a Button component defined above
component :button, Button
on :click, 'button', :greet
def greet
# The defined components are available as instance variables
@text.text = 'Hello There!'
@text.style.border = '1px solid #000'
end
end
As you can see we composed a Button
component into the MyGreeter
component.