【问题标题】:jsView - How to render the content of a custom tag with its props as its data?jsView - 如何使用其道具作为数据呈现自定义标签的内容?
【发布时间】:2013-04-25 07:14:45
【问题描述】:

我有自定义标签,它可以将自己作为内部标签,我想将它的props 绑定为data。我可以更改第一个 test 标记 title 属性并查看更改,但不能对内部 test 标记执行此操作。我认为这是因为this.tagCtx.content.render() 的参数错误。下面是例子:

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="js/jsrender.js" type="text/javascript"></script>
<script src="js/jquery.observable.js" type="text/javascript"></script>
<script src="js/jquery.views.js" type="text/javascript"></script>

<script id="testTemplate" type="text/x-jsrender">
    <div>{^{>title}}{^{:content}}</div>
</script>

<script id="myTemplate" type="text/x-jsrender">
    {^{test title='Test1'}}
        {^{test title='Test2'}}
        {{/test}}
    {{/test}}
</script>

<script type="text/javascript">
    $.views.tags({
        test: {
            render: function(){
                this.tagCtx.props.content = this.tagCtx.content.render();
                return this.template.render(this.tagCtx.props, this.tagCtx, this.tagCtx.view);
            },

            template: "#testTemplate"
        }
    });

    $.templates({myTemplate: "#myTemplate"});

    $(function () {
        $.link.myTemplate('#container', {});

        $('#editTitle').click(function () {
            $.observable($.view('#container div:first div').data).setProperty('title', prompt());
        });
    });
</script>
</head>
<body>
    <span id="editTitle">EditTitle</span>
    <div id="container"></div>
</body>
</html>

【问题讨论】:

    标签: jsviews


    【解决方案1】:

    这里的问题是内部标签被渲染为字符串,而不是数据链接标签,因为this.tagCtx.content.render()调用只是在与块内容对应的编译模板上调用渲染方法。

    如果要呈现为数据链接标签,则需要调用this.tagCtx.render()

    此外,在调用this.tagCtx.render() 时,您需要标签来呈现其内容,而不是另一个模板。设置template: "#testTemplate" 将导致标签使用该模板而不是内容。所以你需要的是这些方面的东西:

    var template = $.templates("#testTemplate"); 
    
    $.views.tags({
        test: {
        render: function() {
                var tagCtx = this.tagCtx;
                tagCtx.props.content = tagCtx.render();
                return template.render(tagCtx.props, undefined, tagCtx.view);
            }
        }
    });
    

    您可能不想在template.render(...) 调用中将tagCtx 作为上下文传递。可以传入tagCtx.ctx,或者干脆undefined...

    【讨论】:

    • 现在 #parent.data 有效,但 ~root 无效。我问了here
    猜你喜欢
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 2011-12-14
    • 2015-05-07
    • 2011-03-08
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    相关资源
    最近更新 更多