定义用作列表元素的组件
Define a component used as list element
我有一个组件想用作某种列表元素:
var ListElement = Ractive.extend({
// the template defining the look of each list element
// is currently defined within a <script> block
template: '#listElementTmpl';
});
此外,我有某种父级维护列表及其元素:
var App = Ractive.extend({
template: 'appTmpl',
components: {
ListElement: ListElement
},
data: {
listElements: []
},
add: function(info) {
var element = new ListElement({
data: {
info: info
}
});
this.push('listElements', element);
}
});
最后,我会将应用程序的模板定义为:
<div>
{{#each listElements}}
<ListElement />
{{/each}}
</div>
列表元素是按照其模板中的定义绘制的,但不幸的是,数据绑定不知何故在某处丢失了。谁能告诉我,我错过了什么?
您不需要创建组件元素,您只需修改数据,ractive 就会为您创建组件。
var ListElement = Ractive.extend({
template: '#listElementTmpl'
});
var App = Ractive.extend({
template: '#appTmpl',
components: {
ListElement: ListElement
},
add: function(info) {
this.push('list', { info } );
this.set('newInfo');
}
});
new App({
el: document.body,
data: {
list: [{
info: 'some info from first item'
}]
}
});
<script src="http://cdn.ractivejs.org/edge/ractive.min.js"></script>
<script id='appTmpl' type='text/ractive'>
<ul>
{{#each list}}
<ListElement info='{{info}}'/>
{{/each}}
</ul>
<div>
<input value='{{newInfo}}'>
<button on-click='add(newInfo)'>add</button>
</div>
</script>
<script id='listElementTmpl' type='text/ractive'>
<li>{{info}}</li>
</script>
我有一个组件想用作某种列表元素:
var ListElement = Ractive.extend({
// the template defining the look of each list element
// is currently defined within a <script> block
template: '#listElementTmpl';
});
此外,我有某种父级维护列表及其元素:
var App = Ractive.extend({
template: 'appTmpl',
components: {
ListElement: ListElement
},
data: {
listElements: []
},
add: function(info) {
var element = new ListElement({
data: {
info: info
}
});
this.push('listElements', element);
}
});
最后,我会将应用程序的模板定义为:
<div>
{{#each listElements}}
<ListElement />
{{/each}}
</div>
列表元素是按照其模板中的定义绘制的,但不幸的是,数据绑定不知何故在某处丢失了。谁能告诉我,我错过了什么?
您不需要创建组件元素,您只需修改数据,ractive 就会为您创建组件。
var ListElement = Ractive.extend({
template: '#listElementTmpl'
});
var App = Ractive.extend({
template: '#appTmpl',
components: {
ListElement: ListElement
},
add: function(info) {
this.push('list', { info } );
this.set('newInfo');
}
});
new App({
el: document.body,
data: {
list: [{
info: 'some info from first item'
}]
}
});
<script src="http://cdn.ractivejs.org/edge/ractive.min.js"></script>
<script id='appTmpl' type='text/ractive'>
<ul>
{{#each list}}
<ListElement info='{{info}}'/>
{{/each}}
</ul>
<div>
<input value='{{newInfo}}'>
<button on-click='add(newInfo)'>add</button>
</div>
</script>
<script id='listElementTmpl' type='text/ractive'>
<li>{{info}}</li>
</script>