Creating a MVC Object

Here is an overview for creating a MVC Object. Every part of it is described in detail below (starting with 'MVC Object Parameters').


$(function() {
  // The view ID should be a selector of the element containing all the data relevant to the model.
  // Note: The data can still be used and updated outside the View.
  // The model and settings object literals are merged and returned
  // obj contains all the information about the object, which keeps the view synchronized with the model and vice versa.
  var obj = $("#testArea").ModelView({
    model: {
      id: 'foo',
      firstName : 'John',
      lastName : 'Doe',
      type: 'bar'
    },
    settings: {
      controller: MVC.Controller({
        save: function(event, object) {
          // console.log(event);
          console.log(object.GetModelData());
          // handle event
        }
      }),
      // Should changes in the model be reflected in the view?
      // Changes in the view will always be reflected in the model, but the other way is optional.
      isMirror: true, // false
      // Set the model to autosave every X ms. Remember to implement the Save() method in the controller!
      // autoSaveInterval: 1000, //15 seconds (15000ms)
      // Callback function - When input elements change (not div, span or p elements).
      // change: function(e, n, v, o, t, s) { // event, name, value, object, targetValue, selectedValue
          //do something when input changes
      //}
      // Other event types: focus, blur, change, select, submit, keyup, keydown and keypress
    },
    methods: {
      init: function(o) { // Simple MVC built-in initalize method which runs after 1 ms

      }
    }
  });
  // Add a computed property
  obj.Set('fullName', function(o) {
    return ("{0} {1}").format(o.firstName, o.lastName);
  });

  //Manipulate the object 'obj' here...
  //Set a new value for a property in the model and update the view:
  obj.Set('type', 'type value has changed both in the Model and View!');
  //Set a new value for a property in the model (but not in the view):
  obj['type'] = 'type value has changed in the Model!';

  //foo and bar should be same if 'isMirror' : true
  var foo = obj.Get('type'); //Access DOM value
  var bar = obj['type']; //Access Object's value

  $('#saveObj').click(function() {
    var extraPar = $('#someId').text();
    obj.Save(extraPar);
  });

  $('#updateObj').click(function() {
    var extraPar = $('#someId').text();
    obj.Update(extraPar);
  });

  $('#deleteObj').click(function() {
    var extraPar = $('#someId').text();
    obj.Delete(extraPar);
  });

});

Simple MVC Parameters

The Simple MVC ModelView() takes 4 parameters: viewId (required), model (optional), settings (optional) and methods (optional).

    // Simple MVC with model, settings and model
    var obj = $("#viewId").ModelView(model, settings, methods);
    // Simple MVC without any optional parameters
    var obj = $("#viewId").ModelView();
  

viewId


The viewId should be a selector of the element containing all the data relevant to the model.
Note: The data passed from the elements in the View to the Model can still be used and updated outside the View.



model


The model is an Object Literal (JSON) which basically is the Model object passed as a parameter and returned (merged with the settings object) after all the internal setup of the object is done.
Important
The property name in the Model should be identical to:

  • The name attribute of the form elements in the View
  • The id or datafld attribute of p, span or div elements in the View.

Example

          //The object
          var obj = {somePropertyName:'someValue'};
          //The view
          <input type="text" name="somePropertyName" />
        



settings (optional)


The settings object is optional, because by default the settings will be set to contain the viewId and isMirror : true
Settings overview:

  • settings['viewId']
  • settings['isMirror']
  • settings['controller']
  • settings['autoSaveInterval']
  • settings['eventName']


settings['viewId']


The viewId will be set automatically if not specified.


settings['isMirror']


The isMirror can either be true or false. If true, then the View is updated when the Model is changed. If not specified, it will be set to true.


settings['controller']


The controller which handles the logic.

Example

      var viewId = "#someViewId",
      ctr,
      settings,
      obj;

      ctr = MVC.Controller({
      Save : function(obj, par) {
      //do something with object 'obj'
      //Implement necessary funcitonality here
    },
    Update : function(obj, par) {
    //do something with object 'obj'
    //Implement necessary funcitonality here
  },
  Delete : function(obj, par) {
  //do something with object 'obj'
  //Implement necessary funcitonality here
}
});

settings = {
controller : ctr, //Add the controller to the settings object
}

obj = MVC.ModelView(viewId, { foo : 'bar' }, settings);

obj.Save({foo:'bar});
obj.Update({foo:'bar});
obj.Delete({foo:'bar});


settings['autoSaveInterval']


The autoSaveInterval will autosave the model's data every X ms (milliseconds), but only if the Save() method in the controller is specified.

Example

      var viewId = "#someViewId",
      ctr,
      settings,
      obj;

      ctr =  MVC.Controller({
      Save : function(obj){
      //do something with object 'obj'
    }
  });

  settings = {
  controller : ctr, //Add the controller to the settings object
  autoSaveInterval : 5000 //autosave every 5 seconds
}

obj = MVC.ModelView(viewId, { foo : 'bar' }, settings);


settings['eventName']


It's possible to set the object to 'listen' to events. Available events:
focus, blur, change, select, submit, keyup, keydown, keypress and focus
The data returned from the event function is:
event: Information about the event. Such as event.data, event.target, event.type, etc...
name: The input's name - Is more convenient than calling event.target.name as this is a common value to use.
value: The input's value - Is more convenient than calling event.target.value as this is a common value to use.

Example

      var viewId = "#someViewId",
      obj,
      settings;

      var settings = {
      focus : function(event, name, value) {
      //event.target.name === name
      //event.target.value === value
      //do something when the input has gained focus
    },
    blur : function(event, name, value) {
    //event.target.name === name
    //event.target.value === value
    //do something when the input has lost focus
  },
  [eventName] : function(event, name, value) {
  //[eventName]: focus, blur, change, select, submit, keyup, keydown, keypress or focus
  //event.target.name === name
  //event.target.value === value
  //handle the event
}
}

obj = MVC.ModelView(viewId, { foo : 'bar' }, settings);



Adding elements in the view to the model


Valid elements: p, span, div and form elements
Use id="[someId]" or datafld="[someId]" for p, span and div elements to add them to the model
Use name="[someName]" for form elements to add them to the model

Examples

    <p id="[someId]">someValue<p>
    <div id="[someId]">someValue<div>
    <span id="[someId]">someValue<span> or <span datafld="[someId]">someValue<span>
    <input name="[someId]" type="[type]" value="[value]" />
  

Databind elements to other elements which are bound to the model

Valid elements: p, span, div and form elements
Use datasrc="[#someViewId]" and name="[somePropertyName]" to databind the element to the Model/View.
The datasrc should correspond to the id of a View.
The name should correspond to the property in the model (the name of the element in the View).
If you want to databind an element to another element in the same View, then you need to add class="excludeFromModel" to the element or else it will be part of the Model too - if on the other hand you want the element to be part of the Model too, then don't add the class to the element.

Examples

    //Inside the view:
    <span class="excludeFromModel" datasrc="[#someViewId]" name="[somePropertyName]">someValue<span>
    <input class="excludeFromModel" datasrc="[#someViewId]" name="[somePropertyName]" type="text" />

    //Outside the view:
    <span datasrc="[#someViewId]" name="[somePropertyName]">someValue<span>
    <input class="excludeFromModel" datasrc="[#someViewId]" name="[somePropertyName]" type="text" />

    //This input element will be databound to the property 'type' in the View with the id 'testArea'.
    <span name="type" datasrc="#testArea"></span>
  


MVC Object Methods


Note: Older IE browsers don't support accessing an Object's property using dot notation. Therefore always access by association.
Don't use object.property
Do use object['property'] or object.Get('property')

.Set(property, value)


The .Set() method updates a property in the Model and is reflected in the View (including databound elements).
Notice that the .Set() method will update the View with values from the Model when called.
This is by design, but can seem a bit confusing (maybe) to start with. See this example, which demonstrates this (intended) behaviour.

Note: The method will only work when isMirror : true.
Note: This is not the same as setting the property value directly: object['property'] = 'value';

Examples

      var viewId = "#someViewId",
      obj;
      obj = MVC.ModelView(viewId, { foo : 'bar' });
      //Method 1: Updates the value in the Model and also the View (including databound elements)
      obj.Set('foo', 'foo changed in Model and View');
      //Method 2: Updates the value only in the Model
      obj['foo'] = 'foo changed only in Model';
      //Method 3: Update the value in the Model and call .SetViewFromModel() afterwards.
      obj['foo'] = 'foo changed initially in the Model, but the View has been updated with values from the Model using the .SetViewFromModel() method.';
      obj.SetViewFromModel();
    

.Get(property)


The .Get() method returns the value for specfied object's property.
Note: The method will only work when isMirror : true.

Example

        var viewId = "#someViewId",
        obj;
        obj = MVC.ModelView(viewId, { foo : 'bar' });
        var foo = obj.Get('foo'); //Same as obj['foo'];
      

.Save(parameters)


Call the .Save() method whenever you want to save the object.

Example

        var viewId = "#someViewId",
        ctr,
        obj;

        ctr = MVC.Controller({
        Save : function(obj, par) {
        //do something with object 'obj'
        if(par['isDebug'] === true) {
        console.log('Extra parameter provided: ' + par);
        console.log('The object to save: ' + JSON.stringify(obj));
      }
    }
  });

  obj = MVC.ModelView(viewId, { foo : 'bar' }, { controller : ctr });

  obj.Save({ 'isDebug' : true });

.Update(parameters)


Call the .Update() method whenever you want to update the object.
See the example for the .Save() method.


.Delete(parameters)


Call the .Delete() method whenever you want to delete the object.
See the example for the .Save() method.


._SetDataboundDomVal(viewId, property, value)


Use ._SetDataboundDomVal() to set the value of a databound element
The viewId should correspond with the datasrc attribute of the element to be updated.
The property should correspond with the name attribute of the element to be updated.

Example Use this method when updating a single value. E.g. when using keyup event for updating an element outside the view.

      var obj,
      viewId = '#testArea';
      $(function() {
      obj = MVC.ModelView(viewId, {
      name : 'Benjamin Hammer'
    }, {
    keyup: function(e, n, v) {
    //Update the input which has focus on the 'keyup'-event
    //Note: works only with 'input' elements (not e.g. select, radio)
    obj._SetDataboundDomVal(viewId, n, v);
  }
});
});



.SetModelFromView()


Updates the Model and databound elements with values from the View.


.SetViewFromModel()


Updates the elements in the View from the Model.


.GetViewData()


Returns the View data as an JSON object literal.


.AddGetSet(property)


Add getter and setter methods to the properties in the Model.
Note: Getter and setter methods only work when isMirror : true.


.RemoveGetSet(property)


Remove getter and setter methods from a property in the Model.
Note: Getter and setter methods only work when isMirror : true.