自己构建MVC中的M

/**
 * @ description Model MVC中M 数据模型
 * @ Object
 * @ public
 * @ create method IE不支持
 */

if(typeof Object.create !== 'function'){
    Object.create = function(o){
        function F(){}
        F.prototype = o;
        return new F()
    }
}

Math.guid = function(){
    return 'xxxxxxxx-xxxx-4yxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c){
        var v = Math.random()*16|0,
            c = c == 'x' ? v : (v & 0x8),
            c = c.toString(16);
        return c.toUpperCase() 
    })
}

var Model = {
    created : function(){
        
    },
    
    prototype : {
        init: function(){
            console.log('prototype.init')
        }
    },

    extend : function(o){
        for(var i in o){
            this[i] = o[i]
        }
    },

    include : function(o){
        for(var i in o){
            this.prototype[i] = o[i]
        }
    },

    create : function(){
        var object = Object.create(this);//object 继承 Model
        object.parent = this;
        object.prototype = object.fn = Object.create(this.prototype) // object.prototype 继承 Model.prototype
        object.created();
        return object
    },

    init : function(){
        var instance = Object.create(this.prototype);
        instance.parent = this;
        instance.init.apply(instance,arguments);
        return instance;
    }
}

/*
    *Object 存储实例对象 
 */


Model.records = {};


var Asset = Model.create();


Model.include({
    init : function(attr){
        if(attr){
            this.load(attr)
        }
    },
    load : function(attr){
        for(var i in attr){
            this[i] = attr[i]
        }
    }
})

Model.include({
    newRecords : true,

    create : function(){
        this.newRecords = false;
        this.id = this.id || Math.guid();
        this.parent.records[this.id] = this.dup();
    },

    destroy : function(){
        delete this.parent.records[this.id]
    },

    updata : function(){
        this.parent.records[this.id] = this.dup();
    },

    save : function(){
        this.newRecords ? this.create() : this.updata()
    },

    dup : function(){
        var o = {};
        for(var i in this){
            o[i] = this[i]
        }
        return o;
    } 

})


Model.extend({
    find : function(id){
        var record = this.records[id]
        if(!record) throw('no you need object')
        return record.dup()
    },

    created : function(){
        this.record = {}
    }
})

Model.extend({
    populate : function(values){
        this.records = {};
        for(var i = 0, len = values.length; i < len; i++){
            var record = this.init(values[i]);
            record.newRecords = false;
            record.id = record.id || Math.guid();
            this.records[record.id] = record;
        }
    }
})


var asset = Asset.init({name : 'xiaohui108'})

 

posted @ 2015-01-26 00:12  xiaoxiaohui  阅读(257)  评论(0编辑  收藏  举报