上下文(context)
个人认为,context是对访问资源、访问资源权限的抽象,或者说是能够访问的属性或方法的资源库。
在riot中,每个自定义标签都有一个context,通过这个context可以访问该标签对象的属性和方法。当前标签中的context就是this,这个在前几篇中已经经常用到了。另外,对于通过each迭代的每个item,riot也会给他生成一个单独的context,这个context只能访问当前item的属性,而不能访问标签的属性和方法,例如:
var template = '<li each="{items}"><span>姓名:{name}</span>---<span>年龄:{age}</span></li>'; riot.tag('person', template, function(opts) { this.items = opts; this.tagMsg = "用户信息列表"; }) riot.mount('person', [{name:'张三', age:12},{name:'李四', age:13}]);在each的item中可以访问name、age,但是想要访问标签的tagMsg属性是不行的,因为二者不在同一个上下文中。但二者是有父子关系的,为此可以使用parent.tagMsg访问,parent是父上下文的引用,如改为:
var template = '<li each="{items}"><span>姓名:{name}</span>---<span>年龄:{tagMsg}</span><span>表名称:{parent.tagMsg}</span></li>';另外,对于嵌套标签(会在下篇将)的上下文也是父子关系, 也可通过parent访问父标签的属性和方法。如:
<body> <persons></persons> </body> </html> <script> var template = '<span>人数:{parent.personNum}</span>'; riot.tag('person', template, function(opts) { }) template = '<person></person>'; riot.tag('persons', template, function(opts) { this.personNum = "50人"; }); riot.mount('persons'); </script>
还有一点需要注意的,对于直接在标签上添加的属性,如<person address="北京市海淀区"></person> 并不属于上下文,不能通过this、parent访问,只能通过opts访问,如:
<body> <person address="北京市海淀区"></person> </body> </html> <script> var template = '<span>姓名:{name}</span>---<span>年龄:{age}</span><button onclick="{ showAddress }">地址</button>'; riot.tag('person', template, function(opts) { this.address = opts.address;//不能直接使用this.address this.showAddress = function(e) { alert(this.address); }.bind(this); }) riot.mount('person', [{name:'张三', age:12},{name:'李四', age:13}]); </script>这个特性对于嵌套标签是比较重要,可以通过此方法将父标签的参数传递给子标签,会在下文讲。