通过MVC更新JS模型不会改变

时间:2018-10-06 07:38:09

标签: javascript model-view-controller

我有一个变量作为模型,我可以临时更改它,但是当尝试更新其他值时,它已在控制器中获取,但是当尝试重新呈现它时,它将显示新值并快速检索旧值,< / p>

我认为,updateCat函数中的问题也是我想传递的形式是对象,而不是每个值都单独作为更新名称和更新img。

谢谢。

/* ======= Model ======= */

var model = {
    currentCat: null,
    cats: [
        {
            clickCount: 0,
            name: 'Tabby',
            imgSrc: 'img/434164568_fea0ad4013_z.jpg',
            imgAttribution: 'https://www.flickr.com/photos/bigtallguy/434164568',
            isAdmin: 0
        },
        {
            clickCount: 0,
            name: 'Tiger',
            imgSrc: 'img/4154543904_6e2428c421_z.jpg',
            imgAttribution: 'https://www.flickr.com/photos/xshamx/4154543904',
            isAdmin: 0
        },
        {
            clickCount: 0,
            name: 'Scaredy',
            imgSrc: 'img/22252709_010df3379e_z.jpg',
            imgAttribution: 'https://www.flickr.com/photos/kpjas/22252709',
            isAdmin: 0
        },
        {
            clickCount: 0,
            name: 'Shadow',
            imgSrc: 'img/1413379559_412a540d29_z.jpg',
            imgAttribution: 'https://www.flickr.com/photos/malfet/1413379559',
            isAdmin: 0
        },
        {
            clickCount: 0,
            name: 'Sleepy',
            imgSrc: 'img/9648464288_2516b35537_z.jpg',
            imgAttribution: 'https://www.flickr.com/photos/onesharp/9648464288',
            isAdmin: 0
        }
    ]
};


/* ======= Octopus ======= */

var octopus = {

    init: function () {
        // set our current cat to the first one in the list
        model.currentCat = model.cats[0];

        // tell our views to initialize
        catViewList.init();
        catView.init();
    },

    getCurrentCat: function () {
        return model.currentCat;
    },

    getCats: function () {
        return model.cats;
    },

    // set the currently-selected cat to the object passed in
    setCurrentCat: function (cat) {
        model.currentCat = cat;
    },

    // increments the counter for the currently-selected cat
    incrementCounter: function () {
        model.currentCat.clickCount++;
        catView.render();
    },

    // Admin mode, to edit exist cat (name, url)
    showAdminForm: function () {
        model.currentCat.isAdmin = 1;
        catView.render();
    },

    updateCat: function (name, img) {
        console.log(name + " ----- " + img + " before currentCat " + model.currentCat.name);
        model.currentCat.name = name;
        model.currentCat.imgSrc = img;

        catView.render();
    }
};


/* ======= View ======= */
var catView = {

    init: function () {
        // POINTERS
        this.catElem = document.getElementById('cat-div');
        this.catNameElem = document.getElementById('cat-name');
        this.catCounter = document.getElementById('cat-counter');
        this.catImage = document.getElementById('cat-image');
        this.isAdmin = document.getElementById('show-admin');
        this.adminPanel = document.getElementById('admin-panel');
        this.newName = document.getElementById('updated-name');
        this.newImg = document.getElementById('updated-name');

        this.isAdmin.addEventListener('click', function () {
            octopus.showAdminForm();
        });

        this.catImage.addEventListener('click', function () {
            // Get count from octopus
            octopus.incrementCounter();
        });
        this.render();
    },

    render: function () {

        // Empty the form
        // this.isAdmin.innerHTML = '';

        // update the DOM elements with values from the current cat         
        var currentCat = octopus.getCurrentCat();
        this.catCounter.textContent = currentCat.clickCount;
        this.catNameElem.textContent = currentCat.name;
        this.catImage.src = currentCat.imgSrc;
        this.isAdmin = currentCat.isAdmin;
        this.newName.textContent = currentCat.name;
        this.newImg.src = currentCat.imgSrc;

        this.adminPanel.addEventListener('submit', function() {
            var updatedName = document.getElementById("updated-name").value;
            var updatedImg = document.getElementById("updated-img").value;


            // document.getElementById('cat-name') = updatedName;

            
            octopus.updateCat(updatedName, updatedImg);
            // catView.render();
        });
        

        if (this.isAdmin == 1) {
            this.adminPanel.style.display = "block";
            // problem here when changed and re render it fetched old name
            // this.adminPanel.addEventListener('submit', function() {
            //     var updatedName = document.getElementById("updated-name").value;
            //     var updatedImg = document.getElementById("updated-img").value;

            //     console.log(updatedName + updatedImg);

            //     // document.getElementById('cat-name') = updatedName;

                
            //     octopus.updateCat(updatedName, updatedImg);
            //     // catView.render();
            // });
        } else {
            this.adminPanel.style.display = "none";
        }


    }
};


var catViewList = {

    init: function () {
        // store the DOM element for easy access later
        this.catListElem = document.getElementById('side_nav_item');

        // render this view (update the DOM elements with the right values)
        this.render();
    },

    render: function () {
        var cat, elem, i;
        // get the cats we'll be rendering from the octopus
        var cats = octopus.getCats();

        // empty the cat list
        this.catListElem.innerHTML = '';

        // loop over the cats
        for (i = 0; i < cats.length; i++) {
            // this is the cat we're currently looping over
            cat = cats[i];

            // make a new cat list item and set its text
            elem = document.createElement('a');
            elem.textContent = cat.name;

            // on click, setCurrentCat and render the catView
            // (this uses our closure-in-a-loop trick to connect the value
            //  of the cat variable to the click event function)
            elem.addEventListener('click', (function (catCopy) {
                return function () {
                    octopus.setCurrentCat(catCopy);
                    catView.render();
                };
            })(cat));

            // finally, add the element to the list
            this.catListElem.appendChild(elem);
        }
    }
};



octopus.init();
<!DOCTYPE html>
<html lang="en">

<head>
    <link href="css/main.css" rel="stylesheet">
    <!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> -->
    <title>Cat List </title>
</head>

<body>
    <div class="main">
        <div id="side_nav" class="sidenav" >
            <li id="side_nav_item" class="side_nav_item"></li>
        </div>

        <div id="cat-div">
            <h2 id="cat-name"></h2>
            <div id="cat-counter"></div>
            <img id="cat-image" src="" alt="cute cat">
        </div>

        <button id="show-admin">Admin</button>

        <form id="admin-panel">
            <label >Name :</label> 
            <input type="text" id="updated-name">
            <label>Img url :</label>
            <input type="text" id="updated-img">

            <button id="updateCat" type="submit">Save</button>
        </form>
        
        <script src="js/model.js"></script>
    </div>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

我找到了解决我愚蠢问题的方法,

this.adminPanel.addEventListener('submit', function(evt) {
        var nameToChange = document.getElementById('updated-name').value;
        var imgTOChange = document.getElementById('updated-img').value;
        console.log(nameToChange + imgTOChange);
        octopus.updateCat(nameToChange + imgTOChange);
        evt.preventDefault();   // Here is the trick

    });

关闭。

谢谢。