ListView: sortByKey()
ListView
に取り付けられたコンテンツを特定のキーについて並べ替えます。
構文
listView.sortByKey(key, ascending = true) => this
引数
-
key
:string
ListView
に取り付けられたコンテンツの順序比較に使うプロパティ名です。プロパティ名はViewLogic
のcurateValues()
で取得したオブジェクトに含まれていなければなりません。 -
ascending
:boolean
昇順で並べ替えをするかどうかを示すフラグです。
true
なら昇順、false
なら降順で並べ替えを行います。既定ではtrue
が設定されます。
返値: this
対象の ListView
自身を返します。
例外
TypeError
key
が文字列でない場合ascending
がboolean
でない場合
例
const listVl = new class ListVl extends ViewLogic {
constructor() {
super();
this.loadContainer({
text: `<alier-list-view id="list"></alier-list-view>`,
id: "list",
});
this.relateElements(this.collectElements(this.container));
}
};
const archetype = new class ListItemVl extends ViewLogic {
constructor() {
super();
this.loadContainer({
text: `
<head><style>
.row {
--border-width: 2px;
display: grid;
grid-template: auto 1fr / repeat(2, 1fr);
}
.row:nth-child(3n) {
background-color: lightblue;
}
.row:nth-child(5n) {
border: var(--border-width) solid orange;
}
:not(.row:nth-child(5n)) {
padding: var(--border-width);
}
</style></head>
<body>
<div id="hello" class="row">
<span
id="word"
data-ui-component
data-primary="textContent"
></span>
<span
id="length"
data-ui-component
data-primary="textContent"
></span>
</div>
</body>
`,
id: "hello",
});
this.relateElements(this.collectElements(this.container));
}
};
const words = [
"Antelope", "Bear" , "Cat" , "Dog" , "Elephant",
"Falcon" , "Giraffe", "Hawk" , "Iguana" , "Jaguar" ,
"Kangaroo", "Lion" , "Moose" , "Narwhal", "Ostrich" ,
"Penguin" , "Quail" , "Rhinoceros", "Sloth" , "Tiger" ,
"Urchin" , "Vulture", "Wolf" , "Xerus" , "Yak" ,
"Zebra"
];
const prevVl = Alier.View.attach(listVl);
// listVl.container に archetype のコンストラクタ(ListItemVl)をテンプレートとして設定する
listVl.container.attach(archetype);
// listVl に ListItemVl から生成した要素を 10 個追加する
listVl.container.splice(0, 0, 10);
// words からランダムに単語を設定する(重複なし)
for (const item of listVl.container) {
const index = Math.floor(words.length * Math.random());
const word = words.splice(index, 1)[0];
item.reflectValues({ word, length: word.length });
}
// word について降順に並べ替えを行う
listVl.container.sortByKey("word", false);
解説
ListView
に取り付けられたコンテンツを、引数 key
に従って並べ替えます。