Search code examples
backbone.jsmustache

Mustache lambda function accessing its view instance 'this'


Is it possible for mustache lambda function to access its view instance this?

Backbone.View.extend ({
    initialize: function (options) {
        this.collection = options.collection  // large backbone.collection 
    },

    parseContent: function (){
        return function (id, render){
            //this.collection is undefined below
            return this.collection.get (render (id)).get ('stuff);
        }
    }
});

Tried _.bind (this.parseContent, this) inside initialize (), this still carry the model context inside parseContent ().

My current workaround is saving this.collection to my app root namespace and access from there. Wondering is there a cleaner way to do this as intended above?

Appreciate your advice.


Solution

  • If you're going to pass around the function returned by parseContent, you should

    1. bind that function before returning it with _.bind,
    2. and use _.bindAll in initialize to force this in parseContent on each instance.

    Your view could be written as

    Backbone.View.extend ({
        initialize: function (options) {
            _.bindAll(this, 'parseContent');
    
            // you don't need this.collection = options.collection
            // collection is part of the special variables handled By Backbone
        },
    
        parseContent: function (){
            var f = function (id, render){
                console.log(this.collection);
            }
    
            return _.bind(f, this);
        }
    });
    

    And a demo http://jsfiddle.net/nikoshr/VNeR8/