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'); } });
Digitaljohn
source share