Backbone.js Tratamento de atributos que são matrizes
Gosto muito do Backbone, mas estou com dificuldades para fazer o que parece ser coisas simples. Agradeço qualquer ajuda com o exemplo a seguir.
Eu tenho um modelo, Critérios, que quero usar para armazenar o estado de alguns itens na minha interface do usuário. existem alguns atributos simples e um atributo que é uma matriz de IDs usados para armazenar os IDs de tags que o usuário selecionou na interface do usuário.
Então, eu crio uma nova instância. Eu adiciono alguns itens à matriz de tags. Então, quero começar de novo, criar uma nova instância, atribuída à mesma variável. Porém, minha matriz de tags continua mantendo as informações adicionadas a ela como parte da primeira instância de Critérios.
Documentei o caso de teste abaix
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<script src="Scripts/Libraries/jquery-1.6.1.js" type="text/javascript"></script>
<script src="Scripts/Libraries/underscore.js" type="text/javascript"></script>
<script src="Scripts/Libraries/backbone.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(function () {
// Simple model to hold some state about my UI.
var Criteria = Backbone.Model.extend({
defaults: {
"status": "Normal",
"priority": "Normal",
"tags": new Array()
}
});
// Create new criteria.
window.criteria = new Criteria();
// The length of the tags array should be 0. PASSES
console.log("Expect 0: Actual " + window.criteria.get("tags").length);
// Add a tag id to the tags array.
window.criteria.get("tags").push(5); // Tag with ID of 5.
// The length of the tags array should be 1. PASSES
console.log("Expect 1: Actual " + window.criteria.get("tags").length);
// Create a new instance of criteria.
window.criteria = new Criteria();
// The length of the tags array should be 0. FAILS
// CONFUSED. I thought this is now a new instance with a new set of attributes.
// Why does the tags collection still have an item in it.
console.log("Expect 0: Actual " + window.criteria.get("tags").length);
// OK. So, I will call the clear method on the model. This is supposed to remove all attributes
// from the model.
// Then, I will create it again.
window.criteria.clear();
window.criteria = new Criteria();
// The length of the tags array should be 0. FAILS. Still 1.
console.log("Expect 0: Actual " + window.criteria.get("tags").length);
// ARGH!
console.log("HELP!");
});
</script>
</head>
<body>
<h1>Test</h1>
<p>Backbone test page.</p>
</body>
</html>
Estou apenas fora da marca aqui? Estou tentando usar o Backbone para coisas que não foram planejadas? Ou estou faltando algo mais geral na programação OO de javascript?
P.S. Originalmente, usei uma coleção de tags do Backbone, mas que apresentava um conjunto totalmente diferente de problemas relacionados à referência de um modelo de tags em várias coleções e como o método de remoção do Backbone desativa a referência de "coleção" quando um item é removido de qualquer coleção. Outro dia, outro problema.