2

我正在查看 Tritium API 网站上的示例,但我不明白 yield() 函数的作用。

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

有人可以解释这些例子吗?

# 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"
}
4

1 回答 1

4

yield()函数允许您在函数调用范围内编写额外的 Tritium 代码。

例如,您可以wrap()像这样使用函数:

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

在此示例中,该wrap()函数将当前节点包围在<div>标签内,然后将“产品”类添加到该标签中,从而生成以下 HTML:

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

函数调用add_class()是在wrap()函数yield()块内执行的。wrap() 函数定义如下所示:

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

如您所见,yield()函数定义中的调用 forwrap()让 Tritium 代码其执行交给add_class()我上面编写的函数。

因此,再次使用我的示例,这部分代码:

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

就像写:

%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
}
于 2013-05-30T09:46:19.763 回答