Skip to content
Advertisement

Bind function to the onClick on other scope

I’m trying to bind a function to the anchor onclick attribute. I’m not using the traditional jQuery’s bind/live/on/whatever because I have some other scripts stopping the events propagation (it sucks, I know).

To bind the function to the onclick attribute I’m passing a JSON object to a module like this:

function foo() {
  alert('foo')
}

$('document').ready(function() {
    var options = {
        opt1: 'fooID',
        opt2: 'barID',
        json: mightyJSON,
        actions: [
            { url: 'contact/_id_/edit', text: "Edit", iconPath: 'edit.png' },
            { url: '#', onClick: foo, text: "Delete", iconPath: 'delete.png' }
        ]
    };

    var trolol = myModule.configure(options);
});

As you can see the function named “foo” is passed via the onClick property of the JSON. The function is defined above the object.

In myModule I’m creating the anchor tag like this:

var buildLinks = function(objectID)
{
  var linksNbr = actions.length;
  var link, cssClass;

  for (var i = 0; i < linksNbr; i++)
  {
    // Adding the object ID to the URL
    link     = actions[i].url.replace('_id_', objectID);
    cssClass = actions[i].cssClass || '';

    var $link = $(document.createElement('a')).attr('onClick', actions[i].onClick)
                                              .attr('href', link)
                                              .attr('title', actions[i].text)
                                              .addClass(cssClass)
                                              .text('foo');
  }

  return $link.html();
};

The thing is, as you can expect ‘foo’ is executed when the script is parsed and only there. The onclick doesn’t even work after.

I can pass it like this onClick: 'foo()'. The onclick works but it’s also executed at parsing and it’s, in my opinion, very ugly.

I’d like to still be able to pass it like this onClick: foo but working correctly (i.e. not being executed at loading but only when clicking.

It has to work with jQuery 1.4.4 unfortunately.

Advertisement

Answer

I would do it like this:

var $link = $('<a></a>',{
    href : link,
    title : actions[i].text,
    'class' : cssClass,
    text : 'foo',
    click : actions[i].onclick
})
return $link;

Then use one of these (1,2) functions to insert the node, which is the html with events.


for the propagation issue i would do something like this:

html <a href="#no" ....>text</a>

js $('a[href="#no"]').live('click',function(){ return false; });

This way whenever the href is pointing to #no the event is eventually propagated

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement