Note that there are some explanatory texts on larger screens.

plurals
  1. POPrivate event handlers in Backbone Views
    primarykey
    data
    text
    <p>I'm trying to figure out a way to keep my private functions and helper methods truly private. Each object should only publicize what is allowed to be called externally (radical, I know!). I'm having a hard time doing this with Backbone views in a way that:</p> <ol> <li>Doesn't sacrifice readability</li> <li>Doesn't involve a lot of boilerplate</li> <li>Doesn't have any unintended consequences</li> </ol> <p>Here's my general View structure:</p> <pre><code>(function(){ //Private function no other view needs to care about var addStuffToMyDom = function(model){ var newView = new Subview({model: model}); //Problem: this doesn't refer to the 'view' here this.$el.append(newView.render().$el); } //Another trivial function which should really be private var doSomeThingTrivial = function(){ this.$el.addClass("meh"); } return BaseView.extend({ events: { "click": doSomeThingTrivial }, render: function(){ var me = this; this.collection.each(addStuffToMyDom); return this; } }); }()); </code></pre> <p>As you can see the private functions can't reference 'this' to append themselves to.</p> <p>Solution 1:</p> <pre><code>(function(){ var me; ... return BaseView.extend({ initialize: function(){ me = this; } }); }()); </code></pre> <p>This has a lot of subtle side-effects + would be annoying to have to do this every time. </p> <p>Solution 2:</p> <pre><code>(function(){ var me; ... return BaseView.extend({ events{ "click" : function(){ doSomeThingTrivial.call(this); } } }); }()); </code></pre> <p>This works, but it's a lot of boilerplate for messy code.</p> <p>Solution 3:</p> <pre><code>(function(){ return BaseView.extend({ events: {..} initialize: function(){ _.bindAll(this, this.events); } }); }()); </code></pre> <p>I like this the best; this works, is fairly readable and works as advertised, but again, is one extra step to do for each view. Any other solutions I'm missing?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload