Search code examples
javascriptjsviews

How can I bind to element attribute in jsview


I have a label like below. I wonder is it possible for jsview to support binding its title to its text? Can I show the same text in its title?

<label title="">{^{for Owners}}{{:Name}}{^{if #index < #parent.data.length - 1}}&#59;{{/if}}&nbsp;{{/for}}</label>

The expected rendered result would be:

<label title="name1; name2; name3">name1; name2; name3</label>

Solution

  • When using JsViews to data-link to elements, element attributes etc, you need to use the data-link attribute. When using JsViews link method (as opposed to JsRender render method) you can't nest {{...}} tags within element markup.

    See http://www.jsviews.com/#samples/data-link for a tutorial sequence on data-linking elements.

    Using data-link="expression" is quite flexible, so there are a few alternative ways you can achieve your scenario. Here is a jsfiddle with three alternatives: http://jsfiddle.net/BorisMoore/j363W/.

    It shows these three variants:

    Custom helper

    <label data-link="title{:~listHelper(Owners, Owners.length)}">...

    myTmpl.link("#content", data, {listHelper: function(arr) { return ...; // compute return value }});

    Data method

    <label data-link="title{:nameList()}">...

    var data = {
        Owners:[{Name: "name1"}, {Name: "name2"}, {Name: "name3"}],
        nameList: function() {
        return ...; // compute return value
        },
        ... 
    };
    
    data.nameList.depends ="Owners.length";
    

    Custom JsViews tag

    <label data-link="title{nameList Owners}">...

    $.views.tags("nameList", {
        render: function(Owners) {
            return ...; // compute return value
        },
        depends: "Owners.length"
    });
    

    See also https://github.com/BorisMoore/jsviews/issues/255