PX - Using Callback Functions
  • Callback Functions

    Callback functions are the key to the real power of the pxtreme project.
    • Arguments

      function($this, $index)
      All methods since px.011.php pass $this and $index to callback functions.
    • Closures

      A more convenient and very jQuery-like means of passing functions is to define a Closure as the parameter to a px method that accepts functions.

Callback Functions

Callback functions are functions you define. When you pass the function to compatible pxObject methods, your function will be called once for each matching element. The value returned from your function will then be used as is appropriate to the method called.

For example, the addClass() method can accept a callback function as it's argument. If you write a PHP function and pass that function's name to addClass(), each currently matched element will be set according to the result returned from your function.

When to Use Callback Functions

Why go to all the trouble of writing a function when you can just pass a string? You may not need to. In simple situations, it's better to just pass a string. Small jobs don't need much power, and passing a string is quite a bit faster than passing a function. However, when the result you want requires a bit of processing, callback functions provide an elegant and comprehensible solution.

Example


			
			

Use a callback function to mark spans with class "date" as being "too late" - the date's already past.

$xml='<div>
  <p>
  	<span>The City Council will convene</span>
  	<span class="date">January 1, 2010</span>
  </p>
  <p>
  	<span>The Marching Band will perform</span>
  	<span class="date">July 4, 2011</span>
  </p>
  <p>
  	<span>The Mayan Club will hold its final meeting</span>
  	<span class="date">December 21, 2012</span>
  </p>
</div>
';
$px = new px($xml);


function fn_MarkIfTooLate ($px, $index)
{
	// get the matched node at index $index
	$currentSpan = $px->index($index);
	
	// if the date is past, mark it as "too late"
	if (strtotime($currentSpan->text()) < time())
	{
		$currentSpan->attr('title', "Too Late!");
		$currentSpan->addClass("tooLate");
	}
}

// the px::fn static function encapsulates a string
// into a px_function object, to be called as needed.
$fn = px::fn("fn_MarkIfTooLate");

// select the second span in each paragraph, and call
// each - the fn_MarkIfTooLate function is called.
$px->xpath("//span[@class='date']")->each($fn);

// show the results
echo $px->xml();
Result:
<div>
  <p>
    <span>The City Council will convene</span>
    <span class="date tooLate" title="Too Late!">January 1, 2010</span>
  </p>
  <p>
    <span>The Marching Band will perform</span>
    <span class="date tooLate" title="Too Late!">July 4, 2011</span>
  </p>
  <p>
    <span>The Mayan Club will hold its final meeting</span>
    <span class="date tooLate" title="Too Late!">December 21, 2012</span>
  </p>
</div>