Despite I have been using MVC in PHP many times, I found out that it is quite different in Javascript. I’m reading MVC in Javascript over the web, but many of them have a different implementation. I came up with a simple MVC, but I think this is not correct. Is this acceptable or completely wrong?
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 listens to changes in the model and assigns events to html anchors. View calls the controller when the anchors are clicked then controller updates the model.
This is classic 1979-type MVC:
PHP/Rails (web request/response in general) is a slightly different type of MVC (constricted by the request/response nature of the web):
In both types, view events trigger controller actions.