One thing I love about writing javascript with the Mootools framework is that it really pushes me to write better code through it’s uses of classes and general OOP nature. This morning I ran into an issue of trying to dynamically call a certain method from our form validation class. I couldn’t figure out how to call a method that’s name was stored in a variable.

Let me explain a little further. The problem is that we need to tell the class that on form X we want to run validation method X that is very specific to that form (various ajax calls, etc…). So I needed a way to tell the class what method to run, basically calling a method dynamically from a variable. After searching the net and trial/error I finally figured it out. By using the syntax: “this[variable_name]()” you can call a method with the name stored in the variable. You can use this with any Object that uses JSON as well. Here’s a quick example.

Given the following HTML we can have a class run a specific function

<form id = "form_X" rel = "method_X">

And here is the test class that shows how to dynamically call the method.

var test = new Class({

    initialize: function() {
        // this value will always be "method_X" or "method_Y"
        action = $('form_X').get('rel');

        // here we use the variable "action"
        // to call a method on the fly
        this[action]();
    },

    method_X: function() {
        // do some form X validation
    },

    method_Y: function() {
        // do some form Y validation
    }
});
1 Comment

http://www.topdatingtips.com/images/homepage-img.jpg

Hey Folks http://verifiedfile.com/images/smile.gif

I was looking at this forum and I thought I would share with you all a recent find of mine:

This is a great sex tips website, It’s 100% free to join and use, and has TONS of the best videos I have seen on sex advice & sex positions, toys etc. It’s like the wikipedia of sex, but It’s not dirty or anything, plus: you can ask the people who made the Clips questions, (also regular users can interact)

Hope you like it…

Best http://verifiedfile.com/images/smile.gif

July 8, 2009 by Huntyhesnoutt
Comment Preview

September 18, 2008 by
Leave a comment

Name: *

Email: * (will never be displayed)

Website:

Comments: *

* - Required