Migrazione da jComponent 19
Sostituisci ogni API di jComponent 19 rimossa o modificata con il suo equivalente in jComponent 20, comprese le modifiche che falliscono senza errori.
In questa pagina
Questa guida porta un'applicazione da jComponent 19 a jComponent 20.015. Mostra il sostituto di ogni funzione, attributo e impostazione rimossi o modificati e segnala le modifiche che non producono errori nella console del browser, perché sono quelle che un test rapido non rileva.
Aggiorna i file della CDN
Sostituisci entrambi i file. Il bundle contiene ancora jQuery, Tangular e le funzioni di routing, quindi non serve caricare altro.
| jComponent 19 | jComponent 20 |
|---|---|
https://cdn.componentator.com/spa.min@19.js | https://cdn.componentator.com/spa.min@20.js |
https://cdn.componentator.com/spa.min@19.css | https://cdn.componentator.com/spa.min@20.css |
Ordine di lavoro consigliato
- Sostituisci i file della CDN e apri l'applicazione con la console del browser visibile.
- Modifica prima il markup: gli elementi
data---,data-bindedata-scopevengono ignorati, quindi non puoi testare nient'altro finché non li converti. - Cerca nel codice i pattern di Modifiche che falliscono in silenzio e correggili. La console non li segnala.
- Correggi gli errori riportati dalla console, come
VALID is not definedo$(...).scope is not a function. - Adatta i form, poi prova a mano ogni form: vuoto, non valido, valido e dopo un reset.
- Prova le schermate che caricano dati, perché le callback AJAX ricevono meno argomenti.
Modifiche che falliscono in silenzio
Ciascuno di questi casi viene eseguito senza errori in 20.015, ma fa la cosa sbagliata. Cerca nel tuo codice quanto riportato nella colonna di sinistra.
| jComponent 19 | jComponent 20 |
|---|---|
WATCH('user.name', function(path, value, type) { | WATCH('user.name', function(value, flags, path) { |
WATCH('user.*', function(path) { | WATCH('user', function(value, flags, path) { |
RESET('form.*'); | RESET('form'); |
GET('form @modified') | COMPONENTS('form @modified') |
return value; // a non-empty string means valid | return !!value; |
self.setter = function(value, path, type) { | self.setter = function(value, path, flags) { |
SET('user.name', 'Ann', 100); | setTimeout(() => SET('user.name', 'Ann'), 100); |
SET('form.city', 'Vienna', true); | SET('form.city @reset', 'Vienna'); |
PUSH('cart.items', [2, 3]); | [2, 3].forEach(item => PUSH('cart.items', item)); |
SETTER('box', 'show', 1); | SETTER('box/show', 1); |
FIND('box', function(com) { | WAIT(() => FIND('box'), function() { |
<div data---="box__user.name__size:2"></div> | <ui-component name="box" path="user.name" config="size:2"></ui-component> |
<ui-plugin path="address"> | <ui-plugin path="?.address"> |
config="text;format:2" | config="text:value.format(2)" |
AJAX('GET /orders/', function(response, err) { | ON('response', opt => status = opt.status); |
Anche una dichiarazione PLUGIN() senza un elemento <ui-plugin> smette di funzionare. Vedi Scope e plugin.
Form e validazione
VALID(), CAN(), DISABLED(), INVALID(), CHANGE(), MODIFIED() e DEFAULT() sono state rimosse. Leggi lo stato di un form con COMPONENTS() e ERRORS() e modificalo con i flag. Form e validazione descrive il nuovo modo di lavorare.
| jComponent 19 | jComponent 20 |
|---|---|
VALID('form.*') | COMPONENTS('form @invalid').length === 0 |
CAN('form.*') | can('form') (la funzione qui sotto) |
DISABLED('form.*') | !can('form') |
ERRORS('form.*') | ERRORS('form @touched', list => console.log(list.length)) |
CHANGE('form.*'); | UPD('form @change'); |
CHANGE('form.*', false); | RESET('form'); |
MODIFIED('form.*') | COMPONENTS('form @modified').map(com => com.path.toString()) |
DEFAULT('filter.*'); | SET('filter @default', {}); |
INVALID('form.name'); | COMPONENTS('form.name').forEach(com => com.reconfigure({ touched: 1, invalid: true })); |
RESET('form.*'); | RESET('form'); |
CAN() non ha un sostituto diretto, quindi tieni una piccola funzione nella tua applicazione:
function can(path) {
return COMPONENTS(path + ' @invalid').length === 0 && COMPONENTS(path + ' @touched').length > 0;
}ERRORS() richiede una callback. Senza, genera l'errore r is not a function. Nella 19 restituiva i campi toccati e non validi. Nella 20 passa tutti i campi non validi, quindi aggiungi il flag @touched per ottenere il risultato di prima:
ERRORS('form @touched', list => console.log(list.length)); // 0
SET('form.name @change', '');
ERRORS('form @touched', list => console.log(list.map(com => com.path.toString()))); // ["form.name"]I path non accettano più .*. Non corrisponde a nulla e non viene mostrato alcun errore. ERRORS() segnala quindi come valido un form con errori:
ERRORS('form.*', list => console.log(list.length)); // 0
ERRORS('form', list => console.log(list.length)); // 1GET('form @modified') restituisce l'intero modello nella 20. Raccogli tu stesso i campi modificati:
SET('form.city @change', 'Prague');
var changed = {};
COMPONENTS('form @modified').forEach(com => changed[com.path.toString().split('.').pop()] = com.get());
console.log(changed); // {"city":"Prague"}Il risultato di self.validate viene interpretato in modo diverso. Nella 19 qualsiasi valore truthy era valido. Nella 20 una stringa non vuota è un messaggio di errore, quindi un validatore che restituisce il valore segna come non valido un campo compilato. Anche un numero come value.length non è valido. Restituisci un booleano:
self.validate = function(value) {
return !!value;
};self.validate = function(value) {
return value.length > 0;
};self.validate ha perso anche il secondo argomento, init. Se la prima esecuzione richiede un trattamento diverso, usa un tuo flag:
COMPONENT('field', function(self, config) {
var init = true;
self.validate = function(value) {
console.log(init);
init = false;
return true;
};
});Associare un input
L'attributo data-jc-bind viene ignorato, quindi l'input non scrive nel modello. Chiama self.autobind20() quando l'HTML esiste già:
COMPONENT('textbox', function(self) {
self.make = function() {
self.html('<input type="text" />');
self.autobind20();
};
});Le funzioni globali FORMATTER() e PARSER() sono state rimosse. Registrale sul componente:
self.formatter(function(path, value) {
return value ? value.toUpperCase() : value;
});self.parser(function(path, value) {
return value ? value.toLowerCase() : value;
});Osservatori e path
Gli argomenti di un osservatore hanno cambiato ordine e il codice continua a funzionare con i valori sbagliati. Path descrive gli osservatori nella 20.
| jComponent 19 | jComponent 20 |
|---|---|
WATCH('user.name', function(path, value, type) { | WATCH('user.name', function(value, flags, path) { |
self.watch('user.name', function(path, value, type) { | self.watch('user.name', function(value, flags, path) { |
exports.watch('count', function(value, path, type) { | exports.watch('count', function(value, flags, path) { |
WATCH('user.*', function(path) { | WATCH('user', function(value, flags, path) { |
WATCHONCE('user.name', function(path, value) { | UNWATCH('user.name', once); dentro la callback |
ON('watch', 'user.name', function(path, value) { | WATCH('user.name', function(value) { |
Un osservatore su un path padre viene eseguito anche per i path sottostanti, quindi WATCH('user', ...) sostituisce il carattere jolly.
Scrivere nel modello
Il terzo argomento di SET() è stato rimosso. Un ritardo o un flag di reset passato in quella posizione viene ignorato e il valore viene scritto subito.
| jComponent 19 | jComponent 20 |
|---|---|
SET('user.name', 'Ann', 100); | setTimeout(() => SET('user.name', 'Ann'), 100); |
SET('form.city', 'Vienna', true); | SET('form.city @reset', 'Vienna'); |
PUSH('cart.items', [2, 3]); | [2, 3].forEach(item => PUSH('cart.items', item)); |
PUSH('cart.items', 'tea'); su un path inesistente | SET('cart.items', ['tea']); |
NOTIFY('user.name'); | UPD('user.name'); |
EXT('user', { age: 30 }); | SET('user', Object.assign(GET('user'), { age: 30 })); |
MAKE(function(obj) { | Un oggetto semplice |
EVALUATE('user.age', 'value >= 18') | FN('value => value >= 18')(GET('user.age')) |
REMOVECACHE('token'); | CACHE('token', null, '1 day'); |
CL_INIT('colors', function(next) { | CLINIT('colors', function(next) { |
PUSH() su un path che non esiste non notifica alcun osservatore, quindi crea l'array con SET().
Il terzo argomento di CACHEPATH() ora è un valore predefinito e i valori salvati da jComponent 19 non vengono letti:
CACHEPATH('filter.q', '1 day', 'all');
console.log(GET('filter.q')); // allChiamare componenti e funzioni
| jComponent 19 | jComponent 20 |
|---|---|
SETTER('box', 'show', 1); | SETTER('box/show', 1); |
RECONFIGURE('box', 'size:2'); | SETTER('box/reconfigure', 'size:2'); |
RETURN('box/name') | FIND('box').name |
FIND('box', function(com) { | WAIT(() => FIND('box'), function() { |
EXEC(true, 'FUNC.start', 'now'); | EXEC('FUNC.start @important', 'now'); |
AEXEC('FUNC.save', 1) | () => EXEC('FUNC.save', 1) |
ADD('box__user.name', '#panel'); | $('#panel').append('<ui-component name="box" path="user.name"></ui-component>'); |
Attributi del markup
Le forme con attributi vengono ignorate senza errori e gli elementi restano vuoti. Usa gli elementi personalizzati descritti in Usare i componenti e Associazione dei dati.
| jComponent 19 | jComponent 20 |
|---|---|
<div data---="box__user.name__size:2"></div> | <ui-component name="box" path="user.name" config="size:2"></ui-component> |
<span id="name" data-bind="user.name__text"></span> | <ui-bind id="name" path="user.name" config="text"></ui-bind> |
<div id="box" data-scope="panel"> | <ui-plugin id="box" path="panel"> |
Scope e plugin
Nella 20 non esiste un oggetto scope. L'elemento <ui-plugin> è lo scope e $(selector).plugin() restituisce l'istanza. Un elemento con path ? al di fuori di un <ui-plugin> non viene renderizzato. Plugin descrive l'oggetto plugin.
| jComponent 19 | jComponent 20 |
|---|---|
var scope = $('#panel').scope(); | var plugin = $('#panel').plugin(); |
console.log(scope.path); // invoice | console.log(plugin.path.toString()); // invoice |
scope.watch('number', function(path, value) { | plugin.watch('number', function(value, flags, path) { |
<ui-plugin path="address"> annidato in un plugin | <ui-plugin path="?.address"> |
<ui-plugin path="!shared"> | <ui-plugin path="shared"> |
<ui-plugin path="login" default="{ user: 'guest' }"> | exports.set('user', 'guest'); nel plugin |
function loginready(path, element) { | function loginready(element) { |
config="text:?/format" | config="text:PLUGINS.contact.format(value)" |
Un <ui-plugin> annidato non estende più il path del suo genitore. Scrivi ? nel path per ottenere il risultato di prima, altrimenti il plugin legge un path globale con lo stesso nome:
<ui-plugin path="order">
<ui-plugin path="?.address">
<ui-bind id="city" path="?.city" config="text"></ui-bind>
</ui-plugin>
</ui-plugin>Un plugin ha bisogno del suo elemento. Nella 19 PLUGIN() creava l'istanza da solo. Nella 20 la callback viene eseguita solo se esiste un elemento <ui-plugin> con quel path, quindi un plugin senza elemento non si avvia mai:
<ui-plugin path="orders"></ui-plugin>| jComponent 19 | jComponent 20 |
|---|---|
exports.extend('filter', { page: 2 }); | exports.set('filter', Object.assign(exports.get('filter'), { page: 2 })); |
PLUGINS.orders.reset(); | RESET(PLUGINS.orders.path.toString()); |
exports.api('/api/ orders_list', { page: 1 }, function() { | API('/api/', 'orders_list', { page: 1 }, function() { |
console.log(exports.modified); // {"city":"Prague"} | Il codice qui sotto |
exports.modified restituisce l'intero modello e azzera lo stato dei componenti. Raccogli prima i campi modificati:
var changed = {};
COMPONENTS(exports.path + ' @modified').forEach(com => changed[com.path.toString().split('.').pop()] = com.get());
RESET(exports.path.toString());
console.log(changed); // {"city":"Prague"}Comandi di ui-bind
Diversi comandi di <ui-bind> sono stati rimossi e la maggior parte viene saltata senza errori. L'espressione di un comando è semplice JavaScript, quindi una chiamata al suo interno sostituisce la maggior parte di essi. Il riferimento di ui-bind elenca i comandi della 20.
| jComponent 19 | jComponent 20 |
|---|---|
config="text;format:2" | config="text:value.format(2)" |
config="text;currency:eur" | config="text:value.currency('eur')" |
config="text;default:'none'" | config="text:value == null ? 'none' : value" |
config="text;helper:pluralize('no items','# item','# items','# items')" | config="text:value.pluralize('no items','# item','# items','# items')" |
config="text;selector:b" | config="text" child="b" |
config="checked input" | config="checked" |
config="init:FUNC.start;text" | config="exec:FUNC.start;text" |
config="click:FUNC.open" | <button id="a" class="exec" data-exec="FUNC.open">Open</button> |
config="setter:'box/show',value" | config="exec:FUNC.show" |
config="config:'size:' + value" | <ui-component name="box" config="=size:ui.size"></ui-component> |
Il valore false viene visualizzato come vuoto con il comando text. Converti il valore in stringa:
<ui-bind id="a" path="order.count" config="text:value + ''"></ui-bind>Componenti
Il path di un componente ora è un oggetto. Confrontarlo con una stringa dà false e i metodi delle stringhe come split() non esistono su di esso, quindi convertilo prima. Il terzo argomento di self.setter è un oggetto con i flag al posto di un numero. Creare componenti descrive i delegate.
| jComponent 19 | jComponent 20 |
|---|---|
self.path === 'form.name' | self.path.toString() === 'form.name' |
self.setter = function(value, path, type) { | self.setter = function(value, path, flags) { |
type === 0 | flags.init |
self.notify(); | self.upd(); |
self.faicon('home') | self.icon('home') |
self.scopepath('user.age') | self.makepath('user.age') |
self.inc(2); | self.set(self.get() + 2); |
self.extend({ b: 2 }); | self.set(Object.assign(self.get(), { b: 2 })); |
self.dirty() | !config.touched |
self.dirty(false); | self.touch(); |
self.invalid(); | self.reconfigure({ touched: 1, invalid: true }); |
self.skip(); prima di self.set(2); | self.rewrite(2); |
self.main() | self.element.parent().component() |
self.exec('show', 1) | self.element.SETTER('*/show', 1) |
self.data('page', 2); | Una variabile dentro il componente |
Nella 20 gli argomenti di self.state(type, what) hanno valori diversi. Leggi lo stato da config:
self.state = function() {
if (config.touched && config.modified && !changed) {
changed = true;
console.log('changed');
}
};self.bindchanges() è stato rimosso. Confronta il valore nel setter:
var last;
self.setter = function(value) {
if (value !== last) {
last = value;
console.log(value);
}
};Macro e associazioni virtuali
MACRO(), il comando macro, VBIND(), VBINDARRAY() e il comando vbindarray sono stati rimossi. Riscrivi una macro come componente e un'associazione virtuale come comando template con Tangular.
| jComponent 19 | jComponent 20 |
|---|---|
MACRO('clicks', function(self, element) { | COMPONENT('clicks', function(self) { |
config="macro:clicks" | <ui-component id="c" name="clicks" path="counter"></ui-component> |
VBIND('<div><b data-bind=".name__text"></b></div>') | config="template" |
VBINDARRAY('<li data-bind=".name__text"></li>', '#list') | config="template" |
config="vbindarray" | config="template" |
<ui-component id="c" name="clicks" path="counter"></ui-component>COMPONENT('clicks', function(self) {
self.make = function() {
self.event('click', () => self.set((self.get() || 0) + 1));
};
self.setter = function(value) {
self.text('Clicked ' + (value || 0));
};
});Un elenco che usava VBINDARRAY() diventa un template:
<ul id="list">
<ui-bind path="rows" config="template">
<script type="text/html">{{ foreach m in value }}<li>{{ m.name }}</li>{{ end }}</script>
</ui-bind>
</ul>L'oggetto M
M esiste ancora ed è lo stesso oggetto di jComponent e MAIN. M.version, M.components e M.binders funzionano come prima. I metodi che modificavano il modello sono stati rimossi o accettano argomenti diversi, quindi usa le funzioni globali.
| jComponent 19 | jComponent 20 |
|---|---|
M.set('user.name', 'Ann'); | SET('user.name', 'Ann'); |
M.inc('user.age', 2); | INC('user.age', 2); |
M.push('user.tags', 'new'); | PUSH('user.tags', 'new'); |
AJAX e API
La callback di AJAX() riceve solo la risposta e AJAX() non restituisce più una Promise. Il riferimento Funzioni globali descrive AJAX().
| jComponent 19 | jComponent 20 |
|---|---|
AJAX('GET /orders/', function(response, err) { | ON('response', opt => status = opt.status); |
AJAX('GET /orders/').then(function(response) { | new Promise(resolve => AJAX('GET /orders/', resolve)).then(function(response) { |
AJAX('GET /orders/ error', () => console.log('callback')); | AJAX('GET /orders/ ERROR', () => console.log('callback')); |
AJAX('GET /orders/ {"X-Token":"abc"}', function() { | ON('request', opt => opt.headers['X-Token'] = 'abc'); |
AJAXCONFIG('secure', function(options) { | ON('request', function(options) { |
AJAXCACHE('GET /orders/', null, NOOP, '1 minute'); | AJAX('GET /orders/ <1 minute>', NOOP); |
AJAX('GET /orders/', null, 'orders', 100); | setTimeout(() => AJAX('GET /orders/', 'orders'), 100); |
API('/api/ users_save', { name: 'Ann' }, function() { | API('/api/', 'users_save', { name: 'Ann' }, function() { |
DAPI('users_save', { name: 'Ann' }, function() { | TAPI('users_save', { name: 'Ann' }, function() { |
Per leggere il codice di stato di una risposta, ascolta l'evento response prima della richiesta:
var status = 0;
ON('response', opt => status = opt.status);
AJAX('GET /orders/', function(response) {
console.log(response.error, status); // denied 403
});Impostazioni
| jComponent 19 | jComponent 20 |
|---|---|
DEF.validators.email | DEF.regexp.email |
DEF.pathcommon | DEF.path.common |
DEF.pathcl | DEF.path.cl |
DEF.environment | DEF.env |
DEF.languagehtml = 'sk'; | DEF.language = 'sk'; |
Queste impostazioni non esistono più: ajaxcredentials, ajaxcredentialshtml, ajaxerrors, customelements, delay, delaybinder, delaykeypress, delaypref, delayrepeat, delaywatcher, fallbackcache, importcache, jsoncompress, jsonconverter, jsondate, keypress, makeurl, monitor, prefixcssmacros, repeatfocus, scope, secret e versioncomponents. Il riferimento DEF elenca le impostazioni della 20.
Eventi
| jComponent 19 | jComponent 20 |
|---|---|
ON('destroy', name => console.log('removed', name)); | self.destroy = () => console.log('removed', self.name); |
ON('watch', 'user.name', function(path, value) { | WATCH('user.name', function(value) { |
L'evento exec non viene più emesso. WW e WH non sono impostati finché la libreria non si avvia, quindi leggili dentro ON('ready', ...). Il riferimento Eventi elenca gli eventi della 20.
Helper jQuery
| jComponent 19 | jComponent 20 |
|---|---|
$('#panel').components() | $('#panel').COMPONENTS() |
$('#panel').FIND('box') | $('#panel').COMPONENTS().findItem('name', 'box') |
$('#panel').RECONFIGURE('box', 'size:2'); | $('#panel').SETTER('box/reconfigure', 'size:2'); |
$('#panel').EMIT('hello', 1); | EMIT('hello', 1); |
Helper per stringhe, numeri, date e array
| jComponent 19 | jComponent 20 |
|---|---|
'Hello {name}'.arg({ name: 'Ann' }) | 'Hello {name}'.args({ name: 'Ann' }) |
'{{ name }}'.render({ name: 'Ann' }) | Tangular.render('{{ name }}', { name: 'Ann' }) |
'<b>Ann</b>'.removeTags() | '<b>Ann</b>'.replace(/<[^>]*>/g, '') |
'a=1&b=2'.parseEncoded() | Object.fromEntries(new URLSearchParams('a=1&b=2')) |
new Date(2026, 0, 5).toNumber() | +new Date(2026, 0, 5).format('yyyyMMdd') |
new Date(2026, 0, 5).parseDate() | new Date(2026, 0, 5) |
(5).between({ 1: 'low', 10: 'high' }) | value < 10 ? 'low' : 'high' |
tasks.async(() => console.log('done')); | tasks.wait((task, next) => task(next), () => console.log('done')); |
String.parseConfig() non accetta più una callback e, se gliene passi una, la ignora senza errori. Scorri l'oggetto restituito:
var config = 'size:2;open:true'.parseConfig();
for (var key in config)
console.log(key, config[key]);Funzioni senza sostituto
Queste funzioni globali sono state rimosse e 20.015 non ha un equivalente diretto.
| jComponent 19 | jComponent 20 |
|---|---|
WAPI, WAPI_INIT, AJAXCACHEREVIEW | Nessun sostituto |
DEBUG, STOPDEBUG | Nessun sostituto |
QUEUE, REPEAT, WORKFLOW | Nessun sostituto |
PLUGINABLE, VERSION, IMPORTCACHE | Nessun sostituto |
CLEARCACHE, REWRITE, REWRITE2, NOTMODIFIED, BIND, OPT | Nessun sostituto |
Un form completo
Questo form ha due campi obbligatori e un pulsante che si abilita quando il form è valido. Entrambe le versioni si comportano allo stesso modo: il primo salvataggio segnala i due path non validi e un salvataggio con i campi compilati restituisce il modello.
Prima, in jComponent 19:
<ui-component name="textbox" path="form.name" config="label:Name;required:true"></ui-component>
<ui-component name="textbox" path="form.email" config="label:Email;required:true;email:true"></ui-component>
<button id="save" disabled>Save</button>
<script>
COMPONENT('textbox', function(self, config) {
self.validate = function(value) {
if (!config.required)
return true;
if (!value)
return false;
return config.email ? DEF.validators.email.test(value) : true;
};
self.make = function() {
self.html('<label>' + config.label + '</label><input type="text" data-jc-bind />');
};
});
var form = { name: '', email: '' };
WATCH('form.*', function(path, value, type) {
$('#save').prop('disabled', DISABLED('form.*'));
});
function save() {
CHANGE('form.*');
if (!VALID('form.*')) {
console.log(ERRORS('form.*').map(com => com.path));
return;
}
console.log(GET('form @reset'));
}
</script>Dopo, in jComponent 20:
<ui-component name="textbox" path="form.name" config="label:Name;required:true"></ui-component>
<ui-component name="textbox" path="form.email" config="label:Email;required:true;email:true"></ui-component>
<button id="save" disabled>Save</button>
<script>
COMPONENT('textbox', function(self, config) {
self.validate = function(value) {
if (!config.required)
return true;
if (!value)
return false;
return config.email ? DEF.regexp.email.test(value) : true;
};
self.make = function() {
self.html('<label>' + config.label + '</label><input type="text" />');
self.autobind20();
};
});
var form = { name: '', email: '' };
function can(path) {
return COMPONENTS(path + ' @invalid').length === 0 && COMPONENTS(path + ' @touched').length > 0;
}
WATCH('form', function(value, flags, path) {
$('#save').prop('disabled', !can('form'));
});
function save() {
UPD('form @change');
ERRORS('form', function(list) {
if (list.length) {
console.log(list.map(com => com.path.toString()));
return;
}
console.log(GET('form @reset'));
});
}
</script>