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));
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述