MVC中简单数据模型(M): Model类

读书笔记:

基于mvc的javascript web富媒体应用开发,
模型和数据
Model类
 
//新建类的函数Object.create,ECMAScript5已经实现
if(typeof Object.create !== 'function'){
 Object.create = function(o){
  function F(){};
  F.prototype = o;
  return new F();
 };
}

//模型
var Model = {
 inherited: function(){},
 created: function(){},
 prototype:{//用于模型实例继承用
  init: function(a){
   console.log(22);
   this.name = 'Model.name'
  }
 },
 //创建模型
 create: function(){
  var o = Object.create(this);
  o.parent = this;
  o.prototype = o.fn = Object.create(this.prototype);//Model.prototype.init
  o.created();
  this.inherited();
  return o;
 },
 //创建模型实例
 init: function(){
  //console.log(this);
  //console.log(this.prototype);//Model.prototype.init
  var instance = Object.create(this.prototype);
  instance.parent = this;
  instance.init.apply(instance, arguments);
  return instance;
 },
 //扩展模型方法
 extend: function(o){
  var extended = o.extended;
  jQuery.extend(this, o);
  if(extended) extended(this);
 },
 //扩展模型实例方法
 include: function(o){
  var included = o.included;
  jQuery.extend(this.prototype, o);
  if(included) includeed(this);
 }
};

//扩展模型find方法
Model.extend({
 find: function(){}
});
//扩展模型实例init方法,会覆盖Model.prototype.init方法

//并扩展load方法
Model.include({
 init: function(attr){
  if(attr) this.load(attr);
 },
 load: function(attributes){
  for(var name in attributes){
   this[name] = attributes[name];
  }
 }
});
//扩展模型属性
Model.records = {};
//扩展模型实例: create,destroy方法及newRecord属性
Model.include({
 newRecord: true,
 create: function(){
  this.newRecord = false;
  this.parent.records[this.id] = this;
 },
 destroy: function(){
  delete this.parent.records[this.id];
 }
});
//扩展模型实例: update方法
Model.include({
 update: function(){
  this.parent.records[this.id] = this;
 }
});
//扩展模型实例: save方法用以实现兼容更新与创建
Model.include({
 save: function(){
  this.newRecord ? this.create() : this.update();
 }
});
//扩展模型方法用于查找记录
Model.extend({
 find: function(id){
  return this.records[id] || 'Unkonw record';
 }
});

使用数据模型创建,保存,查找

var Asset = Model.create();//创建模模型
var asset = Asset.init();//创建数据模型实例1
asset.name = "same, same";
asset.id = 1;
asset.save();
var asset2 = Asset.init();//创建数据模型实例2

asset2.name = "but different";
asset2.id = 2;
asset2.save();
asset2.destroy();
console.log(Asset.find(2));

 

posted @ 2013-01-28 20:15  池中物王二狗  阅读(316)  评论(0编辑  收藏  举报
转载入注明博客园 王二狗Sheldon Email: willian12345@126.com https://github.com/willian12345