2012-10-01 41 views
0

我有一組與類person,我試圖做「人名」的投入與以下幾點:每次KEYUP被記錄在輸入時間,搶輸入的數據 - 散列屬性,並且如果People集合中還沒有具有該散列的Person實例,請添加一個模型。否則,只需更新散列匹配的模型。選擇一個集合中動態創建的模型

$('.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 
    }); 
} 
}); 

而不是使用var person = new Person的我加入這些模型來使用骨幹add方法集合。

所以現在我有一個數量的元素,當我打電話people.models但我無法弄清楚如何選擇它們。通常你會說person.get('attribute'),但我不知道如何選擇模型,如果它沒有var名稱。我可以放入代碼而不是//update name value where hash matches

回答

1

checkMe應該是你想更新模型的數組。迭代通過它們,並使用設置方法:

$('.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 
    }); 
} 
}); 
+0

謝謝 - 這種方法爲我工作。 –

相關問題