extend
extend is a higher-order method used to augment an instance with additional properties or methods.
In general, it is not recommended to extend the properties or methods of an instance, as this increases the learning curve. Unless there is a specific need within the team to customize the behavior of an instance, such extensions are discouraged.
- I am 1
- I am target
- I am 3
logger
Extending the $ Bottom Layer
Similar to jQuery, you can also use fn.extend to extend the properties or methods of the underlying instance; properties or methods extended from fn will be applied to all instances.
- I am 1
- I am target
- I am 3
logger
Extended Template Syntax
Using extend to add attributes or functions can enhance template syntax functionality and even provide component-specific syntactic sugar. However, avoid unofficial template syntaxes, as they impose learning costs and degrade the development experience when overused.
Extended Attributes
You can set extended attributes in templates using :. Below, we extend a red attribute; when red is true, the text color becomes red:
$.fn.extend({
set red(bool){
if(bool){
this.css.color = "red";
}else{
this.css.color = '';
}
}
});
{{count}}
In this example, we added a red attribute to the template syntax. When count % 3 is not 0, the font color will change to red.
Extension Methods
You can also make the method available in template syntax by extending it with extend. The method name is the part before the colon. Here, we extend a color template syntax, and the following arguments will be passed to the defined extension method.
Here, the always attribute is set to true, indicating 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 additional parameters to 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
So far, you should have realized that many template syntax features on ofa.js are actually extended through extend:
class,attrmethods run every time the view is refreshedon,onefunction bindings only run once
You can refer to the example below to better understand the template rendering principle of ofa.js.
class always => {{classalways}}
attr always => {{attralways}}
on always => {{onalways}}