Reputation: 329
I want to implement MVC pattern in JavaScript, but I have a problem with Controller implementation.
MVC concepts are clear to me. I understand how MVC works. I don't think that events is appropriate way build a Controller. And there are a lot of dependences because of edition of the event in JavaScript. I would like to see some small example of implementation of MVC Controller in JavaScript.
p.s. I want to implement MVC pattern by using only JavaScript, but I don't want to use any MVC open-source frameworks.
p.s. I don't want you to do my homework, but I really don't understand how to imprelent Controller in JavaScript.
Upvotes: 0
Views: 563
Reputation: 3750
basicly MVC is based apon the Observer pattern (and controller is also)
How you can implement Observer inside of Javascript?
function Observer() {
var subscribers = [];
return {
subscribe: function(eventName, object) {
subscribers.push({ event: eventName, target: object });
},
unsubscribe: function(object) {
var indexToDelete = subscribers.indexOf(object);
subscribers.splice(indexToDelete, 1);
},
trigger: function(eventName, p1, p2, p3, p4, p5) {
for (var i = 0; i < subscribers.lenght; i++) {
if (subscribers[i].event == eventName) {
//target object must implement this function
subscribers[i].target[eventName](p1, p2, p3, p4, p5);
}
}
}
}
}
And how you can use it?
var model = {
fireChangesInsideOfModel: function(p1){
//do some model update logic here
}
}
var controller = Observer();
controller.subscribe("fireChangesInsideOfModel", model);
controller.trigger("fireChangesInsideOfModel", 11231); // 11231 - is an example of a parameter
Hope this helps you..
Upvotes: 1