Pregunta

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"
}
¿Fue útil?

Solución

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
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top