0
votes

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.

1
Well, you're triggering an event on your ItemView and listening to an event on your controller. That won't work indeed. I suppose you have a reference to your view in the controller somewhere, use that as target for the event listener. Also try to use the listenTo instead of on event binding. In your example in the controller you can do something like this.listenTo(viewReference, 'grants:filter', function()});Wilbert van de Ridder
The problem is, the controller is associated with a different view, so I have no reference to it.eggbert
In that case I would suggest using wreqr to raise and receive events. See: github.com/marionettejs/backbone.marionette/blob/master/docs/…Wilbert van de Ridder

1 Answers

0
votes

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...

}