1

I don't know if the question is clear enough. I think an example is easier to understand. I want to do the following:

Instead of directly calling the object method, like this:

$("#input").changed(function(){  
    //do something  
})

or this:

$("#input").keyup(function(){  
    //do something  
})

I want to have a single function that can dinamically change the object's method that is being called, like this:

function foobar(callback){
    $("#input").callback(function(){  
        //do something  
    })
}

foobar("keyup")
foobar("changed")
Community
  • 1
  • 1
drakenation
  • 195
  • 2
  • 13
  • 5
    Look for "bracket notation", https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors, or you could use `on` which takes the event as a string. – elclanrs May 22 '14 at 05:33
  • @elclanrs I was putting jQuerys `on` into an answer but you beat me. Besides I think drakenation is confused about calling the action and changing the action. – DutGRIFF May 22 '14 at 05:35
  • I don't see how this is a duplicate of that but I bet it is a duplicate of something. :) – DutGRIFF May 22 '14 at 05:37
  • 2
    if you are looking to bind multiple events to the input control and have the same function called for each event then use $("#input").on("keyup changed", function() {...}); – user2321864 May 22 '14 at 05:38
  • @user2321864 I actually want to write a small form validator with which I could easily change when each field is validated (onSubmit, onLoseFocus, onChange, etc). – drakenation May 22 '14 at 05:45

1 Answers1

2

Yes. The methods are keys in a Javascript Object. You can use the methods by name with a dot or within a string in square brackets:

$(selector).keyup()

or

$(selector)['keyup']()

So you could create a function like this:

function foobar(callback){
    $("#input")[callback](function(){  
        //do something  
    })
}

Although, it seems silly.

bozdoz
  • 12,550
  • 7
  • 67
  • 96
  • 1
    I'm a bit new to Javascript, and the language itself seems a bit silly for me. Having learned first C, then Python, then PHP, and now Javascript, JS "do what you want"-ish philosophy is a bit hard to wrap my head around. Also, so many anonymous functions! Anyway, thanks, case solved. – drakenation May 22 '14 at 05:42
  • Thanks. You should accept the answer as the solution if it fits. Also, I agree, Javascript can be a little too flexible. – bozdoz May 22 '14 at 05:45