Remove Item from Array in Meteor.js
javascript, meteor
Solution
Assuming your `Rulesets.rules` array is an array of objects like :
Rulesets : { { title: 'title1',
rules : [ {name : 'rule1', description : 'description1'},
{name : 'rule2', description : 'description2'}
]
},
{ title: 'title2',
rules : [ {name : 'rule1', description : 'description1'},
{name : 'rule2', description : 'description2'}
]
} }
First, in your `rulesetSingle` template, you must assign the `_id` of that particular document to the `<a>` like :
`<a href="#" name="{{../_id}}"class="rule-delete-btn"> x </a>`
Second thing, you are trying to remove rule entry using `Array.splice()`, this is not possible since the `rules` is a document inside the collection. You must do `update` query as `Rulesets.update()`.
If you have done `allow update` on the server, you can delete this array entry from within the event handler, otherwise you must do `Meteor.call()` by passing `rule` an the `_id` of parent document.
So, the event handler will look something like :
'click .rule-delete-btn': function(e) {
e.preventDefault();
var rule = this;
var id = e.currentTarget.name;
Meteor.call('removeRule', id, rule);
}
On the server:
Meteor.methods({
removeRule: function(id, rule){
Rulesets.update({_id: id}, {$pull : {rules : rule}});
}
});
Problem
I have a collection called Rulesets - each ruleset has an array of "rules". I have the following html which displays each ruleset and each rule: ``` <template name="rulesets"> {{#each rulesets}} {{>rulesetSingle}} {{/each}} </template> <template name="rulesetSingle"> {{#each rules}} <p class="rule-description">{{this}} <a href="#" class="rule-delete-btn">x</a> </p> {{/each}} </template> ``` I want to be able to remove the rule when the user clicks the "rule-delete-btn". I have the following javascript to do this: ``` Template.rulesetSingle.event({ 'click .rule-delete-btn': function(e){ e.preventDefault(); var array = Rulesets.rules; var index = array.indexOf(this); array.splice(index, 1); } }); ``` The delete isn't working because the "array" declaration isn't pulling a valid array. How can I find and store the array that contains "this" which is the current rule that needs to be deleted?