Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add attributes to a Backbone View?

I have been working with backbone for a while and I am now using a number of views. In some of my views I sometimes add custom attributes like:

    var DataGrid = Backbone.View.extend({
        className:"datagrid",
        lookup: {
            header: "", //Header wrapper row element
            headers: [], //Views in header
            body: "", //Body wrapper row element
            rows: [] //Views in body
        },

        events: {
            ...
        },

        initialize: function() {
            ...
        },

        render: function() {
            ...
        }
    });

As you can see I have "lookup" as an extra attribute to the Object. I use DataGrid in a number of my views and I am experiencing a very strange behaviour. When I switch between views that use DataGrid, "lookup" would still be populated with the old data. I use "new" when creating a new DataGrid but I still find old data. Am I missing something?

EDIT: Following @rabs reply. I did a search on static variables in Backbone and found this: Simplify using static class properties in Backbone.js with Coffeescript

like image 627
Xerri Avatar asked Oct 04 '12 09:10

Xerri


2 Answers

I know an answer has been accepted on this (a while ago), but as I came across this question while working on a backbone project recently, I thought it would be worth mentioning that you can define attributes as a function also. This is especially useful for views that need to have attributes set to values in their current models.

By defining attributes as a function you can do something like

var myObject = Backbone.View.extends({
    attributes: function() {
        if(this.model) {
            return {
                value: this.model.get('age')
            }
        }
        return {}
    }
}); 

Hope that helps someone

like image 117
Matt Keeble Avatar answered Oct 12 '22 05:10

Matt Keeble


Declaring variables in this way the scope of the variable is to the class not the instance, similar to s static or class variable.

So yeah the lookup object will shared between your different instances.

You could pass the lookup object in to your instance when you create it that way it will behave as an instance variable.

like image 20
rabs Avatar answered Oct 12 '22 05:10

rabs