如何在 Backbone 中获取单个模型? [英] How do I fetch a single model in Backbone?

查看:25
本文介绍了如何在 Backbone 中获取单个模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Backbone 中有一个 Clock 模型:

I have a Clock model in Backbone:

var Clock = Backbone.Model.extend({});

我正在尝试从 /clocks/123 获取具有最新信息的实例.我尝试过的一些事情:

I'm trying to get an instance of that that has the latest information from /clocks/123. Some things I've tried:

Clock.fetch(123)
// TypeError: Object function (){ ... } has no method 'fetch'

创建一个实例,然后对其调用fetch:

c = new Clock({id: 123})
c.fetch()
// Error: A 'url' property or function must be specified

一个集合

我尝试创建一个 AllClocks 集合资源(即使我在页面上没有使用这样的东西):

a collection

I tried creating an AllClocks collection resource (even though I have no use for such a thing on the page):

var AllClocks = Backbone.Collection.extend({
  model: Clock,
  url: '/clocks/'
});
var allClocks = new AllClocks();
allClocks.fetch(123);
// returns everything from /clocks/

我如何获得一个 API 支持的时钟?

How do I just get one API-backed Clock?

推荐答案

您的第二种方法是我使用过的方法.尝试将以下内容添加到您的时钟模型中:

Your second approach is the approach I have used. Try adding the following to your Clock model:

url : function() {
  var base = 'clocks';
  if (this.isNew()) return base;
  return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
},

这种方法假设您已经在 URL 中实现了带有 hashbang 的控制器,如下所示,http://www.mydomain.com/#clocks/123 ,但即使您还没有,它也应该可以使用.

This approach assumes that you have implemented controllers with the hashbang in your URL like so, http://www.mydomain.com/#clocks/123 , but it should work even if you haven't yet.

这篇关于如何在 Backbone 中获取单个模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆