Search code examples
jquerybindmarionettejquery-events

Marionette passing bindData with bindTo


Is there a way to pass bindData to Marionette's bindTo, similar to jQuery's bind?

I read on jQuery's website that you can do the following to pass bindData:

function myFunction(event){
    console.log(event.data.foo); // output "bar"
};
$(".some-element").bind("click", {foo:"bar"}, myFunction);

The reason I'd like to do this is because I am binding multiple functions to one route.

The first function just uses the parameter from the route, nothing special.
The second function needs custom data to be passed to it, which is where bindData comes in.

Controller and Router

var Controller = {
    page1: function(itemId){
        Vent.trigger('openPageOne', itemId);
    }
};

var AppRouter = Marionette.AppRouter.extend({
    controller: Controller,
    appRoutes: {
        "page1/:itemid" : "page1"
    },
    start: function() {
        Backbone.history.start();
    }
});

First bind
This works nicely, and I get the itemId printed on the console when navigating to that route.

var MyLayout = Marionette.Layout.extend({
    initialize: function(){
        _.bindAll(this);
    },
    myFunction: function(itemId){
        console.log(itemId);
    }
});

var myLayout = new MyLayout();
myLayout.bindTo(Vent, "openPageOne", myLayout.myFunction);

Second bind
This is where I fail :(
I would like to pass a custom data object to the function.
Inside anotherFunction, I want to display the value for foo.

var AnotherLayout = Marionette.Layout.extend({
    initialize: function(){
        _.bindAll(this);
    },
    anotherFunction: function(event){
        // Here is where I want to use foo
        console.log(event.data.foo);
    }
});

var anotherLayout = new AnotherLayout();
anotherLayout.bindTo(Vent, "openPageOne", {foo:"bar"}, anotherLayout.anotherFunction);

On more concrete terms, the first function should change the contents of my page. The second function should highlight an item in my navigation menu. The custom object I want to send to my function is basically the menu item's element ID so I can add a class to it.

Am I just approaching this the wrong way? Any input would be helpful.


Solution

  • Not sure if this will help but I tend to use Vent in Marionette.

    var app = new Backbone.Marionette.Application();
    

    I then use listenTo (replaces bindTo) event to fire and when it fires I trigger,

    app.vent.trigger('App:openPageOne', { 'foo': 'bar'});
    

    then in your vent listener

    app.vent.on('App:openPageOne', function(data) {
    }
    

    your data is sent to the data parameter: data.foo

    You can also send more data inside the object { 'foo1': 'bar1', 'foo2': 'bar2' }

    I like using the app event manager.