Get a view from its container element

46 views Asked by At

I'm dealing with some poorly planned, poorly written code right now, and I don't have the time to do a rewrite. I need to be able to access a view that is rendered on the same page, but otherwise separate from the view I need to access it from.

Given the element that contains the external view, how can I access it? Is there a better way to make the view available (without rewriting the way they are wired together)?

1

There are 1 answers

0
Kavish Dwivedi On

I suppose that you are using marionette. Your question is in particular a design question rather than a simple line of code to do another nasty thing. Ideally , something like $("#element") is not a good practice because it goes through whole of your DOM to figure out the element.

Rather I would suggest you the below approach which works well in most of the places given both your views are view1 and view2 :

  1. Make a Layout View in specifying the regions which contain both these views.
  2. Now all you have to do is initialize both these views inside the above created Layout View.
  3. When you want to access anything from view1 to view2, all you do inside view1 is something like below:

From the child Item view of layout :

this.triggerMethod('show:message', msg);

and The layout has some code like :

 childEvents: {
  'show:message': function (childView, msg) {
    view2.dosomething();
  }
}

This way you can keep the views functionality separate from each other and also you code remains clean.

I guess for this you can also look at Marionette documentation http://marionettejs.com/docs/marionette.layoutview.html