0

I just came to know about the jQuery .on() method and decided to use it as it was much cleaner than using multiple binds. It is working as long as I am using pre-defined events but when I am trying to add custom events it is not working.

I have this auxiliary function

var EV_ENTER_KEY = "enterKey";
function bind_events(cur_obj, e) {
    if (e.keyCode == 13) {
        $(cur_obj).trigger(EV_ENTER_KEY);
    }
}

which I am using in the following code

CATEGORY_INPUT.on({
    keyup: function (e) {
        bind_events(this, e);
    }
});

//Action for Category Search box Enter press
CATEGORY_INPUT.bind(EV_ENTER_KEY, function () {
    alert("Aseem");
});

I am changing it to the following

CATEGORY_INPUT.on({
    keyup: function (e) {
        bind_events(this, e);
    },
    EV_ENTER_KEY: function () {
        alert("Aseem");
    }
});

But it is not working. No errors are being logged in console either for this. I looked and found this and I think I am using it correctly. The API reference did not have any examples of binding multiple events. Can someone tell whether I missed something in the API? If not what is the problem here?

Community
  • 1
  • 1
Aseem Bansal
  • 6,722
  • 13
  • 46
  • 84

2 Answers2

1

It seems you have to give the custom event as string directly instead of storing it in a js variable and then using it. If you change EV_ENTER_KEY to "enterKey" in your multiple event binding then it will work.

$(".myInput").on({
    keyup: function (e) {
        bind_events(this, e);
    },

    "enterKey": function () {
        alert("Enter key pressed");
    }
});

JS fiddle demo : http://jsfiddle.net/9ur4c/

Sanjeev
  • 2,607
  • 22
  • 16
0

It can be made to work like this. This is according to this answer

var EV_ENTER = "enter"

categoryInputEvents = {}
categoryInputEvents[EV_ENTER] = function(e) {
    alert("Enter Event");
}

CATEGORY_INPUT.on(categoryInputEvents)

Although this still does not explain the thing reported by @Sanjeev but it is better to have alternatives.

Community
  • 1
  • 1
Aseem Bansal
  • 6,722
  • 13
  • 46
  • 84