Configure the Javascript function + Html Helper

171 Views Asked by At

Is there a way to configure a Javascript(which accepts few parameters) and initialize a function with user specified parameters in an unobtrusive way with data-attributes?

Any reference would be great help

 InitializeLogging({
  Url: "/xxx/yyyy",
  x: 10,
  y: true,
  somevalue: false,
  unHandledErrorCallback: function (message) {
   console.log("Somerror message " + message);
  }
  });
1

There are 1 best solutions below

1
On

We can achieve that in the following way,

HTML

<a href="javascript:void(0);" data-attributes="a">Call a</a> <br />
<a href="javascript:void(0);" data-attributes="b">Call b</a>

Script

var app = {
    init: function(){
        this.addEventListener();
    },

    a: function(){ alert("You have called 'a'"); },

    b: function(){ alert("You have called 'b'"); },

    callMethod: function(event){
        var func = $(this).attr('data-attributes');
        app[func].call();
    },

    addEventListener: function(){
        $('a').on('click', this.callMethod);
    }
};

$(document).ready(function(){
    app.init();
});

Demo JS http://jsfiddle.net/DfHXs/2/

Hope this will help you.