Home > Net >  Trigger jQuery when a vanilla js function has been fired
Trigger jQuery when a vanilla js function has been fired

Time:03-21

I got a jQuery function that catches changes on a input field and add it to a variable.

The input field is also held up on a vanilla js based API lib, that I cant convert to jQuery. The lib is an address API, so people can select a address, and that wont trigger my jQuery function. I therefore thought of a workaround, where my jQuery is watching my vanilla js, to see when it's fired, and fire my jQuery function right after.

My jQuery function:

$('#billing_address_1').on('input',function(e){
    let addressValue = $('#billing_address_1').val();
});

My vanilla js function:

"use strict"

dawaAutocomplete.dawaAutocomplete( document.getElementById("billing_address_1"), {
    select: function(selected) {
        document.getElementById("valgtadresse").innerHTML = selected.tekst;
    }
});

All solutions I've been able to search for, has been requiring that I use .trigger() on my vanilla js in this case. They've not been made for the mix of these two js alternatives. Can I do it in a more proper way?

CodePudding user response:

If you don't want to touch your fields with trigger you can try event emitter pattern which is quite popular in node. Here you keep an object as notifier on which you call event and also hook listeners for that event. It is basically a Pub-Sub pattern a simple implementation of which in vanilla javascript is available over here by mudge or you might also try any alternatives if you find

// KEEP THIS SOMEWHERE IN OUTER SCOPE 
let bird = new EventEmitter()


//THEN - hook on any event you name it
bird.on('tweet', (val)=>{
  console.log(val)  
  addressValue = val
})

//THEN - emit that named event wherever you might need
dawaAutocomplete.dawaAutocomplete( document.getElementById("billing_address_1"), {
    select: function(selected) {
        document.getElementById("valgtadresse").innerHTML = selected.tekst;
        bird.emit('tweet', selected.tekst);
    }
});


  • Related