使Backbone Collection的URL成为动态

时间:2015-04-10 02:11:37

标签: backbone.js backbone-collections

我是BackboneJS的新手。

我想让我的收藏品的网址完全动态化。

以下是我要从中加载我的集合的2个网址:

http://localhost:3001/employees
http://localhost:3001/employees/searchByName/John

URL都返回相同的集合,区别在于第一个URL返回所有结果,而第二个URL基于搜索条件。

我的表单中有一个搜索字段,根据搜索字段是空还是包含搜索值,我想在这些网址之间切换。我看到的所有示例都在视图中记录过滤器,或者我看到的唯一动态URL是将id添加到现有url以获取单个记录而不是所有记录。

所以我的第一个问题是:如何为我的收藏实现此动态URL提取?

我的第二个问题是:如何根据搜索字段值以不同方式调用我的集合,以便集合选择适当的值。

someCollection = Backbone.Collection.extend({

    url: function() {

        if(this.searchName!=null)
            return baseURL + "/" +  "searchByName" + "/" + this.searchName;
        else
            return base_URL; 
    },

    search: function(searchTerm)
    {
        console.log("Search Term =" + searchTerm);

        var results = new someCollection();
        results.searchName = searchTerm;
        results.fetch({
            success: function()
            {
                vent.trigger("search:results", results);
            },
            error: function(collection, response){}
        });     
    },    

    parse: function(response, options) 
    {
        return response;
    }

});

到目前为止,我的Collection代码是这样的,但我认为我没有朝着正确的方向发展。

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

var SomeCollection = Backbone.Collection.extend({

    url: function() {

        if (this.searchName) {
            return this.baseURL + "/" +  "searchByName" + "/" + this.searchName;
        } else {
            return this.baseURL;
        }

    },

    searchName: null,

    search: function(searchName) {

        console.log("Search Name =" + searchName);

        this.searchName = searchName;

        this.fetch({
            success: function() {
                vent.trigger("search:results", results);
            },
            error: function(collection, response){
                console.log("Something went wrong");
            }
        });

    },    

    parse: function(response, options) {
        return response;
    }

});

var aFilteredCollection = new SomeCollection();
aFilteredCollection.search("Name goes here");

var aNonFilteredCollection = new SomeCollection();
aNonFilteredCollection.search();
相关问题