0

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.

4

1 回答 1

1

基本上 MVC 是基于观察者模式(控制器也是)

如何在 Javascript 中实现 Observer?

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);
                }
            }
        }
    }
}

以及如何使用它?

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

希望这可以帮助你..

于 2012-07-17T17:47:56.603 回答