Search code examples
javascriptbackbone.jsmarionette

Call one app's view from another in Marionette


I have an IdentificationView that has to call a method of another view in different app:

var NameAndIdentificationView = Application.Views.ItemView.extend({
    loadMailingAddressView: function() {
                //call to mailing address view method setAddress() from here
    }
});

Now my MailingAddressView is something like this:

var MailingAddressView= Application.Views.ItemView.extend({
    setAddress: function(address) {
        if (address != null) {
            // this.autoCompleteBox.data('inputData') = address;
            ProWeb.EXTRACTED_ADDRESS = address;
            this.model.set('mailingAddress', address);
        }
    }
});

I would like to know what is the way to call a method of one view from another. Please provide suggestions.

EDIT:

This is how my application has been setup:

  1. First App is called.
  2. Then the Controller is called.
  3. From within the Controller, View is called and intialized.

So from within my NameIdentificationView, I'm calling the MailingAddress app that in turn controls all the process of calling the controller and it's view.


Solution

  • You can do it many ways using event channel,triggering and listening events on shared model, the simpler way of doing this is using Bsckbone events.

    Trigger a event in caller

    loadMailingAddressView: function () {
                    //call to mailing address view method setAddress() from here
                 Backbonw.trigger('setAddress')
    })
    

    and listen in callee's initalize

        var MailingAddressView = Application.Views.ItemView.extend({
    
        initialize: function() {
            Backbone.on('setAddress', this.setAddress)
        },
        setAddress: function(address) {
            if (address != null) {
                // this.autoCompleteBox.data('inputData') = address;
                ProWeb.EXTRACTED_ADDRESS = address;
                this.model.set('mailingAddress', address);
            }
        },
    });
    

    make sure callee View is initialized by the time you trigger event