WordPress.org

Make WordPress Core

Opened 5 years ago

Closed 5 years ago

#33359 closed defect (bug) (worksforme)

Custom fields in media modal javascript events are unbound after ajax save method

Reported by: LindsayBSC Owned by:
Milestone: Priority: normal
Severity: normal Version: 4.2.4
Component: Media Keywords:
Focuses: javascript, administration Cc:

Description

Problem:
Any javascript bound to a field created by the custom attachment fields API (attachment_fields_to_edit) gets unbound (or removed) after the save function is finished.

Replicate:
You can replicate it by adding the following code into your theme's functions.php or into a plugin file (update path to JS accordingly)
Form Fields & Save PHP functions
https://gist.github.com/Lindsayanng/81d2360c227ebc325325

Test javascript
https://gist.github.com/Lindsayanng/b6f52af6bbe35f7bd347

The above code will create custom fields at appear in the media modal "details" sidebar. To test this, click the "Trigger JS Event" button. You will see all input fields turn red.

Enter content into any of the default image attachment fields like 'title' and 'caption' and as you switch between fields the save function is run and the red background remains.

Update any content into a custom created field and when you switch between fields the save function will trigger and you will see the js event that created the red background on those fields is gone!

I have found that the JS events are unbound using both edit-attachment and wp_ajax-save-attachment-compat' actions.

Solutions:
I believe this has to do with how the javascript view is re-rendered after the save function.

See screencast: http://cl.ly/0a401F0r0z2S

Change History (4)

This ticket was mentioned in Slack in #core by lindsaymac. View the logs.


5 years ago

This ticket was mentioned in Slack in #core by lindsaymac. View the logs.


5 years ago

This ticket was mentioned in Slack in #core by lindsaymac. View the logs.


5 years ago

#4 @ericlewis
5 years ago

  • Milestone Awaiting Review deleted
  • Resolution set to worksforme
  • Status changed from new to closed

Any javascript bound to a field created by the custom attachment fields API (attachment_fields_to_edit) gets unbound (or removed) after the save function is finished.

This depends on the method of event binding. After testing your code, I found the events are actually bound in a way that persists after the save function is finished. The issue is that the DOM state changes (i.e. color changes) don't persist, which is because the attachment compat view is re-rendered, initializing new DOM nodes that have default colors.

So the issue you're experiencing is that the entire attachment compat view is rerendered whenever any compat field is saved. If that's an issue, I would suggest a good reading of #22186 which documents moving attachment_fields_to_edit filter into the media modal.

Note: See TracTickets for help on using tickets.