Make WordPress Core

Opened 2 months ago

Last modified 2 months ago

#43149 new defect (bug)

WP-API JS Client not triggering change event when using setMeta/setMetas helpers

Reported by: caercam Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 4.9
Component: General Keywords:
Focuses: javascript, rest-api Cc:


As briefly mentioned on Slack earlier today the model.setMeta() helper method introduce in #41055 has a couple of weaknesses.

1/ The meta attribute is undefined when creating a new model, which makes sense, but causes setMetas() to silently fail at set new meta values; using setMeta() causes an error.

var post = new wp.api.models.Post( { id : 1234 } );
post.setMetas( { foo : 'bar' } ); // post.attributes.meta remains undefined
post.setMeta( 'foo', 'bar' ); // TypeError: metas is undefined

2/ When the meta attribute is properly defined, some changes in meta values fail to trigger a change event. Provided that the above issue does not show:

var post = new wp.api.models.Post( { id : 1234 } );
post.on( 'change:meta', console.log );
post.set( 'meta', { foo : 'bar' } ); // trigger change event
post.setMetas( { foo : 'BAR' } ); // Does not trigger change event
post.setMeta( 'foo', 'BAR' ); // Does not trigger change event

Values are correctly updated; the change event is just not triggered as it should.

The only way I found to make this work is to clone the meta attribute in setMeta()/setMetas(). As of now these methods simply retrieve the meta attribute using get() and then _.extend() to add/update properties, which doesn't seem enough to make Backbone consider it a change.

Change History (1)

This ticket was mentioned in Slack in #core-js by caercam. View the logs.

2 months ago

Note: See TracTickets for help on using tickets.