简体   繁体   中英

How can I remove a specific element from my array generated by a blaze helper?

I have a helper class that pushes an element into an array when a checkbox is checked and should remove the element when it is unchecked. I am able to successfully push the element to the array but having trouble removing it.

I am noticing some curious behavior. For instance, unchecking the element also pushes it to the array making a duplicated of it instead of removing it from the array. If I console log the index value, I get -1 for each array element that I'm trying to remove.

Here is the Blaze Code:

Template.Job_setup_page.onCreated(function homePageOnCreated() {

    this.checkedJobs = [];

});

Template.Job_setup_page.events({
    'click .filled-in'(event, instance) {
        var currentId = event.target.id;

        if($(".filled-in").is(':checked')){
            instance.checkedJobs.push({
                instruction: currentId,
                quantity: 1
            })
        }
        else {
            var index = instance.checkedJobs.indexOf(currentId);
            instance.checkedJobs.splice(index, 1);
            console.log("This is the current Id", currentId);
            console.log("this is the index", index);
        };
    },
});

indexOf searches for an element itself and will not be able to match an object by its instruction property. You should instead use a for-loop to iterate over your checkedJobs array and compare each instruction to currentId in order to find the correct index. Replace the contents of your else block with the following:

var jobs = instance.checkedJobs
for (var i = 0; i < jobs.length; i++) {
  if (jobs[i].instruction === currentId) {
    instance.checkedJobs.splice(i, 1)
    console.log('currentId:', currentId)
    console.log('index:', i)
  }
}

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