2

To begin with, I'm not even sure, if it is the right way to do it.

Let's say, i have script (jquery included) like this:

foo = function() {

    this.bar = function() {
    alert('I\'m bar');
    }

    this.test = function() {
    $('body').append('<a onclick="my_var.bar();">Click me</a>');
    }

this.test();

}

var my_var = new foo();

Is there any way, i could make variable "my_var" dynamic inside function "foo". So I could do something like

$('body').append('<a onclick="'+the_variable_which_im_assigned_to+'.bar();">Click me</a>');

Thank you

//Edit:

I'm sorry if i wasn't clear enough, because I'm not quite sure of what I'm trying to do myself.

My goal is to replace line

$('body').append('<a onclick="my_var.bar();">Click me</a>');

with

$('body').append('<a onclick="'+what_ever_should_go_here+'.bar();">Click me</a>');

So when i call

var my_var = new foo();
var your_var = new foo();
var our_var = new foo();

I would be able to call functions inside each object (after they append something into document body).

1
  • I don't think it is clear what you are trying to do? Commented Mar 26, 2010 at 12:21

3 Answers 3

2

You should use anonymous handler functions instead of inline events, like this:

$('<a href="#">Click Me</a>')
    .click(function() { my_var.bar(); return false; })
    .appendTo('body');
Sign up to request clarification or add additional context in comments.

Comments

1

In addition to switching from the inline event handler, you'll need to use a closure to access the Foo instance within the handler.

function Foo() {
    var self = this;
    this.test = function() {
        $('body').append(
            $('<button>something</button>').click(function () {
                self.bar(); return false;
        }));
    }
}

2 Comments

Thank you, that worked. I was doing it completely wrowng way.
SLaks' code phrasing (chaining all the calls) is cleaner than mine. Keep the use of self and the click handler, but use his click(...).appendTo(...). Note also that a button might make more sense than a link while still calling out to the user to click it (without having to say "click me"), depending on the element's exact purpose.
0

If that's the general plan you want/need to use to attach event handler, yeah, send in the name of the variable to the function that foo refers to:

foo = function(name_of_the_variable_which_im_assigned_to) { [...] };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.