RactiveJS-02 Nested properties

来源:互联网 发布:oracle删除字段数据 编辑:程序博客网 时间:2024/06/11 01:58

Ractive使用了Mustache语法,所以支持嵌套属性嵌套,对于JS来说,也就意味着对象属性还有这自己的属性。

通过.访问属性

看下面的例子:

<h1>This is Ractive Test</h1><div id="container"></div><script type="text/ractive" id="template">    <h2>Country profile</h2>    <P>{{country.name}} has a climate which is {{country.temperature}} and {{country.rainfall}}</p>    <p>Its population is {{country.population}} and its capital is {{country.capital.name}} and locates at {{country.capital.lat}} and {{country.capital.lon}}.</p></script><script>    var ractive1 = new Ractive({        el : '#container',        template : '#template',        data : {            country : {                name : 'China',                temperature : 'cold',                rainfall : 'excessive',                population : '120000000',                capital : {                    name : 'beijing',                    lat : 501,                    lon : 299                }            }          }    });</script>   

在模板中可以使用.语法来获取对应的嵌套的属性。在文档渲染后也可以通过set改嵌套属性的一个或者多个。

ractive1.set('country', {    name : '日本'})

使用上面的这种方式就会使country的其他属性默认为null,在文档中不予以渲染。所有如果仅仅要更改一个或属性可以使用下面这种形式:

ractive1.set('country.name','日本')

通过{{#value}}{{/value}}访问属性

上面通过类似JS属性的访问方法访问嵌套属性还是比较繁琐的,可以使用块(section)来为属性提供作用域,例如上面的模板就可以更改为:

<h2>Country profile</h2>{{#with country}}    <P>{{name}} has a climate which is {{temperature}} and {{rainfall}}</p>    {{#with capital}}        <p>Its population is {{population}} and its capital  is {{name}} and locates at {{lat}} and {{lon}}.</p>    {{/with}}{{/with}}

需要注意的有:
1、指明作用域块其实可以不必加with关键词,可以直接使用#和/表明块:

<h2>Country profile</h2>{{#country}}    <P>{{name}} has a climate which is {{temperature}} and {{rainfall}}</p>    {{#capital}}        <p>Its population is {{population}} and its capital  is {{name}} and locates at {{lat}} and {{lon}}.</p>    {{/country}}{{/country}}

但是Ractive官方文档建议加上with关键词,因为在上面的代码中,Ractive遇到{{#country}}之后会自己根据块的值去确定使用with、if还是each来渲染这个块。

所以显式的声明块的处理类型对于程序的可读性来说还是非常有益的。

2、一个块中应该包含一对完整的标签,不应该将其在循环中打开,比如:

{{#capital}}    <p>Its population is {{population}} and its capital  is {{name}} and locates at {{lat}} and {{lon}}.{{/country}}</p>

这样程序就会报错。

3、在上面的代码中有两个name属性,其中属于capital块中的name属性有两个作用域,当最近的作用域可以找到对应的值时就取这个值,如果最近的作用域中没有对应值时就向上寻找,知道最外层的data的作用域。(与JS变量的函数中变量的作用域类似)

0 0
原创粉丝点击