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

前端 未结 5 1326
-上瘾入骨i
-上瘾入骨i 2021-02-15 14:48

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 differe

5条回答
  •  温柔的废话
    2021-02-15 15:32

    I really like the approach suggested by 'user645715'. I have adjusted the code to be more versatile. If you add this to a Backbone Model it will allow you to search the server by one or more attributes, and should work as a direct drop-in 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 like this:

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

提交回复
热议问题