When/where is perfect to register event listener?

When/where is perfect to register event listener?

pisislerpisisler Posts: 106Questions: 21Answers: 1

Hi.

I would like to discuss performance impact of the placing of event listener. In my use case, I calculate some fields based on the value of other fields on the fly and live. For example calculating profit margin of a product based on the "sale price" field. For this to work, you need to listen changes on the price field input with $(editor.field('price').input()).on('input', function (e, d) { } );. In my case, I have 5-6 different fields which I need to listen at the same time. So I register the event listener for all of them in the same way.

Here is the question; do you think it has effect to listen this event as soon as data is loaded or to register the listener only when the corresponding field is triggered in the editor like:

editor.on('open', 'tbody tr td', function(e, type) {
  if (editor.displayed()[0] == 'price')
    $(editor.field('price').input()).on('input', function (e, d) {
      //Do the calculation here
    });
});

Replies

  • pisislerpisisler Posts: 106Questions: 21Answers: 1
    edited April 2021

    The way that event listener works, since it will be listening the changes on all along the column as soon as it is registered, it doesn't seem that it would have any performance difference to register at the beginning or after editor is triggered for that column.

    Would it make difference to attach the event listener only to the specific single field (of one single row) which is being edited now?

  • allanallan Posts: 61,450Questions: 1Answers: 10,055 Site admin

    Hi,

    My thoughts on this are that you would be best to add the event listener just once, immediately after the Editor instance has been created - e.g.:

    var editor = new $.fn.dataTable.Editor( {
      ...
    } );
    
    $(editor.field('price').input()).on('input', function (e, d) {
       //Do the calculation here
    });
    

    I don't think that the open event is the correct one to use here as you would need to remove it on close, thus causing an add and remove every time editing is activated / deactivated. Now in terms of time, you wouldn't actually see any impact, but it seems like adding clock cycles for no benefit.

    Adding an event listener is going to be super fast - you can add a hundred and not notice any performance issues like this.

    Does that help?

    Allan

  • pisislerpisisler Posts: 106Questions: 21Answers: 1

    In fact yes, I meant to register the event only when editing is activated. I didn't do any benchmarks, I just wanted to learn what you think about its performance impact. But if as you said adding even a hundred event listeners wouldn't effect performance that much, then it is no problem.

    Thanks.

This discussion has been closed.