简体   繁体   中英

rv-each - prevent remove on data change

How could I modify the rv-reach binding so that new and changed array items are added to the dom, but removed array items not removed from the dom?

new array item > add item to dom

changed array item > change item in the dom

removed array item > do nothing

You simply have to keep it in the array to not remove it from the dom.

What you actually want to achieve is a so called "soft delete" to achieve that, you have to add a property: removed to the item, which is set default to 0 , then based on that value, you can either hide the item, give it a red color etc.. while it will still be shown in the dom.

So this is how i would do this to give you an example of how it will work:

var App = {} // this wraps everything up.
App.items = [] // collection of items

// example item model
App.item = new function(data){
    var _self;
    this.data = data || {};
    this.defaults = {
        removed:0
    }

    // set default values where needed if not set
    for (x in this.defaults) { 
        if(!this.data.hasOwnProperty(x)){
            this.data[x] = this.defaults[x];
        }
    }

    this.remove = function(){
        _self.data.removed = 1;
        // ajax request to set current item to removed...    
        // but dont remove it from the array so it stays in the dom
    }
    _self = this;       
}
rivets.bind($('#app'),{app:App});

then if you want to add items:

items.push(new item({name:'my newest item'}); // new item gets added to the dom

if you want to remove items for example:

eventually add some classes when the item is removed:

rv-class-danger="item.data.removed | eq 1" // adds the class danger

<div id="app">
    <div rv-each-item="app.items" rv-class-danger="item.data.removed | eq 1">
        {{ item.data.name }}
        <!-- when the button is clicked, this will trigger the remove function on the item it belongs to. -->
        <button rv-on-click="item.remove">remove</button>
    </div>
</div>

So whenever you change any data, it wil change in the dom also, when you remove the item, it just sets property removed of the item to 1 so you can keep it in the dom this way. And when you add an item, you just have to push it into the array and it will be added to the dom.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM