简体   繁体   中英

Form init and field init events do not work in parsley.js

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

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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM