实现一个MVC模型

110 阅读1分钟

“我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第3篇文章,点击查看活动详情

本文已参与「新人创作礼」活动,一起开启掘进创作之路。

let myapp = {} // 创建这个应用对象

// modal
myapp.Modal = function(){
    let val = 0
    this.add = function(v){
        if (val < 100) val += v
    }
    this.sub = function(v){
        if (val > 0) val -= v
    }
    this.getVal = fucntion(){
        return val
    }
    // 观察者模式
    let views = []
    let self = this
    this.register = fucntion(view){
        views.push(view)
    }
    this.notify = function(){
        for(let i = 0; i < views.length; i++) {
            views[i].render(self)
        }
    }
}

// view
myapp.View = function(controller){
    let $num = $('#num')
    let $incBtn = $('#increase')
    let $decBtn = $('#decrease')
    this.render = function(modal) {
        $num.text(modal.getVal() + 'rmb')
    }
    // 绑定事件
    $incBtn.click(controller.increase)
    $decBtn.click(controller.decrease)
}

// controller
myapp.controller = function(){
    let modal = null
    let view = null
    this.init = function(){
        // 初始化modal和view
        modal = new myapp.Modal()
        view = new myapp.View(this)
        // view向modal注册,当modal更新就会去通知view
        modal.register(view)
        modal.notify()
    }
    
    // modal更新数据并通知view更新视图
    this.increase = function () {
        modal.add(1)
        modal.notify()
    }
    this.decrease = function() {
        modal.sub(1)
        modal.notify()
    ]
}

// init
(function(){
    let controller = new myapp.controller()
    controller.init()
})()