Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch Jquery event from vue.js

Scenario: I have an iframe (which is hosted in the same domain, but purely use Jquery only) and it is already coded to trigger some events with parameters. And I have to catch those events with parameters in the parent vue.js application.

iframe:

$('*').mouseover(function (event) {
  var event = jQuery.Event( "mouseover-highlight" );
  event.top = $(this).offset().top;
  event.left = $(this).offset().left;
  parent.$('body').trigger(event);
});

vue.js

Catch this event somehow from the vue.js and set a div's css styles accordingly (Set the 'absolute' position). I have done it using vue.js before v2 comes by using Jquery inside the vue.js, But I've seen in the docs that vue.js isn't able to catch native events anymore. Any solution ?

like image 391
stackminu Avatar asked Sep 12 '17 12:09

stackminu


2 Answers

https://jsfiddle.net/wx84na32/2/ Please check the fiddle this is complete example what you want. HTML

<button id="testBtn">Trigger an event</button>
<div id="app">
<div v-show="this.show">
1st Argument of Custom Event <br />
"{{ one }}"
<br />
2nd Argument of Custom Event <br />
"{{ two }}"
<br />
A complete event object below <br />
{{ event }}
</div>
</div>

Javascript / jQuery / Vue

//jQuery

$('#testBtn').on("click", function(event) {
    console.log(this, 'this');
  $(this).trigger("custom", ["1st", "2nd"]);
});

//vue.js


new Vue({
  el: '#app',
    mounted () {

    let _this = this;

    $(document).on("custom", function(event, one, two) {

        console.log(event, 'event');
      console.log(one, 'one');
      console.log(two, 'two');

      _this.event = event;
      _this.one = one;
      _this.two = two;

      _this.show = true;

    });
  },
  data () {
    return {
        show : false,
        event : {},
      one : '',
      two : ''
    }
  }
});

[https://jsfiddle.net/wx84na32/2/]

like image 197
Muhammad Adil Avatar answered Oct 18 '22 19:10

Muhammad Adil


jQuery uses it's own event system. You cannot catch events emitted from jQuery with Vue, you have to catch them with jQuery and call Vue from the handler.

new Vue({
  el: "#app",
  data:{
    iframeSource: $("template").html()
  },
  methods:{
    onMouseover(event){
      alert(`Top: ${event.top}, Left: ${event.left}`)
    }
  },
  mounted(){
    $("body").on("mouseover-highlight", this.onMouseover)    
  },
  beforeDestroy(){
    $("body").off("mouseover-hightlight", this.onMouseover)
  }
})

Here is an example of it working.

Note: when adding events with something other than Vue, you should manage removing them yourself, especially if you are adding it in a component. Components are created/destroyed more than once and you don't want to end up with multiple handlers.

like image 25
Bert Avatar answered Oct 18 '22 19:10

Bert