前端編程提高之旅(七)----marionette實現todoMVC

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   io   os   ar   使用   

          

   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採用regionmodel: 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變化,顯示或隱藏部分regionaddStatus: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相比,更多的規則,帶來的是更少的代碼,採用任何技術都是在學習成本與高效開發上做權衡。

前端編程提高之旅(七)----marionette實現todoMVC

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.