udexter
udexter

Reputation: 2347

Updating some parts of a Backbone Marionette ItemView

I'm a new to Backbone.js and also to Backbone.Marionette and I'm having some troubles trying to follow the best patterns for my application.

I'm creating a mobile web application encapsulated by PhoneGap. I have a common layout (Facebook like): 2 sidebars, a main header and a content zone where all the views are loaded.

My initialization code for a Backbone.Marionette application is:

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

App.addRegions({
    leftRegion: '#left-drawer',
    rightRegion: '#right-drawer',
    headerRegion: '#header',
    contentRegion: '#content',
    mainRegion: '#main'
});

This are my regions where the content will be attached. Later, just after initialize the router I have the next:

App.headerRegion.show(App.Views.Header);
App.leftRegion.show(App.Views.LeftSidebar);
App.rightRegion.show(App.Views.RightSidebar);

This will load my content to this new regions. The problem occurs in the HeaderView. The template for my Header view:

<button id="open-left"><img src="assets/img/icons/menu-icon.png"></button>
<h1 class="title logo"><img src="assets/img/logo.png" height="28px" width="167px"></h1>
<button id="open-right"><img src="assets/img/icons/chat-icon.png"></button>

The ItemView it's very simple too:

var HeaderView = Backbone.Marionette.ItemView.extend({
    template: _.template(template),
});

In some parts of the app I don't want to use the <img> in the header. Some pages of the app will need to update this to a text, for example something like <h1>Settings</h1>. My question is, what's the best way to do it? Or better, what is the way to do it? Right now I don't know where to start and the only idea I've in mind is to create a new ItemView with another template.

Thanks in advance!

Upvotes: 4

Views: 456

Answers (1)

Rayweb_on
Rayweb_on

Reputation: 3727

Marionette provides a useful function for this case, getTemplate, and you use this function isntead of the template : template declarations, like this.

SampleView = Backbone.Marionette.ItemView.extend({
   getTemplate: function(){
      if (this.model.get("foo")) 
          return "#sample-template";
      else       
          return "#a-different-template";
   },
});

So in the parts of yur application where you need a diferent template wihtout image you just change modify a value on the view or your model that can be used in this function to made the change on the template at the time you call render.

Upvotes: 6

Related Questions