I’m using javascript and jQuery. I have a “problem” that my web app has different views, and one action (like mouse click) should do different things in the different views.
I’ve created an ActionManager that get’s notified when an click event is fired. This manager object knows about the current view. Now I wan’t the actionmanager to be able to trigger a function in different objects.
What I’ve done is that the manager gets an instance of the different objects. This is done via a registration when they are initialized, where they register what kind of event they wan’t to handle and what kind of view they are responsible for.
the problem is that I want to make this as generic as possible, so that the actionmanager doesn’t need to know about what the name of the function that is gonna be called is. Then the different instances can have different function names without letting the actionmanager to know about it. I could let the registration part store the function name for that event in that instance by sending a reference to the function, but then I can’t do this:
myfunc : function (myinstance, myfunction)
{
myinstance.myfunction();
}
that will assume that myfunction() exists as a function in myinstance, and not use the real function name which could be “onMouseClick”.
Edit:
Explanation for others seeing this tread and wondering why: The reason for my eventmanager is that I want to only add one click event on the elements that need it, and not changing the click event code. I also want to only call one method and run the code in that method. I don’t want to call several methods and let the methods decide based on the view if they should run or not.
If
myfunctionis a string:You can do this:
A function on an object is simply a function object assigned to a property on that object. In JavaScript, you can access properties in one of two ways:
x = obj.foo;, orx = obj["foo"];They do exactly the same thing, but of course the second form is much more flexible — designed, in fact, for exactly the situation you’re describing.
If
myfunctionis an actual function object:You can do this:
That calls
myfunctionand ensures thatthis = myinstanceduring the call. All JavaScript function objects have acallfunction and anapplyfunction. They both do the same thing (call the function with a specificthisvalue), but they differ in how you pass arguments to the function:With
call, you pass them as discrete arguments in thecallcall:With
apply, you pass in an array of arguments:E.g.:
Example of all of the above
Live copy – Since you said you were using jQuery, I went ahead and used it for convenience, but none of the above is related to jQuery, it’s how vanilla JavaScript works.
(
displayjust appends a paragraph element to the page with the given text;sepjust appends anhrelement.)More reading:
this