【问题标题】:using 'this' references with meteor.template.rendered在meteor.template.rendered 中使用“this”引用
【发布时间】:2015-07-16 04:28:22
【问题描述】:

假设我有一个名为 message 的 Meteor 模板,客户端可以在其中发布消息。帖子被包裹在一个 div 中,该 div 的 id 等于其在 Mongo 集合中的唯一 id。

<template name="message">
<div class="msg comment" id="{{this._id}}">{{msg}}</div>
</template>

有没有办法引用Meteor.message.rendered 中的特定ID?现在我正在使用this._id,但它不起作用。这是我的功能

Template.message.rendered = function() {
texts = $('this._id').html();
texts = texts.replace(/#(\w+)/g, 
"<a href='https://www.google.com/?q=$1'target='_blank'>$&</a>");
$("this._id").html(texts);
}

【问题讨论】:

    标签: javascript jquery mongodb meteor


    【解决方案1】:

    四件事:

    • 您使用的是字符串而不是变量:$('this._id') -> $(this._id)
    • 渲染函数的上下文(this)是一个模板助手,而不是数据本身(它是模板的上下文),所以将this._id替换为this.data._id以匹配{{ this._id }}
    • 这是一个 ID 选择器:$(this.data._id) -> $('#' + this.data._id)
    • 每当模板被重新渲染,以及子模板(模板中包含的模板)被渲染时,渲染回调就会运行,所以你应该在它被渲染时进行标记(source,关于流星渲染的有趣文章)。

    最终代码:

    Template.message.rendered = function() {
        if(!this.rendered) {
            this.rendered = true;
            texts = $('#' + this.data._id).html();
            texts = texts.replace(/#(\w+)/g,"<a href='https://www.google.com/?q=$1'target='_blank'>$&</a>");
            $('#' + this.data._id).html(texts);
        }
    }
    

    【讨论】:

    • 也许我实现了这个错误,但这是针对具有msg 类的每条消息(每条消息)。我正在尝试处理特定消息,而不是一次处理所有消息
    • 针对您的用例编辑了我的答案。
    猜你喜欢
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 2018-04-19
    • 2016-02-27
    • 2020-10-24
    • 2013-03-15
    相关资源
    最近更新 更多