Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use X-editable on dynamic fields in a Meteor template?

Tags:

meteor

I'd like to display an entire collection in a table, and make the "name" field in every row in-place editable with X-editable

editable can be attached to every name in the table using a recently added "selector" option:

$('#collectionTable').editable({
  selector: '.editable-click',
});

// I also need to setup a 'save' callback to update the collection...

$('a.editable-click').on('save', function(e, params) {
  console.log('Saved value: ' + params.newValue);
  // TBD: update the collection 
});

But I can't run either of these until the template is done rendering and the DOM nodes are available, so I put this in the "rendered" callback of the Template.

The problem is that every time the collection changes, rendered is called, and then a new editable is attached to each DOM node as well as another callback. This means memory leaks and multiple callbacks whenever a "name" is saved.

Clearly I'm doing this wrong, but I'm not sure where the right place is to call editable and on('save', function()) ?

like image 883
jpeskin Avatar asked Nov 04 '22 04:11

jpeskin


1 Answers

Calling editable after every rendering seems to be reliable (although I imagine could be causing memory leaks). But if you wish to bind to events like 'save', you should be sure to unbind all existing events, otherwise you will keep binding new save events on every rendering:

Template.editableTable.rendered = function() {

    $('#myParentTable').editable({
      selector: '.editable-click'
    });

    $('a.editable-click').unbind('save').on('save', function(e, params) {
      // Make changes to your collection here.
    });

  };

I experimented with only calling editable on the first rendering of the template. That mostly worked as long as you made sure to call it again if the template is ever destroyed (e.g. using routers that create and destroy templates dynamically). But there were some edge cases where it didn't seem to work, so I've reverted back to just calling editable after every rendering.

like image 182
jpeskin Avatar answered Nov 10 '22 15:11

jpeskin