我有一个Backbone应用程序正在运行,并且可以与requirejs一起正常使用。现在,我正在尝试迁移到Marionette,以便更好地组织代码。
我只想显示一个区域中某个集合的模型,而另一个区域中有两个按钮。我想转到该集合中的下一个或上一个模型。并更改其在模型区域上的视图。
但是我不知道如何遍历集合并将其模型发送到视图。
jsfiddle在这种情况下提供了一些简化的代码。
的HTML:
<div class="player"></div>
<script id="layout-template" type="text/template">
<div class="modelView"></div>
<div class="controls"></div>
</script>
<script id="model-region" type="text/template">
<%=name%>
</script>
<script id="control-region" type="text/template">
<button id="prev">Prev</button>
<button id="next">Next</button>
</script>
如果我理解您的问题,则您正在尝试在同一布局上的两个视图之间协调事件。在这种情况下,我建议设置一个Controller。
然后,您可以在控件视图上注册视图触发器:
ControlsView = Backbone.Marionette.ItemView.extend({
// ...
triggers: {
"click #previous": "control:previous",
"click #next": "control:next"
}
});
然后在控制器中,您将实例化视图并为controlView触发器设置处理程序以更新modelView。
var Router = Marionette.AppRouter.extend({
appRoutes: {
"/": "start",
"/:index" : "showModel"
},
});
var Controller = Marionette.Controller.extend({
initialize: function(){
var self = this;
this.controlsView = new ControlsView();
this.modelView = new MainView();
this.myCollection = new MyCollection();
this.myIndex = 0;
this.myCollection.fetch().then(function(){
self.myIndex = 0;
});
this._registerTriggers();
},
start: function(){
this.controlLayout.show(this.controlView);
this.showModel();
},
showModel: function(index){
index = index || this.index;
this.modelView.model = myCollection.at(this.index);
this.modelLayout.show(this.modelView);
},
showNext: function(){
var max = this.myCollection.models.length;
this.index = max ? 1 : this.index + 1;
this.showModel();
},
showPrevious: function(){
var max = this.myCollection.models.length;
this.index = 0 ? max : this.index - 1;
this.showModel();
},
_registerTriggers: function(){
this.controlsView.on("control:next", this.showNext());
this.controlsView.on("control:previous", this.showPrevious());
}
}
var controller = new Controller();
var router = new Router({
controller: Mod.controller
});
controller.start();
使用这种方法可以使视图和集合脱钩。这将使您的代码可重用(以不同上下文中的控件视图为例)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句