Paolo Rossi
Paolo Rossi

Reputation: 2510

Jquery - get from html attribute a callback name in event delegation

I have a table with many records. To improve perfomence I use the jquery event delegation.

<div id="table">
  <div class="dosomething" uid="1">first</div>
  <div class="dosomething" uid="2">second</div>
  ..etc
</div>  

$('#table').on('click', '.dosomething', function() {
  var htmlMsg = 'foo bar';
  var uid = $(this).attr('uid');
  // Now call confirm Dialog
  callDialog(htmlMsg, uid, changeCrt);
});

function callDialog(htmlMsg, uid, callback) {
  $('#confirm').dialog({
   resizable: false,
   autoOpen: false,
   modal: true,
   buttons:
   {
      Yes: function ()
      {
          $(this).dialog("close");
          callback(uid);
      },
      No: function ()
      {
          $(this).dialog("close");
      }
   }
}).html(htmlMsg).dialog('open');
}

function changeCrt(uid) {
   do something
}

To be able to use for most scenarios I would like to pass the callback name dynamically passed via html attribute. I tried in this way

<div id="table">
      <div class="dosomething" uid="1" act="changeCrt">first</div>
      <div class="dosomething" uid="2" act="changeCrt">second</div>
      ..etc
</div>

$('#table').on('click', '.dosomething', function() {
    var htmlMsg = 'foo bar';
    var uid = $(this).attr('uid');
    var act = $(this).attr('act');
    // Now call confirm Dialog
    callDialog(htmlMsg, uid, act);
});

but I get this error from the console

TypeError: callback is not a function.

how can I fix it? thanks

Upvotes: 0

Views: 122

Answers (2)

Paolo Rossi
Paolo Rossi

Reputation: 2510

Could this be a good solution?

  var act = $(this).attr('act');

  switch (act)
  {
     case "changeCrt":
        callDialog(htmlMsg, uid, changeCrt);
     break;

  }

Thank you for your suggestion.

Upvotes: 0

George
George

Reputation: 36784

You would need to call the function using square bracket notation, using the scope in which you defined the function, which in this case, is window:

Yes: function ()
{
    $(this).dialog("close");
    window[callback](uid);
},

Or, if you don't want to pollute window's namespace, create a library object to keep your callback:

var library = {
    changeCrt: function(uid) {
        // do something
    }
}

And use your library as the scope:

Yes: function ()
{
    $(this).dialog("close");
    library[callback](uid);
},

Upvotes: 1

Related Questions