前端编程提高之旅(七)----marionette实现tod

marionetteJS是在backboneJS基础上进行更简洁的操作,平常开发主要用到几个涉及到view的概念:CollectionView、CompositeView、ItemView、LayoutView。这几个概念中,用的最广的当属ItemView。ItemView相对于backbone中view的概念方便之处在于:不用显式定义render方法,而是由ItemView本身完成将数据渲染到模板,并将视图追加到el,由此可见减少了很多流程化的操作。

同时marionetteJS还有很多事件和回调方法如:onBeforeRender、onRender、onBeforeDestroy、onDestroy、onShow等。这些回调函数,都在相应事前执行前或后,被调用执行,即帮助开发人员设定好了时序的通用方法,大大简化了业务逻辑实现。

当然本文并不是详细讲述marionetteJS的原理,而是针对使用marionetteJS实现todoMVC功能(点击下载)做讲解。由于公司根据具体业务需要,在marionetteJS上又进行了一些封装实现,不过基本功能marionetteJS没有太大出入,故如看到代码中Italent无需惊慌,只需做到理念上的理解即可。

首先让我们看一下,项目目录、view目录及templates目录:



从以上三个目录来看,相对于上一篇文章采用backbone实现todoMVC似乎没有太大差别,那么差别在哪呢?

上篇文章中提到每个view所提供的职能:

  • 设置el或tagname,用于定义在上一层view放置的位置,或包裹的标签
  • 设置对应模板(Template)
  • 定义交互事件,并连带定义交互函数
  • 初始化函数(initialize),一般设置对collection或者model的监听,用于view之间的通信
  • 渲染函数(render),用于渲染数据到模板中,设置其他一些全局函数

 在marionetteJS中,各种view所实现的职能与上述职能类似,不同之处在于上文讲到内建Render及各执行时序上的回调,大大简化了开发。除此之外各原子视图并没有太大的变动。

这里着重讲解的是appView:

Talent.Layout.extend({
		//layout采用region
		model: new Talent.Model(),
		template: jst["about/app-page"],
		initialize: function() {
			this.collection = new Todos([{
				title: "ada"
			}, {
				title: "oman"
			}, {
				title: "come"
			}]); //初始化collection便于调试
			this.listenTo(this.collection, "add", this.addOne);
			this.listenTo(this.collection, "all", this.reDraw); // 监听collection的变化,执行添加和重绘
		}, //这里的重绘中,用于调整部分内容显示或隐藏的逻辑
		regionsClass: {
			input: InputView,
			list: TodoView,
			toggleAll: ToggleAllView,
			status: StatusView
		}, // 这里采用的regionsclass简写类
		regions: {
			// main: ".page-main-region"
			todoApp: "#todo-header",
			ToggleAll: "#todo-toggleAll",
			status: "#todo-footer"
			// todoList: "#todo-list"
		}, // regions部分简写元素部分
		ui: {
			// item: ".ui-item"
		},
		events: function() {
			var events = {};
			// events["click " + this.ui.item] = "eventHandler";
			return events;
		},
		onRender: function() {
		},
		onShow: function() {
			var self=this;
			this.todoApp.show(new this.regionsClass.input({
				collection: this.collection
			}));
			this.ToggleAll.show(new this.regionsClass.toggleAll({
				collection: this.collection
			}));
			this.addAll(); //已经渲染完再显示,用于显示所有初始化数据
			this.addStatus();		
			if (this.collection.length) {
				$("#main").show();
			}; //这里用于初始化显示collection数据
		}, // onshow用于app模板显示完,使用的逻辑。
		reDraw: function() {
			if(this.collection.length==0){
				this.flag = true;
			}
			if((this.collection.length>=1)&&this.flag)
			{
				this.addStatus();
				this.flag = false;
			}//通过设置一个flag属性,标记当collection从空到有值,再重新show statusview过程
			if (this.collection.length) {
		        //渲染时执行显示或隐藏的代码
		         $("#main").show();
		        //如果collection为空的话,则清空footer
		      } else {
		        $("#main").hide();

		      }
			
		}, //时刻监听collection变化,显示或隐藏部分region
		addStatus:function(){
			var statusView = new this.regionsClass.status({
				collection: this.collection,
				model: new Talent.Model({
					done: this.collection.done().length,
	                remaining: this.collection.remaining().length,
	                length:this.collection.length
				})
			});
			this.status.show(statusView);
		},//添加状态栏视图
		addOne: function(todo) {
			var listItem = new this.regionsClass.list({
				model: todo
			});
			listItem.render();

			$("#todo-list").append(listItem.$el);
			//这里不断加入新的项并渲染加入到appview中
		},
		addAll: function() {
			var self = this;
			_.each(self.collection.models, function(item) {
				self.addOne(item); //对collection每个都进行添加到appview页面中显示
			})
		}
	});
}); 

appView采用的是layout类,layout混合了ItemView及Region概念,非常适合管理多个子视图。appView下面有多个视图,采用layout非常合适。

layout有几个概念:

regionsClass: {
			input: InputView,
			list: TodoView,
			toggleAll: ToggleAllView,
			status: StatusView
		}, // 这里采用的regionsclass简写类
		regions: {
			// main: ".page-main-region"
			todoApp: "#todo-header",
			ToggleAll: "#todo-toggleAll",
			status: "#todo-footer"
			// todoList: "#todo-list"
		}, // regions部分简写元素部分

regionsClass属性可以给引入的类设置别名,regions属性则是对所要插入的区域节点设置别名。

当需要将子视图插入到appView视图指定区域时,执行如下代码:

this.todoApp.show(new this.regionsClass.input({
				collection: this.collection
			}));

这里,show方法起到的作用,是将子视图渲染并将el放到regions定义的区域节点下,则子视图被展示到appView指定区域。

上面提到marionetteJS各类视图都内建了render,那么之前采用backboneJS监听collection或者model变化所执行的this.render就受到了限制,因为除了将数据塞入模板及放到el下,我们可能还需要其他的逻辑连同执行。

乐帝这里采用了一个自定义方法,并做事件监听。

reDraw: function() {
			if(this.collection.length==0){
				this.flag = true;
			}
			if((this.collection.length>=1)&&this.flag)
			{
				this.addStatus();
				this.flag = false;
			}//通过设置一个flag属性,标记当collection从空到有值,再重新show statusview过程
			if (this.collection.length) {
		        //渲染时执行显示或隐藏的代码
		         $("#main").show();
		        //如果collection为空的话,则清空footer
		      } else {
		        $("#main").hide();

		      }
			
		}, //时刻监听collection变化,显示或隐藏部分region

事件监听:

this.listenTo(this.collection, "all", this.reDraw); // 监听collection的变化,执行添加和重绘

为了使程序更加标准,这里采用了新型的隐藏或展示视图的方式,涉及到status子视图的隐藏和展示。按照Jquery式编程,通过选取指定dom元素,采取show及hide方法,即可解决。

这里为了充分发挥数据驱动执行方式,在statusView视图中,当collection中model长度为零时,关闭视图:

reDraw: function() {
            if(this.collection.length==0){
                this.close();
            }
            var length = this.collection.length;
            this.model.set({
                done: this.collection.done().length,
                remaining: this.collection.remaining().length,
                length:this.collection.length
            });
            this.render();
        }

此时,视图关闭后,整个视图在dom及内存中被移除,当collection中model再次非零时,需要重启视图,就需要在appView里,重新show一个statusView。

这里定义了一个添加statusView方法:

addStatus:function(){
			var statusView = new this.regionsClass.status({
				collection: this.collection,
				model: new Talent.Model({
					done: this.collection.done().length,
	                remaining: this.collection.remaining().length,
	                length:this.collection.length
				})
			});
			this.status.show(statusView);
		},//添加状态栏视图

再将如上方法,在自定义监听collection变化的回调函数中引入即可:

reDraw: function() {
			if(this.collection.length==0){
				this.flag = true;
			}
			if((this.collection.length>=1)&&this.flag)
			{
				this.addStatus();
				this.flag = false;
			}//通过设置一个flag属性,标记当collection从空到有值,再重新show statusview过程
			if (this.collection.length) {
		        //渲染时执行显示或隐藏的代码
		         $("#main").show();
		        //如果collection为空的话,则清空footer
		      } else {
		        $("#main").hide();

		      }
			
		}, //时刻监听collection变化,显示或隐藏部分region

注意这里设置了一个标志属性flag,用于记录collection是从空到增加model,这种状态才重新开启statusView子视图。

至此,涉及到有关此篇采用marionetteJS实现todoMVC的关键问题,都已经做了阐述。

与backbone相比,更多的规则,带来的是更少的代码,采用任何技术都是在学习成本与高效开发上做权衡。


文章导航