views:

105

answers:

1

I have a PHP class with a static function:

<? echo view::getUserSelector() ?>

Which outputs:

<div id="user_selector">
    <div class="user">
        <h1>Username1</h1>
        <a href="javascript:selectUser(this);">select</a>
    </div>
    <div class="user">
        <h1>Username2</h1>
        <a href="javascript:selectUser(this);">select</a>
    </div>
</div>

What do I need to do to make this possible?:

<? echo view::getUserSelector(array('onSelect' => 'function() { alert(this.id); }')); ?>
  1. How do I 'add' the onSelect-value as a function of div#user_selector?
  2. How do I 'call' div#user_selector.onSelect() with this reference as div#user_select?

Javascript:

function selectUser(anchor) {
    //remove all 'selected' classes from $user_selector child divs
    //add 'selected' class to parent div.user of anchor
}
+1  A: 

In the PHP function, where you output all this, you could add this inside script tags, which gives you what you want (from what I can understand).

<script type="text/javascript>
var uSelect = document.getElementById('user_select');
uSelect.onSelect = function() {
    alert(this.id);
}

function selectUser(anchor) {
    //remove all 'selected' classes from $user_selector child divs
    //add 'selected' class to parent div.user of anchor
    uSelect.onSelect();
}
</script>

But, one more resource I want to point out, is if you want to simply declare the function and are curious how to assign any given object to be 'this' inside it, Javascript functions have to methods call and apply.

For example: you could try something like this as well.

<script type="text/javascript>
var onSelect = function() {
    alert(this.id);
}

function selectUser(anchor) {
    //remove all 'selected' classes from $user_selector child divs
    //add 'selected' class to parent div.user of anchor
    var node = anchor;
    while(node && node.parentNode) {
        if(node.getAttribute('id') == 'user_select') {
         //apply(thisRef, argsArray)
         //call(thisRef, arg1, arg2 [...])

         onSelect.apply(node);
         break;
        }
        node = node.parentNode;
    }
}
</script>
seanmonstar
Alright, this sorta works! Thanks!
Ropstah