-2

I got this javascript code to solve in a manner to use inner function but not able to use it. Please try to help me to use inner functions or do i need to modify this. I want to use inner functions on click on html element such as view and remove respectively;

var App = function(){ 
    var url = 'api';

    function view(event) {
        var id = '??'; //here i have to receive id of the element(data-id)
        $.ajax({
            url: url + '/view/' +id,
            data: data
        }).done( function (data){

        });
    }

    function remove(event) {
        var id = '??'; //please determine the id
        $.ajax({
            url: url + '/remove/' + id ,
            data: data
        }).done( function (data){

        });
    }

    function initialize() {
        //
    }

    return {
        //
    }

}();
M K Garwa
  • 495
  • 2
  • 13

2 Answers2

1

Try doing this:

  1. For id you can do one thing, Save the id in data-id attribute of the element on which you want onClick listener and access it using Event-Delegation in javascript.

  2. To use the inner method you don't need to return anything. Just do it this way :

        var App = function(){ 
          var url = 'api';
    
          function view(event) {
           //access the id attribute of event.target
          }
    
          function remove(event) {
           //same
          } 
    
          function initialize() {
           //
          }
    
          App.view = view;
          App.remove = remove;
    
        };
        //EDIT : instead of making it self-invoking, call the app function                
        App();
        //to access it outside:
        App.view("your_parameter");
        App.remove("your_parameter");
    

EDIT : Instead of making it self-invoking, call the app function

Neha AB
  • 60
  • 1
  • 9
0

Well it's pretty simple, use the $("#caller").click() function of our beloved

jQuery

Then inside the .click() function you can easily retrieve your id

Here you can find more on the .click() function

It will be something like this

$( "#view" ).click(function() {
     id = document.getElementById("id").id;
     //Here paste the code of your view function
});
TheRev
  • 124
  • 13
  • Thanks but that i know, My question here is how to use App? or how to initialise it – M K Garwa Jan 10 '18 at 08:53
  • Why do you need App? you can just use the $(document).ready() – TheRev Jan 10 '18 at 08:57
  • so again. the above mentioned javascript is there along with some html. in HTML I have two rows in a table with two actions each named view and remove. now how to use this above mentioned javascript code in a way that when i click on remove. it will call ajax function and do something. how to call these two view and remove function on click of view and remove button respectively. – M K Garwa Jan 10 '18 at 09:09