【发布时间】:2012-02-10 18:06:05
【问题描述】:
尽管我在 PHP 中多次使用 MVC,但我发现它在 Javascript 中完全不同。我正在网上阅读 Javascript 中的 MVC,但其中许多都有不同的实现。我想出了一个简单的 MVC,但我认为这是不正确的。这是可以接受的还是完全错误的?
var AppView = View.extend({
init: function()
{
// listen to Model changes
this.listen("counterChanged", $.proxy( this.updateCounter, this ));
// assign click event; call controller method
this.container.find("#increase").click( this.callback( this.Controller, "increase" ));
this.container.find("#decrease").click( this.callback( this.Controller, "decrease" ));
},
updateCounter: function( evtData )
{
this.container.find("#counter").html( evtData.newValue );
}
});
var AppController = Controller.extend({
increase: function()
{
this.Model.update("counter", this.Model.get('counter') + 1 );
},
decrease: function()
{
this.Model.update("counter", this.Model.get('counter') - 1 );
}
});
var AppModel = Model.extend({
onUpdate_counter: function( newValue )
{
this.fireEvent("counterChanged",{
newValue: newValue
})
}
});
var App = {}
$(document).ready(function(){
App.Model = new AppModel({
counter: 0
});
App.Controller = new AppController( App.Model );
App.View = new AppView("#app", App.Controller );
App.Model.setView( App.View );
});
HTML:
<div id='app'>
<div id='counter'>0</div>
<a id='increase'>Increae</a>
<a id='decrease'>Decrease</a>
</div>
View 监听模型中的变化并将事件分配给 html 锚点。 View 在单击锚点时调用控制器,然后控制器更新模型。
【问题讨论】:
标签: javascript model-view-controller design-patterns