【问题标题】:In Tritium, what does the yield() function do?在 Tritium 中,yield() 函数有什么作用?
【发布时间】:2013-05-30 07:26:12
【问题描述】:

我正在查看 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"
}

【问题讨论】:

    标签: yield moovweb tritium


    【解决方案1】:

    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() function definition 看起来像这样:

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

    如您所见,wrap() 的函数定义中的 yield() 调用让 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
    }
    

    【讨论】:

    • 哇,解释这个概念的方法非常清晰、简单!
    • 那么yield函数允许其他函数在被调用的原函数范围内运行?
    • 嗨@gregorygtseng,这是完全正确的。另外,请注意,不同的函数将 yield() 在其函数范围内的不同位置,但通常标准库函数非常简单,它们会像您期望的那样 yield()。如果不确定,可以参考Tritium API reference获取原函数定义。
    猜你喜欢
    • 1970-01-01
    • 2020-05-30
    • 2018-02-22
    • 1970-01-01
    • 2019-09-10
    • 2014-01-18
    • 2011-05-18
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多