Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client-side only attributes in Backbone

Tags:

backbone.js

I have a fairly generic model and collection of that model (see below) I am dealing with as the basis for a series of views. On several of the views, the selection of one of the models generates actions (via the 'selected' attribute), and I need to be able to keep track of the selection on just the client side.

However, it appears that there is no clean way to do this in Backbone. Any attributes added to/changed on the model on the client will be sync'd up to the server. I can't use {silent : yes} when changing that attribute because I need to trigger changes in my views when the change event fires on that attribute. The only way I have come up with to do this is to overwrite the save function on Backbone.Model

My question: is there a way to have client-side only attributes that I am missing OR is my approach structurally flawed in some other way that I am just not seeing?

    var CSEvent = Backbone.Model.extend({
        idAttribute: "_id",
        urlRoot : '/api/events',
        defaults: {
            title : "",
            type : "Native",
            repeatOrOneTime : "OneTime",
            selected : false
        }
    });    

    var CSEventCollection = Backbone.Collection.extend({
        model: CSEvent,
        url: '/api/events',
        getSelectedEvent : function() {
            return this.find(function(csevent) { return csevent.get('selected') === true; });
        },
        selectEvent : function(eventId) {
            this.deselectEvent();
            this.get(eventId).set({selected : true});
        },
        deselectEvent : function() {
            this.getSelectedEvent().set({selected : false});
        }
    });
like image 256
Dave Avatar asked Aug 13 '12 19:08

Dave


1 Answers

Try to override the Model.toJSON() method, as you can see in the Backbone Model code this method is not very complicate. Also the official documentation suggests to override it in case of special needs.

Try something like this:

var CSEvent = Backbone.Model.extend({
  toJSON: function(){
    return _.clone( _.pick( this.attributes, "title", "type", "repeatOrOneTime" ) );
  }
});
like image 106
fguillen Avatar answered Nov 15 '22 08:11

fguillen