【发布时间】:2011-06-22 01:06:34
【问题描述】:
我真的很喜欢 Backbone,但我在做看似简单的事情时却遇到了困难。感谢您对以下示例的任何帮助。
我有一个模型 Criteria,我想用它来存储 UI 中某些项目的状态。有几个简单的属性,一个属性是一组 ID,用于存储用户在 UI 中选择的标签的 ID。
所以,我创建了一个新实例。我在标签数组中添加了一些项目。然后,我想重新开始,创建一个新实例,分配给同一个变量。但是,我的 tags 数组继续保存我作为第一个 Criteria 实例添加到其中的信息。
我已经记录了下面的测试用例。
<!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>
我是不是有点离题了?我是否试图将 Backbone 用于非预期的事情?还是我在 javascript OO 编程中遗漏了一些更通用的东西?
附:我最初使用了一个 Backbone 的标签集合,但它提出了一组完全不同的问题,这些问题与在多个集合中引用标签模型有关,以及当从任何集合中删除项目时,Backbone 的 remove 方法如何取消设置“集合”引用。改天,另一个问题。
【问题讨论】:
-
嗨,凯文,也许您可以将您接受的答案更改为下面的答案?这是更清晰和推荐的方法。无论如何,公认的答案只是对同一件事的夸大其词。谢谢。