Model for adding book

We have created the static view. The next thing is to have the model ready.

We defind a Book definition inside model scope where we will create Book instance for our record.

Please note that we do not need to expose the Book definition because only the model scope needs to create Book instance. Other modules just use the Book instances.

What we expose outside the model scope is a data object with books array and addBook function.

 1// Model
 2// Anything related to data querying and manipulation
 3;(function($){
 4  var app = this.app || (this.app={});
 5
 6  var Book = (function(){
 7    function Book(title, isbn) {
 8      this.title = title;
 9      this.isbn = isbn;
10    }
11    return Book;
12  })();
13
14  app.data = {};
15  app.data.books = [];
16  app.data.addBook = function(title, isbn) {
17    app.data.books.push(new Book(title, isbn));
18  };
19
20}).call(this, jQuery);

We will test the model logic before moving on. We do that by adding the following code ind the controller. It handles the click event of the button and add a dummy book to the data.

 1;(function($){
 2
 3  // Entry point
 4  $(function(){
 5
 6    $('#add-book-btn').click(function(){
 7      app.data.addBook('Testing book', '1234567890123');
 8    });
 9
10  });
11
12}).call(this, jQuery);

When testing the code in browser, we click the button several times. Then try to inspect the app.data.books array and we should see some dummy data. The count of the data should equal to the times you clicked the add-book button.

Books data log

What’s next? We’re going to take a look at “View for adding book”.

overlaied image when clicked on thumbnail

Makzan | Mobile web app dev with phonegap | Table of Content