Selecting dynamically created models within a collection
-
12-12-2019 - |
Question
I have a set of "Person name" inputs with the class person
that I'm trying to do the following with: each time a keyup is recorded in the input, grab that input's data-hash attribute, and if there's not already an instance of Person with that hash in the collection People, add a model. Otherwise just update the model where hash matches.
$('.person').keyup(function(){
var myHash = $(this).attr('data-hash'),
myName = $(this).val(),
checkMe = people.where({'hash':myHash});
if ( checkMe.length > 0 ){
//update name value where hash matches
}
else {
people.add({
'name':myName,
'hash':myHash
});
}
});
Instead of using var person = new Person
I'm adding these models to the collection using Backbone's add
method.
So now I have a number of elements when I call people.models
but I can't figure out how to select them. Normally you'd say person.get('attribute')
but I'm not sure how to select the model if it has no var
name. What could I put in the code instead of //update name value where hash matches
?
Solution
checkMe should be an array of models you're trying to update. Iterate through them and use the set method:
$('.person').keyup(function(){
var myHash = $(this).attr('data-hash'),
myName = $(this).val(),
checkMe = people.where({'hash':myHash});
if ( checkMe.length > 0 ){
_.each(checkMe, function(person){
person.set({
'name':myName,
});
});
}
else {
people.add({
'name':myName,
'hash':myHash
});
}
});