In this Page, we will create our first component —— HelloMag . It is used to show a welcome message for people who login. if people aren't logged in yet, the component will prompt a window. For simplicity, only username is required during the login operation.
<div id="hello">
Hello, Guest
</div>
<!-- include mag.js -->
<script src="https://cdn.jsdelivr.net/gh/magnumjs/mag.js/dist/mag.0.21.2.min.js"></script>
<script>
//Create your first module:
var HelloModule = {view:function(){}}
//Create Your First Component:
var HelloMag = mag.create(
'hello',
HelloModule
);
//Initialize component:
var component = HelloMag({
data: {username: "leeluolee"}
});
</script>
RESULT
mag.create
mag.create will create a Component that can be executed.
template Id
a Component needs a template to describe its structure.
data/props
component's model, but it is just a Plain Object. the data
passed to new Component
and the data
passed to mag.create
are merged.
This component only shows static message until now, we should make it live by using interpolation.
Hello, <username/>
RESULT
if/else
to show other message if the user is not logged inif(props.username){
state.b = props.username
state.guest = null;
} else {
state.user = null;
}
Null removes the element.
RESULT
Login/Logout
by eventIn this step , we need to add two events to deal with the Login and Logout operation.
<div id="hello">
<div class="user"><span>Hello, <b>{username}</b>.
<a href='#'>Logout</a>
</span>
</div>
<div class="guest"><span>Sorry, Guest.
Please <a href='#'>Login</a>
</span>
</div>
</div>
Tips
in MagJS, the
_on
prefixed attribute will be considered as a native JavaScript event ui event
we add two operations in the template above:
Login: the keyword this
in the template just point to the component
itself. so we need to add a method named login in HelloMag module.
Logout: the model's root in template points to component.props
. so in this example, we just simply clear the username in props
.
var HelloModule = {
view: function(state, props) {
if (props.username) {
state.user = {
a: {
_onClick: function() {
props.username = ''
}
}
}
state.b = props.username
state.guest = null;
} else {
state.guest = {
a: {
_onClick: function() {
props.username = prompt("please enter your username", "")
}
}
}
state.user = null;
}
}
}
RESULT
MagJS's data-binding is based on observing the state and props objects. some builtin (.e.g event, onClick) will trigger the component's redraw phase automatically. you can also trigger the redraw manually using component.draw
just like the example above, the usage of state
is flexible.
no matter how you use the
state
. the component will always enter into the redraw phase when props or state is changed.
In this chapter, we create a super simple component named HelloMag.
you can consider MagJS's component as a small mvvm
realization.
you can also check the more comprehensive example——Login/logout with undo.