Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch a Backbone.js model by something other than the ID?

Tags:

backbone.js

Backbone.js's default, RESTful approach to fetching a model by the ID is easy and straight-forward. However, I can't seem to find any examples of fetching a model by a different attribute. How can I fetch a Backbone.js model by a different attribute?

var Widget = Backbone.Model.extend({
    urlRoot: '/widgets',
    fetchByName: function(){ ... }
});
var foowidget = new Widget({name: 'Foo'});
foowidget.fetchByName();
like image 616
Andrew Avatar asked Jan 28 '13 04:01

Andrew


1 Answers

You can try doing something like this on your base model definition or on demand when calling fetch.

model.fetch({ data: $.param({ someParam: 12345}) });

In your case, along the lines of.

var Widget = Backbone.Model.extend({
    initialize: function(options) {
        this.name = options.name;        
    },
    urlRoot: '/widgets',
    fetchByName: function(){ 
        this.fetch({ data: $.param({ name: this.name }) }) 
    }
});

var foowidget = new Widget({name: 'Foo'});
foowidget.fetchByName();
like image 192
Dennis Rongo Avatar answered Sep 21 '22 14:09

Dennis Rongo