I have a field type that I need to initialize. When the page loads I can use code like the following to handle certain behaviors of the field:
$('.myfieldwrapper').each(function() {
new Craft.MyField(this);
});
Within the Craft.MyField object, I add a couple listeners like so:
this.addListener(this.$element, 'change', 'handleElementChange');
this.addListener(this.$element2, 'click', 'handleElement2Click');
That all works fine. However, this field doesn't just get added to the page on page load. It exists in the row of a table, and a user can add additional rows to the table which add a new row and field to the DOM.
I've tried to instantiate the newly added field in several ways, and I have been unable to get it right yet. The Craft.MyField seems to be initializing, and I appear to be able to re-initialize the default fields on the page, but my attempts do not have any affect on the dynamic fields that get added.
I don't think the following is the best way to do this, but it's currently the closest I've come and is the simplest example code I can share reflecting my attempts.
After a new field gets added dynamically, I trigger an event:
$('#tableId').trigger('rowAddOrRemove');
And I have additional code watching for that event and attempting to re-initialize all the fields on the page:
$('#tableId').on('rowAddOrRemove', function(event){
$('.myfieldwrapper').each(function() {
new Craft.MyField(this);
});
});
When I do this the initial field on the page still works but none of the dynamically added fields behave as I need them too.
Any ideas on what I'm doing wrong or what concepts I need to understand better to get this right?