2013-02-09 50 views
0

我想問一下能夠建立一個,基於繼承的模式或語法糖,它不是一個大框架。分類Ajax代碼來維護MVC架構。Javascript可以架構這個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(); 

回答

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(); 
0

聽起來像我一樣,你正在尋找像JavaScriptMVC

我實際上在工作中使用它,它能夠非常好地保持您的不同控制器分離。

我建議你嘗試一下JavaScriptMVC下載的例子,看看它是你在找什麼。

+0

親愛的山姆 我會試試,謝謝 – 2013-02-09 12:20:54