views:

247

answers:

3

Hi,

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).

+2  A: 

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');
SLaks
A: 

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) { [...] };
npup
+1  A: 

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;
        }));
    }
}
outis
Thank you, that worked. I was doing it completely wrowng way.
Mikk
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.
outis