Javascript可以构建这个MVC模式或语法糖吗?

时间:2013-02-09 12:05:23

标签: javascript model-view-controller

我想要能够构建一个,基于继承的模式或语法糖,它不是一个大的框架。分类Ajax代码来维护MVC架构。

我希望它可以运行,例如示例代码,但我不知道Javascript可以做到这一点吗?

/* Just for demonstration architecture may be constructed with an object or function */
var Prototype = (){
    this.Controller = {/*...*/};
    this.Model = {/*...*/};
    this.View = {/*...*/};
    this.Constructor = function(){/* auto binding, like run this.Controller.update */};
    /*...*/
};

var a = new Prototype;  /* or $.extend, object.create, etc */

/* Create a function */
a.Controller.update = function(){
    $('#button').bind('click', function(){
        this.Model.update();    // Equivalent a.Model.update()
        this.Model.list();      // Equivalent a.Model.list()
        b.Model.del();          // Can call other instance of the function
    });
}
a.Model.update = function(){
    $.ajax('json source', function(data){
        this.View.update('json parse'); // Equivalent a.View.update()
    });
}
a.View.update = function(obj){
    /* Do something about the DOM */
}

/* Can be controlled by the other controller */
a.Model.list = function(){
    this.View.list('json parse');   // Equivalent a.View.list()
}
a.View.list = function(obj){
    /* Do something about the DOM */
}


var b = new Prototype;
b.Controller.del = function(){
    $('#del').bind('click', function(){
        this.Model.del();   // Equivalent b.Model.del()
    }
}
b.Model.del = function(){
    $.ajax('json source', function(data){
        this.View.del('json parse');    // Equivalent b.View.del()
    });
}
b.View.del = function(){
    /* Do something about the DOM */
}


a.Constructor();    //init
b.Constructor();

2 个答案:

答案 0 :(得分:0)

听起来像是在找JavaScriptMVC之类的东西。

我实际上在工作中使用它,它可以很好地保持不同的控制器分开。

我建议你在JavaScriptMVC下载中试用这个例子,看看它是不是你想要的。

答案 1 :(得分:0)

我创建了这个

//framework
var Jmvc = function BellaJMVC(){
    this.Controller = { };
    this.Model = function(uri, action, data){
        var self = this;
        $.ajax({ "type": "POST", "url": uri, "data": data, 
            "success": function(r){ self.View[action]($.parseJSON(r)); },
            "error": function(r){ /*...*/ }
        });
    };
    this.View = { };
    this.Init = function(){
        var fNOP = function () {};
        fNOP.prototype = this.prototype;
        for(var cAction in this.Controller){
            this.Controller[cAction].apply(this);
            this.Controller[cAction].prototype = new fNOP;
        }
    };
}

//apply
var a = new Jmvc();
a.Controller.update = function Cupdate(){
    var self = this;
    $('#updateBtn').bind('click', function(){
        self.Model('ajax/json.html', 'update', {"test":"1234"});
    });
}
a.View.update = function Vupdate(obj){
    $('#update').html(obj.msg);
}
a.Init();