Click other than f.link_to_add in nested_form to add a prefilled element

In normal usage, add an element with the a tag displayed by the form method link_to_add. The pattern I implemented this time is to add an element of nested_form to the coordinates where the canvas is clicked, and prefill the coordinates to that element.

As I investigated, the link_to_add method runs on events that depend on the DOM structure, including blueprint, so I couldn't implement it neatly using the javascript method that link_to_add uses internally.

Therefore, the basic implementation policy is to write the coordinates to the global store with the click event handler of canvas, and read the coordinates from the global store with the nested: fieldAdded event, which is an external relay implementation.

function handleClick(e) {
[...]
  var linkToAdd = $('[data-blueprint-id="connectors_fields_blueprint"]')
  linkToAdd.data('tmp-x', Math.floor(mouseX));
  linkToAdd.data('tmp-y', Math.floor(mouseY));
  linkToAdd.click();
}     
  $(document).on('nested:fieldAdded:connectors', function(event){
    var linkToAdd = $('[data-blueprint-id="connectors_fields_blueprint"]')
    event.field.find('input[data-x]').val(linkToAdd.data('tmp-x')) && linkToAdd.data('tmp-x', null);
    event.field.find('input[data-y]').val(linkToAdd.data('tmp-y')) && linkToAdd.data('tmp-y', null);
[...]

Please let me know if you know a better way.

end

Recommended Posts

Click other than f.link_to_add in nested_form to add a prefilled element
How to add a classpath in Spring Boot
I want to click a GoogleMap pin in RSpec
How to add columns to a table
Add a search function in Rails.