× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Updating a LayoutView's Model

Yuriy Linnyk
Apr 06, 2016
<p>Backbone and Marionette do not bind model data to views automatically. You will have to listen that model to change within the view and update it.</p> <p>For example, you can simply re-render the view completely when any data within the model changes:</p> <pre><code>initialize: function(){ this.listenTo( this.model, "change", this.render ); } </code></pre> <p>Or create a listener for a specific piece of data expected to change, and only update part of the view. This is preferred if the view is more complicated:</p> <pre><code>onRender: function(){ this.listenTo( this.model, "change:value", this.renderValue ); }, renderValue: function(){ /* This expects that you wrap the value with &lt;span class="value"&gt;&lt;/span&gt; in the template */ this.$('.value').text( this.model.get('value') ); } </code></pre> <p>Here's a complete working example:</p> <p></p><div class="snippet"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var TestLayoutView = Mn.LayoutView.extend({ template: '#lvTemplate', el: '#app', events: { 'click .watchhere': 'updateValue'}, onRender: function(){ this.listenTo( this.model, "change:value", this.renderValue ); }, renderValue: function(){ this.$('.value').text( this.model.get('value') ); }, updateValue: function (clickedView) { this.model.set('value', this.model.get('value') + 1); } }); var testLV = new TestLayoutView({ model: new Backbone.Model({ value: 15 }) }); testLV.render();</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src='http://code.jquery.com/jquery.js'&gt;&lt;/script&gt; &lt;script src='http://underscorejs.org/underscore.js'&gt;&lt;/script&gt; &lt;script src='http://backbonejs.org/backbone.js'&gt;&lt;/script&gt; &lt;script src='https://cdnjs.cloudflare.com/ajax/libs/backbone.marionette/2.4.2/backbone.marionette.js'&gt;&lt;/script&gt; &lt;script type="text/template" id="lvTemplate"&gt; &lt;a class='watchhere' href="#"&gt;Clicks &lt;span class="value"&gt;&lt;%= value %&gt;&lt;/span&gt;&lt;/a&gt; &lt;/script&gt; &lt;div id="app"&gt;&lt;/div&gt;</code></pre> </div> </div> <p></p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/33003806/Updating%20a%20LayoutView's%20Model/33004169">Stack Overflow</a>.</p>
comments powered by Disqus