How to get the Backbone.js model with something other than an ID?

Backbone.js by default, a RESTful approach to selecting a model by ID is easy and straightforward. However, I cannot find examples of model selection using another attribute. How can I select the Backbone.js model with a different attribute?

var Widget = Backbone.Model.extend({ urlRoot: '/widgets', fetchByName: function(){ ... } }); var foowidget = new Widget({name: 'Foo'}); foowidget.fetchByName(); 
+8
source share
5 answers

You can try to do something similar in your base model definition or on demand when calling fetch.

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

In your case, along the lines.

 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(); 
+14
source share

One approach is to override the Backbone.sync () method for all classes or just for your class. However, apparently, your goal is to override the selection for only one model. One way to do this is to directly call jQuery.ajax (...) and, if successful, accept the response and install it, for example.

 fetchByName: function() { var self = this; $.ajax({ url: self.urlRoot+ "?name="+this.get('name'), type: 'GET', contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { self.set(data); } }); } 
+3
source share

If the model is part of a collection, you can use where () to pull out models that meet certain criteria.

See http://backbonejs.org/#Collection-where

+3
source share

I really like the approach suggested by user645715. I adjusted the code to be more universal. If you add this to the base model, this will allow you to search for a server by one or more attributes and work as a direct replacement for fetch .

 fetchByAttributes: function(attributes, callbacks) { var queryString = []; for(var a in attributes){ queryString.push( encodeURIComponent(a)+'='+encodeURIComponent(attributes[a]) ); } queryString = '?'+queryString.join('&'); var self = this; $.ajax({ url: this.urlRoot+queryString, type: 'GET', dataType: "json", success: function(data) { self.set(data); callbacks.success(); }, error: function(data){ callbacks.error(); } }); } 

It can be used as follows:

 var page = new Page(); page.fetchByAttributes({slug:slug}, { success: function(){ console.log('fetched something'); }, error: function(){ console.log('nothing found'); } }); 
+1
source share

this is a simple model.fetch the same as $ .ajax in some way

 model = Backbone.Model.extend({ urlRoot: "/root/" }); var Model = new model(); Model.fetch({ beforeSend: function () { console.log("before"); }, data: { param1: "param1", param2: "param2" }, success: function () { console.log("success"); }, error: function () { console.log("failure"); } }); 
0
source share

All Articles