问题:
如何在浏览器解析字符串或任何对象时拦截它,以便在实例化之前以自定义方式对其进行格式化。
来源:
可以使用生命周期回调 自定义元素完成:
var proto = Object.create(HTMLElement.prototype);
proto.createdCallback = function() {...};
proto.attachedCallback = function() {...};
var XFoo = document.registerElement('x-foo', {prototype: proto});
逻辑:
查询:
那么如何使用下面示例中的字符串sz
来完成它?
format = {
'abc123': function(p){
spl = p.split(' ');
spl[1]='<span style="color:red">'+ spl[1] +'</span>';
spl[4]='<span style="color:orange">'+ spl[4] +'</span>';
return spl.join(' ');
},
'123abc': function(p){'...'}
}
Object.defineProperties(String.prototype,{
format: {value:
function(){
var spl, cnt, ia, itm
spl = this.split(' ');
cnt = -1;
for(ia in spl){
itm = spl[ia];
if(itm[0] == '%'){
cnt++;
spl[ia]='<span style="'+ arguments[cnt] +'">'+ itm.slice(1) +'</span>';
}
}
return spl.join(' ');
}},
fmt: {get:
function(){
spl = this.split('¦');
ref = spl[0];
str = spl[1];
return format[ref](str);
}}
});
sx = "I'm %Formatted with the %standardised method!".format('color:blue','color:red');
sy = "abc123¦I'm Formatted with a custom method!".fmt;
sz = "123abc¦I have no method call, but want to be formatted as I'm parsed!";
d1.innerHTML = sx +'<br>'+
sy +'<br>'+
sz +'<br>';