如何抓骨干单一的模式? [英] How do I fetch a single model in Backbone?
问题描述
我在骨干时钟
模型:
var Clock = Backbone.Model.extend({});
我想获得某个实例具有从 /时钟/ 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'
创建一个实例,然后调用取
就可以了:
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支持的时钟?
推荐答案
您第二种方法是我使用的方法。尝试添加以下到您的时钟模式:
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;
},
该方法假定您已实现与hashbang控制器在你的URL像这样, http://www.mydomain.com /#时钟/ 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.
这篇关于如何抓骨干单一的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!