Ale.js

Method

1.0.0Updated content:

In version 1.0.0 and later, use this in any function in the methods parameter to refer to the ale component object after rendering.


Also, in version 1.0.0 and later, you can also dynamically set or override the methods property when the component is rendered.

Start

Let’s follow the tutorial for the component life, or an example of a timer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Ale("timer", {
template: function(){
return "<span>Now Time: </span>" + this.data.time
},
data: {
time: new Date().toLocaleTimeString()
},
life: {
mounting: function(){
/* Need to use the arrow function here, because this will not be bound */
this.timer = setInterval(() => {
this.data.time = new Date().toLocaleTimeString();
}, 1000);
},
unmounting: function(){
clearInterval(this.timer);
}
}
})

Ale.render("timer", {
el: "#app"
})

</p

I don’t know if you noticed that our timer is added directly to this:

1
2
3
4
/* Note here, directly bound to the Ale component object (this) */
this.timer = setInterval(() => {
this.data.time = new Date().toLocaleTimeString();
}, 1000);

However, if we are not careful, the added function has the same name as the built-in function in Ale Component Object, then there will be some unknown bugs.

At this point, we recommend that you add the function to the built-in property methods in the Ale component object!

Let’s modify the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Ale("timer", {
template: function(){
return "<span>Now Time: </span>" + this.data.time
},
data: {
time: new Date().toLocaleTimeString()
},
life: {
mounting: function(){
/* Note here, binding methods on */
this.methods.timer = setInterval(() => {
this.data.time = new Date().toLocaleTimeString();
}, 1000);
},
unmounting: function(){
clearInterval(this.methods.timer);
}
}
})

The instance is executable normally.

At the same time, you can also set methods when the component is defined:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Ale("test", {
template: "test",
methods: {
/* Define a function called testFn */
testFn: function(){
alert("test!")
}
},
life: {
mounting: function(){
/* 动态调用它 */
this.methods.testFn();
}
}
})

Advanced

Like the data property, the methods property is automatically bound to all elements and child elements of the component, accessible via this.methods:

1
template: "<span onclick='this.methods.testFn()'>Click me!</span>"

Found some errors? Edit on Github!