extend
extend is a high-order method used to extend the properties or methods of an instance.
Under normal circumstances, it is not recommended for users to extend the properties or methods of an instance, as this increases the learning cost. Unless there is a special scenario within the team that requires customizing the behavior of the instance, it is not recommended to do so.
- I am 1
- I am target
- I am 3
logger
Extend $ Bottom Layer
Similar to jQuery, you can also extend the properties or methods of the underlying instance through fn.extend; properties or methods extended from fn will apply to all instances.
- I am 1
- I am target
- I am 3
logger
Extended Template Syntax
By using extend to extend properties or functions, you can enhance the functionality of template syntax, and even provide exclusive template syntactic sugar for components. However, it is important to note that you should try not to use non-official template syntax, as they impose a certain learning cost on users, and a large amount of non-official template syntactic sugar can degrade the development experience.
Extended Attributes
You can set extended attributes in the template using :. Below, we will extend a red attribute; when red is true, the font color turns red:
$.fn.extend({
set red(bool){
if(bool){
this.css.color = "red";
}else{
this.css.color = '';
}
}
});
{{count}}
In this example, we added a red property to the template syntax. When count % 3 is not 0, the font color will turn red.
Extension Methods
You can also use the extend extension method to make it available in template syntax. The method name is the part before the colon. Here, we extended a color template syntax, and the following parameters will be passed to the defined extension method.
Here, the always attribute is set to true, which means that the defined method will be called every time the component needs to refresh the interface. If always is not set, this template syntax function will only run once.
Among them, options provides more parameters that can help you develop more customized template syntax:
$.fn.extend({
color(value, func, options){
const bool = func();
if(bool){
this.css.color = value;
}else{
this.css.color = '';
}
}
});
$.fn.color.always = true;
{{count}}
Template Syntax Principles
By now, you should have understood that many template syntaxes on ofa.js are actually extended through extend:
class,attrmethods run every time the view is refreshedon,onefunction bindings run only once
You can look at the example below to better understand the template rendering principle of ofa.js:
class always => {{classalways}}
attr always => {{attralways}}
on always => {{onalways}}