I am currently working with the "NinjaForms" plugin for WordPress, which provides custom form management for the backend. It's based on Marionette / Backbone JS. After some research, I had no problem triggering JavaScript functions on input change and on form submit. However, I have not found a way to fish for an event once the form is initialised / rendered / shown (any of these, really).
What I am doing right now is initialising a Marionette object, adding listeners to a radio and then adding functions to execute it on event:
if(typeof Marionette !== 'undefined') {
var mySubmitController = Marionette.Object.extend( {
initialize: function() {
// init listener
this.listenTo( Backbone.Radio.channel( 'forms' ), 'view:show', this.initAction);
// field change listener
this.listenTo( Backbone.Radio.channel( 'fields' ), 'change:modelValue', this.valueChanged);
// submit listener
this.listenTo( Backbone.Radio.channel( 'forms' ), 'submit:response', this.actionSubmit );
},
// init action
initAction: function() {
console.log("init");
},
// input update action
valueChanged: function(model) {
console.log("update");
},
// submit action
actionSubmit: function( response ) {
// handled via php
console.log("submit");
},
});
// initialise listening controller for ninja form
new mySubmitController();
}
However, the line this.listenTo( Backbone.Radio.channel( 'forms' ), 'view:show', this.initAction);
is not working. I have tried the events view:render
, view:show
, show:view
, render:view
without success.
I searched in the Backbone / Marionette documentations, but could not find a fitting event. This question might be a duplicate, but I could not really find any topic regarding form initialisation events with Backbone.
after some long search, googling and frustration I've found a solution. Using the following JavaScript-Code, you can execute code on form render:
// if there is a ninja form on this page
if(typeof Marionette !== 'undefined') {
var mySubmitController = Marionette.Object.extend( {
initialize: function() {
// init listener
this.listenTo( nfRadio.channel( 'form' ), 'render:view', this.initAction );
},
// init action
initAction: function() {
// code to execute on form render
},
});
// initialise listening controller for ninja form
new mySubmitController();
}