Home > OS >  javascript Dynamic function arguments
javascript Dynamic function arguments

Time:03-05

how to setup to use function arguments dynamically, i have tried many method and it doesn't work properly. Hope someone can help me, Thank you very much.

Function:

function initDropdown(type, placement, trigger, strategy, functions) {
    tippy('[data-cg-toggle="'   type   '"]', {
        zIndex: 99999,
        interactive: true,
        placement: placement,
        allowHTML: true,
        trigger: trigger,
        popperOptions: {
            strategy: strategy,
        },
        functions
    });
}

Init Functions

initDropdown('dropdown', 'bottom-end', 'click', 'fixed', {
    content(reference) {
        return content;
    },
    onShown(instance) {
        $($(instance)[0].reference).addClass('dropdown-toggled');
    },
    onHidden(instance) {
        $($(instance)[0].reference).removeClass('dropdown-toggled');
    }
});

initDropdown('dropdown', 'bottom-end', 'click', 'fixed', {
    onShown(instance) {
        var content = $($(instance)[0].reference).parent().children('.dropdown-menu')[0].innerHTML;
        $($(instance)[0].reference).addClass('dropdown-toggled');
        instance.setContent(content);
    },
    onHidden(instance) {
        $($(instance)[0].reference).removeClass('dropdown-toggled');
    },
});

CodePudding user response:

You Can Use Javascript Object In This Case

While Declaring Your Function:

function myFunc (options = {}) {
  if(typeof options === 'object') {
    let a = options.type;
    console.log(a)
    return true
  }
  throw new Error("Oops.. MyFunc Accepts only Objects!")
}

And While Calling It:

myFunc({
  type: 'number',
  etc: '1', // you can add as many values as you want and access it in the function.
})

You Can Learn More About It Here

CodePudding user response:

You can use

Object.assign({}, { ...options... }, functions)

or, as tagged

$.extend({}, { ...options... }, functions)

Example:

function initDropdown(type, placement, trigger, strategy, functions) {
  tippy('[data-cg-toggle="'   type   '"]',
    Object.assign({}, {
        zIndex: 99999,
        interactive: true,
        placement: placement,
        allowHTML: true,
        trigger: trigger,
        popperOptions: {
          strategy: strategy,
        }
      },
      functions
    });
}
  • Related