Ale.js

Component Foundation

Preface

In the introductory chapter, you’ve learned some basic definitions and functions for rendering components. These foundations will not appear in this chapter. If you have not already learned some of the content, please visit the Introduction page.

Start

On the introduction page, we have some knowledge of the template property:

1
2
3
4
//Define a component called com1
Ale("com1", {
template: "HelloWorld"
});

In fact, the template property also supports receiving a function, but the specific template needs to be returned using return:

1
2
3
4
5
6
7
8
9
10
11
12
13
//Define a component called com1
Ale("com1", {
template: function(){
return "HelloWorld";
}
});

// Of course, you can also use ES6 syntax to define templates
Ale("com1", {
template(){
return "HelloWorld";
}
});

Then we need to render this component:

1
2
3
Ale.render("com1", {
el: "#app" /* Target element selector */
})

So, what are the benefits of setting the template property to a function? In fact, it can automatically bind a property called data.

For example, we define a value named name in the data attribute and then render it:
[Before version 1.0.0, the actual use of this refers to this.data, and the 1.0.0 version replaces this with the ale component object after rendering](if you don’t know this sentence is What do you mean, please leave it alone)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Ale("com1", {
template: function(){
return "Hello " + this.data.name;
},
data: {
name: "World"
}
});

/* Remember to use the ES6 arrow function, because the arrow function does not bind this
Ale("com1", {
template: () => {
return "Hello " + this.data.name; //Error!
},
data: {
name: "World"
}
});
*/

Advanced operation

Data

You can also dynamically set data when the component is rendered. Among them, the attribute with the same name will be reassigned:

1
2
3
4
5
6
Ale.render("com1", {
el: "#app",
data: {
name: "Ale.js" /* Will be reassigned to Ale.js */
}
})

Of course, the same component can also be rendered multiple times:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Ale.render("com1", {
el: "#app"
})

Ale.render("com1", {
el: "#app2"
})

Ale.render("com1", {
el: "#app3",
data: {
name: "Ale.js" /* Can also have different properties */
}
})

Local component

If you don’t add a name when defining a component, the Ale() function will return you a Ale local component build object:

1
2
3
4
5
6
/* Define a variable to receive the Ale local component generation object */
var com = Ale({
template: function(){
return "HelloWorld";
}
})

You can render this component using the render function of Ale local component generation object:

1
2
3
com.render({
el: "#app"
})

Found some errors? Edit on Github!