LoginSignup
0
0

More than 3 years have passed since last update.

Backbone.js - コレクション

Last updated at Posted at 2020-02-15

概要

Collectionで任意のリストを作り操作してみる

ローカル環境準備

dockerでnginxを起動して環境を整える。

ターミナル
$ docker-compose build
$ docker-compose up -d

※ 学習ように作ったコードはgithubにアップしています
https://github.com/reflet/sample-backbone.js

サンプルコード

Ajax通信などせず、任意にリストを生成して制御してみる。

./src/html/collection2.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>Backbone.js学習 [Collection]</title>
</head>
<body>
    <h1>Collection</h1>
    <p>Collectionを使ってみる</p>

    <script src="https://cdn.jsdelivr.net/npm/underscore@1.9.1/underscore.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/jquery/jquery@3.4.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/backbone@1.4.0/backbone.min.js"></script>
    <script>
        // Model
        const Person = Backbone.Model.extend({
            defaults: {
                country: '日本',
                prefecture: '東京',
                name: '',
                age: null,
            }
        });

        // Collection
        const Users = Backbone.Collection.extend({model: Person});
        const users = new Users();
        users.add({name:'次郎', age:28});
        users.add({name:'花子', age:25, prefecture:'大阪'});
        users.add({name:'三郎', age:32});
        users.add({name:'田中', age:25, prefecture:'名古屋'});
        console.log('dump1', users.toJSON());

        // 名前だけ取得する
        console.log(users.pluck('name'));

        // 全件取得する
        users.each(function(user) {
            console.log(user.toJSON());
        });

        // 年齢が25歳のユーザーのみ取得する
        $.each(users.where({age:25}), function(e,user) {
            console.log(user.toJSON());
        });

        // 最後のデータ要素を削除する
        users.pop();
        console.log('dump2', users.toJSON());

        // 指定した要素を削除する
        users.remove(users.at(1)); // 2番目
        console.log('dump3', users.toJSON());

        //すべてのデータを削除する
        users.reset();
        console.log('dump4', users.toJSON());
    </script>
</body>
</html>

動作確認

正常に処理できているようです。
sample.png

まとめ

1つのデータは、Modelで取り扱い、データの集合としてCollectionがあるといった感じで
割とシンプルな構成でわかりやすいですね。

参考サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0