자체 제작 MVC의 M

9214 단어 mvc
/**

 * @ 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'})

좋은 웹페이지 즐겨찾기