Question

I have a collection of grants displayed on a page. When I type in a box, it filters the list down. The text input triggers an event on a marionette itemView, which calls the controller with the filtered down collection:

keywordFilter: function (ev) {
    var keyword = ev.currentTarget.value;
    var controller = sff.app.router.controller;
    var collection = sff.app.grantList;

    var filtered = collection.filterByKeyword(keyword);
    controller._showGrants(filtered, 1);
}

This works fine but the way I get a reference to controller and collection doesn't look too good and supposedly using events is better, so I tried this:

In itemView:

keywordFilter: function (ev) {
    var keyword = ev.currentTarget.value;
    this.trigger('grants:filter', keyword);
}

In controller:

var GrantController = Marionette.Controller.extend({
    initialize: function (options) {
        this.viewClass = options.viewClass;
        this.app = options.app;
        this.collection = options.collection;

        this.on("grants:filter", function(keyword) {
            console.log(keyword);
            var filtered = this.collection.filterByKeyword(keyword);
            this._showGrants(filtered, 1);
        });
    },
    ...more methods...
}

Unfortunately it isn't receiving the event. I also tried this.app.on() and this.viewClass.on(), and this.on("itemView:grants:filter) but it's still not working.

As mentioned below, the controller has no reference to the itemView or vice versa. I think perhaps I want to be doing app.vent.trigger('grants:filter') but how do I get a reference to app from the itemView?

I'm starting to really hate backbone and marionette, I'd actually rather have jquery spaghetti than this nonsense.

Was it helpful?

Solution

If you can't get a reference to it. You can trigger the event on other object, Backbone for example, and listen to it in the controller.

keywordFilter: function (ev) {
    var keyword = ev.currentTarget.value;
    Backbone.trigger('grants:filter', keyword);
}


var GrantController = Marionette.Controller.extend({
    initialize: function (options) {
        Backbone.on("grants:filter", function(keyword) {

        });
     },
...more methods...

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top