LoginSignup
1
0

More than 3 years have passed since last update.

Backbone.js - コレクション (Ajax)

Last updated at Posted at 2020-02-15

概要

Backbone.jsのコレクションでAjax通信してリストを動的に取得してみる。

ローカル環境整備

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

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

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

Ajax通信の準備

Collectionで扱うデータをAjaxで非同期通信にて取得するため、jsonファイルを準備する。

./src/html/api/users.json
[
  {"country": "日本", "prefecture": "東京都", "name": "太郎", "age": "30"},
  {"country": "日本", "prefecture": "大阪府", "name": "次郎", "age": "28"},
  {"country": "日本", "prefecture": "愛知県", "name": "花子", "age": "25"},
  {"country": "日本", "prefecture": "福岡県", "name": "三郎", "age": "15"},
  {"country": "日本", "prefecture": "東京都", "name": "四郎", "age": "25"}
]

サンプルコード

Ajaxで動的にデータを取得するCollectionを作成してみました。
※ データの取得先: GET http://localhost:8080/api/users.json

./src/html/collection1.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>Backbone.js学習 [Collection]</title>
</head>
<body>
    <h1>Collection</h1>
    <p>CollectionでAjax通信して動的にデータを取得する</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,
            url: '/api/users.json',
            parse: function(response){
                console.log(response);
                return response;
            }
        });
        const users = new Users();
        users.fetch().done(function(users){
            $.each(users, function(index, user){
                console.log(index, user);
            });
        });
    </script>
</body>
</html>

動作確認

正常にデータが取得できたようです。
sample.png

参考サイト

1
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
1
0