在Backbone.js视图中侦听集合的函数调用

时间:2014-01-21 08:06:02

标签: javascript backbone.js

尝试在调用filterMe时嗅出,以便我可以更新视图:

var MyCollection = Backbone.Collection.extend({
    model: MyModel,
    url: '/myapi',
    filterMe: function() {
        return this.where({tag: "A"});
    }
});

var MyView = Backbone.View.extend({
    el: 'div',
    initialize: function() {
        var that = this;
        //Anytime I call filterMe, I need to update the view with filtered data
        this.listenTo(my_collection, 'filterMe', this.render);
        my_collection.fetch({
            success: function() {
                that.render();
            }
        });
    },
    render: function() {
        ...
    }
)};

var my_collection = new MyCollection();
var my_view = new MyView();

需要在执行filterMe的任何时候触发渲染功能。有任何想法吗?非常感谢!

2 个答案:

答案 0 :(得分:2)

尝试

filterMe: function() {
    this.trigger("filterMe");
    return this.where({tag: "A"});
}

答案 1 :(得分:0)

您应该在'filterMe'函数中触发事件并在视图中监听它。 试试这个:

var MyCollection = Backbone.Collection.extend({
    model: MyModel,
    url: '/myapi',
    filterMe: function() {
        //trigger a custom event that will be listened in the view
        this.trigger('filtered'); 
        return this.where({tag: "A"});
    }
});

var MyView = Backbone.View.extend({
    el: 'div',
    initialize: function() {
        var that = this;
        //listen to custom event triggered in 'filterme' function
        my_collection.on('filtered',$.proxy(this.render, this));
        my_collection.fetch({
            success: function() {
                that.render();
            }
        });
    },
    render: function() {
        ...
    }
)};

var my_collection = new MyCollection();
var my_view = new MyView();

我想这就是你想要的。请试试这个让我知道