[Backbone]6. Collections.

本文介绍如何使用Backbone.js创建一个管理预约集合的实例,包括如何初始化集合、加载JSON数据、从服务器获取数据、监听集合变化以及优化数据加载体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Define a collection:

var AppointmentList = Backbone.Collection.extend({model: Appointment});

RESET the json:

var appointments = new AppointmentList();
var json = [
  {title: 'Back pain'},
  {title: 'Dry mouth'},
  {title: 'Headache'} 
];
appointments.reset(json);

 Get url and fetch json data:

var AppointmentList = Backbone.Collection.extend({
  url: '/appointments',
  model: Appointment
});
var appointments = new AppointmentList();

appointments.fetch();

This Dr. Goodparts does not trust us when we tell him we are successfully loading data from the server into our collection.

To prove him wrong, display an alert with the number of items in the collection by listening for the reset event.

var appointments = new AppointmentList();
appointments.fetch();
appointments.on('reset', function(){
    alert(appointments.length);
});

Wouldn't ya know, our users don't like getting alerts every time we fetch new data for our collection.

Update the fetch call below to not fire the reset event.

//By default, when fetch or add model, the reset event will be triggered.
//TO disable the reset event, can use 
appointments.fetch({silent: true});

Use an event listener to log to the console the model's title anytime a model is added to the appointments collection.

var appointments = new AppointmentList();
appointments.on('add', function(appointment){
    console.log(appointment.get('title'));
});

There are a lot of appointments in our collection and Dr. Goodparts wants a list of all appointment titles so he can arrange his equipment for the day.

Use the map iteration function to return an array of appointment titles and assign to the titles variable.

var titles = new Array();
appointments.map(function(appoinment){
    titles.push(appoinment.get('title'));
});

 

转载于:https://www.cnblogs.com/Answer1215/p/3887500.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值