Mick
Mick

Reputation: 1561

Replace variable in javascript

Apologies for all the code in this post, but I don't know how else to describe it.

I have some Javascript, which is in a Vue component (the component is to encapsulate a Datatable):

let table = $('#datatables-table').DataTable({ 

    "ajax": {
        "url": self.dataUrl,
        "type": "POST",

        "data": function(d){
            d.table = self.table;
        },

    },


"columns": self.tableColumns,
    order: [1, 'asc'],
    dom: "Bfrtip",
    responsive: false,//true wont let me hide columns
    "scrollY": "600px",
    "scrollCollapse": true,

    "paging": false,
    select: {
        style: 'single',
        selector: 'td:first-child',
        blurable: true

    },

    buttons: self.buttons,

});

I am trying to pass the buttons (self.buttons) configuration in, this is what I want it to look like:

[{extend:'remove', editor: editor},{extend:'create', editor: editor},{extend:'edit', editor: editor},],

The variables get populated, in my mounted method. via AJAX:

axios.get(self.tableUrl)
            .then(function (response) {

                self.tableHeaders = response.data.tableHeaders;
                self.panelTitle = response.data.panelTitle;
                self.table = response.data.table;
                self.editorFields = response.data.editorFields;
                self.tableColumns = response.data.tableColumns;
                self.buttons = response.data.buttons;

This is the PHP (Laravel), to form the response:

$dt->buttons = array(
    array('extend' => 'remove', 'editor' => 'editor'),
    array('extend' => 'create', 'editor' => 'editor'),
    array('extend' => 'edit', 'editor' => 'editor')

);

Then I do a JSON.stringify in the JS, but the problem here is that I end up with this:

"[{"extend":"remove","editor":"editor"},{"extend":"create","editor":"editor"},{"extend":"edit","editor":"editor"}]"

So, how can I pass the buttons in, so that they are not a string and the editor is not "editor" (double quoted).

I think I need to somehow pass it as a string, but remove the quotes.

Mick

Update: editor is defined above:

 let editor = new $.fn.dataTable.Editor({
                 "ajax": {
                "url": self.dataUrl,
                "type": "POST",
                data: {table: self.table}
            },

    table: "#datatables-table",
    idSrc: self.table + '.id',
    fields: [self.editorFields]
        });

Full code here: http://artisantinkerer.github.io/2016/12/15/Vue-Datatables.html

Upvotes: 1

Views: 112

Answers (1)

Bert
Bert

Reputation: 82489

If response.data.buttons is truly a javascript array, then you could replace the value of the editor property this way.

response.data.buttons.map(b => ({extend: b.extend, editor: editor}))

Or just not render the editor property at all from the server and map over and add it clientside.

Upvotes: 1

Related Questions