4

I'm trying to send data to the server via Backbone if the users writes or paste a string inside an input text element.

in the Backbone events I thought something like this but it doesn't work:

events:{
    "click .close":"closeResults",
    "keypress input":"fetchData",
    "paste input":"fetchData"
},
fetchData:function (e) {
    var $this = this;
    window.setTimeout(function () {
        if ($.trim(e.target.value).length >= 3) {
            console.log(e.target.value);
            $this.collection.fetch({data: {limit: 10, term:$.trim(e.target.value)}});
        }
    }, 0);
}
vitto
  • 19,094
  • 31
  • 91
  • 130
  • Is `input` located inside the `$el`? Because this is working example – Vitalii Petrychuk May 12 '13 at 20:27
  • btw `$this` is not an appropriate variable name as it implies that it is a jQuery object. `self` is a better alternative. Anyway your code should work I can't see nothing wrong with it – David Fregoli May 12 '13 at 22:10
  • with this code `keypress` event works, but `paste` doesn't, I tried also a different `$this` name, it's a local variable, this shouldn't make problems inside this location. – vitto May 12 '13 at 22:45

3 Answers3

6

If you switch to using the keyup event instead of keypress and paste, it will work for pasting via the keyboard ( ⌘ + v or Ctrl + v ) and typing normally.

If you use the input event, it will work even if you right click and paste (in addition to the same expected behavior as keyup).

More info on input: https://developer.mozilla.org/en-US/docs/Web/API/window.oninput

burin
  • 491
  • 2
  • 4
1

use keyup and mouseleave (instead of input) event handlers so that it will also work in IE

see also How to detect right mouse click + paste using JavaScript?

events:{
    "keyup input":"fetchData",
    "mouseleave input":"fetchData" 
},
Community
  • 1
  • 1
0

Have a look at

e.originalEvent

_paste_plain_text : function (e) {
    e.preventDefault();
    var text = e.originalEvent.clipboardData.getData("text/plain");
    document.execCommand("insertHTML", false, text);
}
styks
  • 3,193
  • 1
  • 23
  • 36