jQuery-QueryBuilder icon indicating copy to clipboard operation
jQuery-QueryBuilder copied to clipboard

Error in .on('rulesChanged.queryBuilder') function when calling getRules

Open cormip opened this issue 6 years ago • 2 comments

Plugin initializes normally, and can load previously saved rules at initialization without problem.

I've added an auto-save feature using the "rulesChanged.queryBuilder API Event as follows:

$('#queryBuilder').on('rulesChanged.queryBuilder', function(evt) {
        const blockRules = $('#queryBuilder').queryBuilder('getRules')
        console.log('Rule Changed!', blockRules)
        if (blockRules) {
            //Save the rule
            //saveRules function here
        }
    })

The problem arises if I try to clear or change the ruleset on an already initialized queryBuilder:

$('#queryBuilder').queryBuilder('clear')

or

$('#queryBuilder').queryBuilder('setRules', rules, true)

Either of the calls above will trigger the rulesChanged event, resulting in the getRules method crashing with the error:

/node_modules/jQuery-QueryBuilder/dist/js/query-builder.js:1697 Uncaught TypeError: Cannot read property 'each' of null at parse (/node_modules/jQuery-QueryBuilder/dist/js/query-builder.js:1697) at QueryBuilder.validate (/node_modules/jQuery-QueryBuilder/dist/js/query-builder.js:1749) at QueryBuilder.getRules (/node_modules/jQuery-QueryBuilder/dist/js/query-builder.js:1779)

I can probably work around it by adding an ugly try/catch or using beforeClear to destroy the listener and rebuild it again, but there really should be an integrated solution.

cormip avatar Oct 22 '19 20:10 cormip

thanks for the solution.

this works:

this.builder.off("rulesChanged.queryBuilder");
this.builder.queryBuilder("setRules", rules);
this.builder.on("rulesChanged.queryBuilder", (e, level) => {...});

tlyau62 avatar Nov 10 '20 07:11 tlyau62

another workaround is adding a settimeout to cause the getRules to run async.

$('#queryBuilder').on('rulesChanged.queryBuilder', function(evt) {
  setTimeout(() => {
    // get rules..
  }, 0)
}

tlyau62 avatar Aug 02 '21 03:08 tlyau62