1

I need to pass a special selector to an event handler. The special selector is calculated by a function:

var getSelectableItems = function () {
    return $('.item').not('.disabled');
}

$(document).ready(function () {
    $body = $('body');
    $body.on('click', $(getSelectableItems()), function () {
        // .. do something
    });
});

The getSelectableItems() method is just a sample. My real code looks different. My point is: how can I have a function return a selector and use this selector in the kind of click event handler shown?

My current solution fires on every click / any DOM element. But I want the click event to fire only on clicks on DOM elements returned by a function.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Ingmar
  • 1,525
  • 6
  • 34
  • 51
  • 1
    This seems like an XY question. Can you give details of what you're actually trying to achieve, as I'm sure there are much better ways than what you are attempting to do. – Rory McCrossan Feb 26 '16 at 11:20
  • 2
    You need to return a selector, not a jQuery object... so `return '.item:not(.disabled)';` – Arun P Johny Feb 26 '16 at 11:23
  • If I understand you correctly you could select desired items via in eq. $('item').not('disabled') and then use this [function](http://stackoverflow.com/questions/2420970/how-can-i-get-selector-from-jquery-object) to create selector for that elements. – Konrad 'Zegis' Feb 26 '16 at 11:24
  • Ohhhhh. The 2nd parameter needs to be a string. Arun's solution is what I was looking for. So simple ;) Thanks everbody!! – Ingmar Feb 26 '16 at 11:30

2 Answers2

1

See if this works,

$(document).ready(function () {
    var dumbVar = $('body');
    dumbVar.on('click', $(getSelectableItems()), function () {
        // .. do something
    });
});
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
viniciusalvess
  • 756
  • 8
  • 18
0

You can create click handler on needed selector(elements that have class .item and don't have class .disabled):

$(document).ready(function () {
    $body = $('body');
    $body.on('click', '.item:not(.disabled)', function () {
        // .. do something
    });
});
Anna Adamchuk
  • 718
  • 4
  • 16
  • Yes, Anna, this works in the sample. But I really need a function because my real scenario is a little more complex. Anyways: I already have a working solution based on Arun's answer (see above). Thanks so much for your effort though! – Ingmar Feb 26 '16 at 11:54