2

I'm looking at the examples on the Tritium API website, and I don't understand what the yield() function does.

http://tritium.io/simple-mobile/1.0.224#yield()%20Text

Can someone explain these examples?

# first example 
@func XMLNode.foo {
  $a = "dog"
  yield()
\  log($a)
 }
# second example 
foo() {
  $a = $a + "cat"
}
@func XMLNode.foo {
  $a = "dog"
  log($a)
  yield()
}
foo() {
  $a = $a + "cat"
}
tdesikan
  • 513
  • 1
  • 4
  • 11
gregorygtseng
  • 851
  • 4
  • 12

1 Answers1

4

The yield() function allows you to write additional Tritium code inside the scope of a function call.

For example, you can use the wrap() function like this:

wrap("div") {
  add_class("product")
}

In this example, the wrap() function surrounds the current node inside a <div> tag, and then adds the class "product" to that tag, which results in the following HTML:

<div class="product">
  <!-- the node you originally selected is now wrapped inside here -->
</div>

The function call to add_class() is being performed inside the wrap() function's yield() block. The wrap() function definition looks like this:

@func XMLNode.wrap(Text %tag) {
  %parent_node = this()
  insert_at(position("before"), %tag) {
    move(%parent_node, this(), position("top"))
    yield()
  }
}

As you can see, the yield() call inside the function definition for wrap() lets the Tritium code yield its execution to the add_class() function that I wrote above.

So to use my example again, this section of code:

wrap("div") {
  add_class("product")
}

Is exactly like writing:

%parent_node = this()
insert_at(position("before"), "div") {
  move(%parent_node, this(), position("top"))
  add_class("product")  ## <-- This is where the code inside a yield() block gets added
}
Zkoh
  • 2,932
  • 3
  • 18
  • 14
  • 1
    wow, that's a really clear, easy way to explain this concept! – tdesikan May 30 '13 at 16:28
  • So the yield function allows other functions to be run in the scope of the original function that was called? – gregorygtseng May 30 '13 at 17:03
  • 1
    Hi @gregorygtseng, that is exactly correct. Also, note that different functions will `yield()` at different places in their function scope, but generally the standard library functions are quite straightforward and they will `yield()` like you expect them to. If you are unsure, you can consult the [Tritium API reference](http://tritium.io) for the original function definition. – Zkoh Jun 07 '13 at 18:41