4

Here's a simple example: http://codepen.io/spacejaguar/pen/KrvqNW

html:

<form data-parsley-validate>
  <label for="name">Name:</label>
  <input type="text" name="name" required>
  <br>
  <input type="submit" value="validate">

  <p><small>This is a simplistic example, good to start from when giving examples of use of Parsley</small></p>
</form>

and JS

$(function () {
    $('form').parsley()
    .on('form:init', function() {
        console.log('Form init', arguments);
    })
    .on('field:init', function() {
        console.log('Field init', arguments);
    })
    .on('form:validate', function() {
        console.log('Form validate', arguments);
    })
    .on('form:submit', function() {
        return false; // Don't submit form for this demo
    });
});

It seems that form:init or field:init callback functions are not called at all, while any other one works just fine. What do i do wrong? Or maybe it's a bug?

[EDIT]
I looked into source code and did some debugging stuff, it seems that init event is triggered before any listener has been attached. Creating parsley instance looks alike:

  • $.fn.parsley is called
    -- new ParsleyFactory is created, calls init fn
    --- ParsleyFactory.prototype.init validates config etc. and calls bind fn
    ---- ParsleyFactory.prototype.bind decides which constructor to create (ParsleyForm, ParsleyField or ParsleyMultiple)
    ----- new ParsleyForm is called and returns instance
    ---- ParsleyFactory.prototype.bind triggers init event and returns instance
    --- ParsleyFactory.prototype.init returns instance
    -- ParsleyFactory constructor returns instance
  • $.fn.parsley returns instance
  • .on('field:init', function() { ... }) is being bound
RamboBambo
  • 88
  • 5
  • Interesting. So `$.Parsley.on('form:init')` will work, but that's the only way to catch the event. It would indeed probably be best to trigger the event just after the initialization (say using `setTimeout`). Feel like writing a PR? – Marc-André Lafortune Jul 07 '16 at 14:30
  • I'm afraid I'm unable to do so in the near future, but I'll give it a try later. – RamboBambo Jul 08 '16 at 09:36

1 Answers1

2

I had the same problem and thanks to your research on the event triggering I found a solution. Just bind the event handler to the window.Parsley object and it will work just fine.

For example:

window.Parsley.on('form:init', () => console.log('form:init'))
Jonathan
  • 1,685
  • 2
  • 18
  • 25
  • Yes, it solves the issue somehow, but keep in mind that this way you bind `form:init` globally and it will be called for each parsley instance. – RamboBambo Aug 23 '16 at 13:45
  • That is true. In this case I only had one form. To be honest the event binding/event emitting in parsley is not really clear to me. – Jonathan Aug 23 '16 at 14:13