Jonas Schreiber
Jonas Schreiber

Reputation: 457

Instantiating Objects Dynamically (Mistic Query Builder)

I'm new to JavaScript, focusing primarily on Java/PHP development. The JS applications I've built in the past have been pretty hackish, untestable, and unextensible.

I'm now trying to create an application that interfaces with data in a more appropriate manner. Basically I'm building a user interface for creating rules/actions that our support team and end users can access. The logic for the application contains a lot of Boolean and logical operators and just requires that some arbitrary set of conditions be met, and then will apply certain actions.

So, I've pretty much settled on a query builder type of application, and I love Mistic's work. Unfortunately, we don't have a Node.js server. So, I've set about finding ways to make this work with vanilla JS/jQuery. One iteration used Knockout.js. However, I found that API to be difficult to work with.

Now, I found this JSFiddle, which uses Mistic's work in a standalone version. I'd prefer to use this, but one thing I can't quite piece together is how to create multiple Query Builders dynamically. (Rules will appear in a table as shown in the second link, and I'll need an Add Row button).

$('#builder').queryBuilder({

sortable: true,

filters: [{
    id: 'core_ID',

I've tried using the jQuery .each() function to create query builders bound to each element with a class of builder, but to no avail.

$.each('.builder').queryBuilder({

Can you guys show me how you'd go about dynamically creating new QueryBuilder objects as shown in the third link?

Upvotes: 0

Views: 592

Answers (1)

x4rf41
x4rf41

Reputation: 5337

You use .builder as a selector, which means you select all elements that have a class="builder" attribute.

If that is so, then you should be able to just call $('.builder').queryBuilder(... and it should use all elements that have the class builder

EDIT: It does in fact do so. But the cakephp query builder doesn't allow it (for whatever reason). So you have to use each in the way that i describe.

if you want to use the each function, you would to it like that:

$( ".builder" ).each(function() {
  $( this ).queryBuilder(...);
});

Explanation:

$(".builder") selects all elements that have a class="builder" attribute. .each iterates over those elements. inside the function that is passed to each this contains the native DomElement (which is not a jquery element). Therefore $(this) gets the jQuery element for the DomElement and .queryBuilder is called on it.

you can call .queryBuilder on pretty much any jQuery element unless it is an array of elements (it will throw an error).

so basically any selector + each in the way I use it should work.

here is a working fiddle with your example using 4 querybuilders: http://jsfiddle.net/ap9gxo4L/42/

Upvotes: 1

Related Questions