私は本当にバックボーンが好きですが、単純なものと思われるようなことをするのが最も難しい時です。私は次の例の助けを感謝します。Backbone.js配列の属性の処理
私は、私のUIにいくつかの項目の状態を保存するために使用するモデル、Criteriaを持っています。いくつかの単純な属性と、ユーザーがUIで選択したタグのIDを格納するために使用されるIDの配列である1つの属性があります。
したがって、私は新しいインスタンスを作成します。タグ配列にいくつかの項目を追加します。次に、同じ変数に割り当てられた、新しいインスタンスを作成し直したいと思います。しかし、私のタグ配列は、それが私が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>
私はちょうどここのマークオフですか?バックボーンを意図せずに使用しようとしていますか?または、私はJavaScriptのオブジェクト指向プログラミングでもっと一般的なものを見逃していますか?
P.S.もともと私は、タグのバックボーンコレクションを使用していましたが、それは、複数のコレクションで参照されるタグモデルと、アイテムがコレクションから削除されたときに、バックボーンのremoveメソッドが "コレクション"リファレンスをどのように設定解除するかに関する、別の日、別の問題。
こんにちはKevin、おそらくあなたはあなたの受け入れられた答えをその下のものに変更することができますか?これははるかに読みやすく、推奨されるアプローチです。受け入れられた答えは、とにかく同じものの膨張したアイデアだけです。ありがとう。 – SuperDuperApps