ListView: sort()
ListView
に取り付けられたコンテンツを並べ替えます。
構文
listView.sort(compare) => this
引数
-
compare
:((object, object) => (-1 | 0 | 1))?
ListView
に取り付けられたコンテンツからcurateValues()
で取得したオブジェクトを比較する関数です。この関数は、第 1 引数が第 2 引数より小さいなら負の数, 等しいなら0
, より大きいなら正の数を関数でなければなりません。この関数が与えられなかった場合、代わりに既定の比較関数が使用されます。既定の比較関数は、列挙可能な同名プロパティの値を順に比較し、同値でないプロパティが見つかったらその順序(負または正の数)を返し、すべてのプロパティが同値なら0
を返します。
返値: this
対象の ListView
自身を返します。
例外
TypeError
compare
がundefined
またはfunction
のいずれでもない場合
例
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 });
}
// length について昇順に並べ替え、また、同列の中で word について昇順に並べ替える
listVl.container.sort((x, y) => {
const xWd = x.word;
const xLen = Number(x.length);
const yWd = y.word;
const yLen = Number(y.length);
const lenOrder = (xLen > y_len) - (xLen < yLen);
return (
lenOrder
+ (lenOrder === 0) * ((xWd > yWd) - (xWd < yWd))
);
});
解説
ListView
に取り付けられたコンテンツを、引数 compare
に従って並べ替えます。