前端編程提高之旅(四)----backbone初體驗,----backbone初體驗
來到新的實習單位,公司的業務模式、組織架構、開發技術、開發規範對於樂帝這樣的職場菜鳥來說都是新的,這一周入職的這幾天主要在熟悉公司採用的前端架構,前端架構基本包括:backbone、marionette、requirejs。由於樂帝在愛奇藝實習期間,自學了PHP技術,對smarty模板及thinkphp架構有一個瞭解,接觸前端MVC還是有點基礎的。
公司有一套專業的前端培訓流程清單。這周主要的工作包括:閱讀backbone簡要文檔、讀backbone的todoMVC例子、通讀backbone官方文檔、再讀backbone的todoMVC例子、閱讀marionette簡要介紹、按照todoMVC源碼,手寫了一遍todoMVC代碼、閱讀backbone總結文章,總算大體弄清楚了backbone的來龍去脈。
回頭來看,對於提升學習效率最高的方法是:閱讀簡單概念的介紹並配合例子、看一個比較綜合的例子對簡單概念做吸收、閱讀官方文檔所有API、敲一遍綜合例子做吸收。這樣的學習順序遵循了認識、實踐的原則。樂帝基本上按照這樣的順序學習了backbone。下面程式碼片段的注釋是樂帝從整體對model、collection、view的理解。
$(function(){var Todo = Backbone.Model.extend({default:function(){return {title:"hello ledi",order: Todos.nextOrder(),done:false};},toggle:function(){return this.save(done,!this.get("done"));}});//構造基本的資料模型及對資料的處理TodoList = Backbone.Collection.extend({model:Todo,localStorage: new Backbone.LocalStorage("todos-backbone"),done:function(){return this.where({done:true});},remaining:function(){return this.where({done:false});},nextOrder:function(){if(!this.length){return 1;}else{return this.last().get('order')+1;}},comparator:'order'});//作為資料模型的集合,對模型進行增刪尋找、排序等管理var Todos =new TodoList;var TodoView = Backbone.View.extend({tagName:"li",template: _.template($('#item-template').html()),events: { "click .toggle" : "toggleDone", "dblclick .view" : "edit", "click a.destroy" : "clear", "keypress .edit" : "updateOnEnter", "blur .edit" : "close" },//事件定義,控制互動部分 initialize:function(){ this.listenTo(this.model,'change',this.render); this.listenTo(this.model,'destroy',this.remove); },// 通過監聽與model資料實現綁定 render:function(){ this.$el.html(this.template(this.model.toJSON())); this.$el.toggleClass('done', this.model.get('done'));//切換是否有done類,調試查看此類 this.input = this.$('.edit'); return this; },//初始化渲染模板內容,作為顯示部分 toggleDone:function(){ this.model.toggle(); }, edit:function(){ this.$el.addClass(".editing"); this.input.focus(); }, close:function(){ var value = this.input.val(); if(!value) { this.clear(); } else{ this.model.save({title:value}); this.$el.removeClass(".editing"); } }, updateOnEnter:function(e){ if(e.keyCode == 13) { this.close(); } }, clear:function(){ this.model.destroy(); }});//todoview與model一一對應,對model資料進行顯示及互動操作 var appView = Backbone.View.extend({ el: $("#todoapp"), statsTemplate: _.template($('#stats-template').html()),// 統計模板 events: { "keypress #new-todo": "createOnEnter", "click #clear-completed": "clearCompleted", "click #toggle-all": "toggleAllComplete" },// 監聽事件 initialize:function(){ this.input = this.$("#new-todo"); this.allCheckbox = this.$("#toggle-all")[0]; this.listenTo(Todos, 'add', this.addOne); this.listenTo(Todos, 'reset', this.addAll); this.listenTo(Todos, 'all', this.render); this.footer = this.$('footer'); this.main = $('#main'); Todos.fetch(); },//監聽collection的變化,實現與collection的綁定 render:function(){ var done = Todos.done().length; var remaining = Todos.remaining().length; if(!Todo.length){ this.main.show(); this.footer.show(); this.footer.html(this.statsTemplate({done: done, remaining: remaining})); } else{ this.main.hide(); this.footer.hide(); } this.allCheckbox.checked = !remaining; },// 實現整體顯示 addOne:function(todo){ view = new TodoView({model:todo}); this.$("#todo-list").append(view.render().el); }, addAll:function(){ Todos.each(this.addOne,this);//這裡用到collection和model溝通了 }, createOnEnter:function(e){ if(e.keyCode!=13) return; if(!this.input.val()) return; Todos.create({title:this.input.val()}); this.input.val(''); }, clearCompleted:function(){ _.invoke(Todos.done,'destroy'); return false; }, toggleAllComplete:function(){ var done = this.allCheckbox.checked; Todos.each(function(todo){todo.save(done,'done');}); } });//作為全域的view,控制多個todoview顯示互動及其他顯示模組的互動部分 var app = new appView;})//view基本模式:通過初始化及渲染函數進行最初顯示,並通過定義事件列表,編寫對應執行函數,實現互動
以上例子是樂帝研究的todo例子,並動手敲了一遍,對各個模組功能的理解。model提供資料模型及對資料處理;collection則是model的集合,主要以model為處理對象,對其增刪尋找、排序等各種操作;view則是傳統後端MVC架構中的起Controller功能,主要負責控制顯示、互動邏輯。
backbone簡要文檔對view的論述並沒有後來讀的文章寫得清楚,這裡樂帝給出介紹view及模板的典型例子,用於理解view作為MVC核心地位的職能;
<!-- Templates --> <script type="text/template" id="hello-template"> <div> <h3 id="hello"><%= message %></h3> <button id="toggle">Toggle</button> </div> </script> <!-- underscore內建模板引擎,通過<%= var %>接收傳入的變數 --> <script type="text/javascript">var TestView = Backbone.View.extend({ events: { 'click button#toggle' : 'toggle' }, initialize: function() { this.template = _.template($("#hello-template").html()); // 設定模板 this.render(); }, render: function() { this.$el.html(this.template({message: "hello world!"})); // 渲染模板 return this; }, toggle: function() { this.$("#hello").toggle(); return this; } }); $(function () { var v = new TestView({el: $('#hello')}); });//這個例子中,給出了設定模板、傳入參數、渲染頁面、添加互動事件的方法,對於理解view功能:顯示頁面、添加互動,非常有協助。//http://blog.csdn.net/raptor/article/details/8566017</script>
這段代碼給出的顯示和互動非常簡單,麻雀雖小、五髒俱全。能非常清楚的看到view用於顯示頁面和添加互動所要做的事情。接下來則是model和collection的例子:
var Foo = Backbone.Model.extend({}); // 或是初始化預設資料 var Foo = Backbone.Model.extend({ defaults: { name: "hello", value: "233" } }); // 或是運行時賦值。 // 比如這樣: var foo = new Foo({name:"world", value:"874"}); // 或這樣: var foo = new Foo; foo.set({name:"world", value:"874"}); var FooList = Backbone.Collection.extend({ model: Foo }); var foos = new FooList; foos.add([{name:"hello", value:"233"},{name:"world", value:"874"}]); $(function () { $("#hello").text(JSON.stringify(foos.at(0))); ; });
這段代碼給出了model及collection基本定義和使用,除此之外還會涉及增刪尋找、有效性驗證、事件綁定等功能。由雩都會涉及到後端的互動,這裡樂帝涉獵不多,詳情可戳我。
至於router則是定義路由規則,相對簡單。樂帝下一步則是需要在這個基礎上使用requirejs組織todoMVC代碼以及閱讀marionette使用其寫一個todoMVC例子,並最終在talentjs上寫MVC例子,真正的上手項目。