Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@reflet

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

More than 1 year has passed since last update.

概要

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

参考サイト

0
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
reflet

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?