我已经构建了一个使用部分的ractive.js应用程序。这些部分是通过fetch/ajax加载的,而且它们都很好地工作。
然后,我决定要封装数据和部件,所以查看组件--正如我所理解的那样:用它的数据隔离一个模板/分部。
然后,我查看了在:http://ractivejs.github.io/ractive-load/中加载组件
但是,我并没有真正看到这种方法的优点--就像加载器显示的那样,您只能在组件模板中加载,而不能加载整个封装的组件(数据、模板等)。您仍然必须将数据放到主ractive实例上(就像使用分部时一样)。
我正在尝试动态更新组件。我还使用page.js进行路由。我正试着把所有的顾虑都分开。
我可能解释得不太清楚-这是我的密码.大部分是从殉道者的回答中摘取的,如何动态创建Ractive的子组件并以编程方式更改它们 )
....
<dynamic name='{{name}}'/>
</script>
<script>
// Component loader
Ractive.load({
home: '/components/home.html', // seems this can only contain a template. Is it possible for it to contain everything - data and all?
packs: '/components/packs.html',
....
addplayer: '/components/addplayer.html',
notfound: '/components/notfound.html',
}).then( function ( components ) {
Ractive.components[ 'home' ] = components.home;
Ractive.components[ 'packs' ] = components.packs;
....
Ractive.components[ 'addplayer' ] = components.addplayer;
Ractive.components[ 'notfound' ] = components.notfound;
// dynamically load component based on route
Ractive.components.dynamic = Ractive.extend({
template: '<component/>',
components: {
component: function() {
this.set('foo','bar'); // I can dynamically set the data here.. but how would I add defaults for each component, within the component?
return this.get('route');
}
},
oninit: function(){
this.observe('route', function(){
this.reset();
},
{ init: false}
);
}
});
var r = new Ractive({
el: document.body,
template: '#template',
data: {
route: 'home'
}
});
// Routing. Sets the route... which triggers the component
page('/', index);
...
page();
function index() {
console.log('index');
r.set('route','home')
}编辑
我读过这篇文章,这对我有很大的帮助:)
https://github.com/ractivejs/component-spec/blob/master/authors.md
在动态组件场景中-我将如何动态更新组件特定的数据。当组件标签硬连接到页面上时,我似乎能够做到这一点.但是当组件标记是动态创建的时候就不是了。在控制台里玩了很多之后--就好像它没有看到动态组件一样。所以像r.findComponent('home').get()这样的东西不起作用。
但是,如果我在模板中添加了一个<home/>标记,它就会工作。
此外,组件在未呈现时会自动“拆卸”吗?
发布于 2015-12-27 15:15:50
我不能百分之百确定你在找什么。
首先创建一个子组件-
var MyWidget = Ractive.extend({
template: '<div>{{message}}</div>',
data: {
message: 'No message specified, using the default'
}
});您可以将此注册到Ractive运行时。
Ractive.components.widget = MyWidget;然后创建一个父组件。
var Parent = Ractive.extend({
template: '<div>
<MyWidget message={{widget}} />
</div>'
});使用父实例将数据传递给子实例。
// Live instance of parent
new Parent({
el: 'id',
data : {
widget: {
message : 'Waddup kiddo'
}
}
});data.widget被映射到MyWidget的数据,然后在转接中得到消息数据。
有关更多信息,请参阅这
通常,您将创建3种类型的组件&使用-
因此,您决定如何制作您的组件,谁来负责,然后考虑数据封装。
https://stackoverflow.com/questions/34462624
复制相似问题