我正在查看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"
}
答案 0 :(得分:4)
yield()
函数允许您在函数调用范围内编写额外的Tritium代码。
例如,您可以使用wrap()
函数,如下所示:
wrap("div") {
add_class("product")
}
在此示例中,wrap()
函数围绕<div>
标记内的当前节点,然后将类“product”添加到该标记,从而产生以下HTML:
<div class="product">
<!-- the node you originally selected is now wrapped inside here -->
</div>
正在add_class()
函数的wrap()
块内执行对yield()
的函数调用。 wrap()
function definition看起来像这样:
@func XMLNode.wrap(Text %tag) {
%parent_node = this()
insert_at(position("before"), %tag) {
move(%parent_node, this(), position("top"))
yield()
}
}
正如您所看到的,yield()
函数定义中的wrap()
调用允许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
}