Tuesday 27 December 2016

Observer Pattern in javascript

   In daily life we always need to do a add,edit,delete,update operation in our development life.
   to better go with it and to adopt a nice way of coding it is important to identify how structured our code is. So today i am going to do this with nice page operation in JavaScript through Observer design patterns.



Var Page = function(){ 
   this.Pages =[];
 

   return{
    addPage : function(pageid,pagename,pagecontent){

      this.Pages.push(pageid);
    /////function to ajax request to save new pages to database through backend

      },

   deletePage: function(pageid){
    ////checking page if contain in array Pages or not for some other use
    var index = this.Pages.indexOf(pageid);
    if(index >-1){
            this.Pages.splice(index,1)
      or

    //// Ajax to delete pages functions

    },


  update: function(pageid,pagecontent){
           //An ajax to check and update
      },

   selectAll: function(){
  // this is where you can select all pages and go through each one//
     for(var i=0; i< this.Pages.length; i++){
         // print div of pages on somehtml
         document.body.append(this.Pages[i]);

           };
      }
 };
};


var observer = function(){
  //here you can get page id from controls and put in external variables 
 // pageid = $('#pageid).val(),pagecontent= $('#pagecontent).val(),pagename= $('#pagename).val();

}

var pageid,pagecontent,pagename;

var pages = new Page();
pages.addPage(pageid,pagename,pagecontent);

////on deleting 

pages deletePage(pageid);

////on deleting 

   pages.update(pageid,content);

////page select function wherever need

 pages.selectAll();



if really said this is not a better design pattern but while writing codes we should accept a basic pattern so that our code looks clear.
we always do button operation in same way if we remove only Page keywords in this topics with button. we can go large function factory in that way. Remove all pages with button provide button id detail and do click or write click event and do click operation in that way.
In fact it seems clear if not i will try to improve it.

0 comments:

Post a Comment