Sprint 2b – MVC – Model

Model Component Source Code

/* MODEL object */
var gobjModel = new function() {
  var self = this;
  var controller;
  var listData;
  var listIndex = 0;
  var selectedTaskId;

  function preserveTaskListData() {
    localStorage.setItem("ToDoListJSON", 
	JSON.stringify(listData));
  }

  function restoreTaskListData() {
    return localStorage.getItem("ToDoListJSON");
  }

  function findTaskItem() {
    var numItemPosition = -1;
    var numItem;
    var numTaskId = Number(selectedTaskId.split("_")[1]);

    for (numItem=0; numItem<listData.list.length; 
	numItem+=1) {
      if (numTaskId == listData.list[numItem].Id) {
        numItemPosition = numItem;
      }
    }
    return numItemPosition;
  }

  self.setListIndex = function(pnumListIndex) {
    listIndex = pnumListIndex;
  };

  self.getTaskList = function() {
    return listData;
  };

  self.getSelectedTask = function() {
    return selectedTaskId;
  };

  self.setSelectedTask = function(numTaskId) {
    selectedTaskId = numTaskId;
  };

  self.updateTask = function(pstrTaskText) {
    listData.list[findTaskItem()].Task = pstrTaskText;
    preserveTaskListData();
  };

  self.createTask = function(pstrTaskText) {
    var objNewTask = {
      Id: (listIndex+=1),
      Task: pstrTaskText
    };
    listData.list.push(objNewTask);
    preserveTaskListData();
    return listIndex;
  };

  self.deleteTask = function() {
    listData.list.splice(findTaskItem(),1);
    preserveTaskListData();
  };

  self.initialise = function( pobjController) {
    var objToDoList = restoreTaskListData();
    var arrListData = {list:[]};

    controller = pobjController;
    if (!!objToDoList) {
      arrListData = JSON.parse(objToDoList);
    }
    if (!arrListData.list || !arrListData.list.length){
      if (confirm("Pre-populate?")) {
	arrListData.list = [
	  {Id:1, Task:"Get out of bed"},
	  {Id:2, Task:"Brush teeth"},
	  {Id:3, Task:"Shower"},
	  {Id:5, Task:"Grab breakfast"}
	];
      }
      else {
	arrListData.list = [];
      }
    }
    listData =  arrListData;
  };
};

Return to previous page.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s