如何从客户端 CoffeeScript 动态更新 Jade 元素?
我正在尝试使用 SocketStream 动态更新值表。我有一个定义表的 Jade 模板:
app.jade:
table
thead
tr
th key
th value
tbody
- var jadeItems = [{key:'Test',value:'3.1415'}, {key:'Test2',value:'2.1878'}]
- each item in jadeItems
tr
td= item.key
td= item.value
这适用于静态数据,现在我需要使其动态。我有客户端 CoffeeScript,它接收一条 SocketStream 消息,其中包含 JSON 格式的表的新值:
app.coffee:
SS.events.on('message', (message) ->
jadeItems = JSON.parse(message)
)
我正在尝试找出如何将 Jade 中项目的 JSON 值替换为与消息的内容,但“jadeItems”变量超出了客户端 CoffeeScript 的范围。
我能够将新的 JSON 填充到 Jade 元素中,但随后我不确定如何获取 Jade 中“jadeItems”变量中元素的值。
有谁知道用于获取 Jade 元素值的 Jade 语法吗?或者有没有办法从客户端 CoffeeScript 中分配给 Jade 中定义的 items 变量?有没有关于 Jade 语法的可靠参考?
I'm trying to dynamically update a table of values using SocketStream. I have a Jade template defining the table:
app.jade:
table
thead
tr
th key
th value
tbody
- var jadeItems = [{key:'Test',value:'3.1415'}, {key:'Test2',value:'2.1878'}]
- each item in jadeItems
tr
td= item.key
td= item.value
This works for the static data, and now I need to make it dynamic. I have client-side CoffeeScript that receives a SocketStream message containing the new values for the table in JSON format:
app.coffee:
SS.events.on('message', (message) ->
jadeItems = JSON.parse(message)
)
I am trying to figure out how to replace the JSON value of items in Jade with with the content of the message, but the 'jadeItems' variable is out of scope in the client-side CoffeeScript.
I am able to stuff the new JSON into a Jade element, but then I'm unsure how to get the values for the element in the 'jadeItems' variable within Jade.
Does anyone know the Jade syntax for getting the value of a Jade element? Or is there a way to assign to the items variable defined in Jade from within the client-side CoffeeScript? Are there any solid references for Jade syntax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您使用 Jade 作为客户端模板库(这种情况很少见,但有可能):
为了纯粹通过 Jade 进行 Ajax 更新,您必须重新呈现模板。你必须做类似的事情(使用文档这里的示例)
你应该做的是制作 < code>jadeItems 该
locals
对象的属性。 使用该行因此,您无需在模板中
,而是使用Ajax 函数中的 Then 调用 Jade 渲染函数,并编写代码
以使用新数据重新渲染模板。
更新:鉴于问题评论中的澄清,更直接的答案是:“只需使用 jQuery 从 Ajax 回调操作 DOM。”这可能看起来像这样
(请注意,上面假设服务器响应已清理且格式良好)。
Assuming you're using Jade as a client-side templating library (which is rare, but possible):
In order to do your Ajax update purely through Jade, you'd have to re-render the template. You must be doing something like (using the example from the docs here)
What you should be doing is making
jadeItems
a property of thatlocals
object. So instead of the linein your template, you'd instead call the Jade render function with
Then in your Ajax function, you'd write
to re-render your template with the new data.
Update: Given the clarification in the comments on the question, the more direct answer is: "Just use jQuery to manipulate the DOM from the Ajax callback." That might look something like
(note that the above assumes that the server response is sanitized and well-formatted).