Backbone.js get and set nested object attribute

83,965

Solution 1

While this.model.get("obj1").myAttribute1 is fine, it's a bit problematic because then you might be tempted to do the same type of thing for set, i.e.

this.model.get("obj1").myAttribute1 = true;

But if you do this, you won't get the benefits of Backbone models for myAttribute1, like change events or validation.

A better solution would be to never nest POJSOs ("plain old JavaScript objects") in your models, and instead nest custom model classes. So it would look something like this:

var Obj = Backbone.Model.extend({
    defaults: {
        myAttribute1: false,
        myAttribute2: true
    }
});

var MyModel = Backbone.Model.extend({
    initialize: function () {
        this.set("obj1", new Obj());
    }
});

Then the accessing code would be

var x = this.model.get("obj1").get("myAttribute1");

but more importantly the setting code would be

this.model.get("obj1").set({ myAttribute1: true });

which will fire appropriate change events and the like. Working example here: http://jsfiddle.net/g3U7j/

Solution 2

I created backbone-deep-model for this - just extend Backbone.DeepModel instead of Backbone.Model and you can then use paths to get/set nested model attributes. It maintains change events too.

model.bind('change:user.name.first', function(){...});
model.set({'user.name.first': 'Eric'});
model.get('user.name.first'); //Eric

Solution 3

Domenic's solution will work however each new MyModel will point to the same instance of Obj. To avoid this, MyModel should look like:

var MyModel = Backbone.Model.extend({
  initialize: function() {
     myDefaults = {
       obj1: new Obj()
     } 
     this.set(myDefaults);
  }
});

See c3rin's answer @ https://stackoverflow.com/a/6364480/1072653 for a full explanation.

Solution 4

I use this approach.

If you have a Backbone model like this:

var nestedAttrModel = new Backbone.Model({
    a: {b: 1, c: 2}
});

You can set the attribute "a.b" with:

var _a = _.omit(nestedAttrModel.get('a')); // from underscore.js
_a.b = 3;
nestedAttrModel.set('a', _a);

Now your model will have attributes like:

{a: {b: 3, c: 2}}

with the "change" event fired.

Solution 5

There is one solution nobody thought of yet which is lots to use. You indeed can't set nested attributes directly, unless you use a third party library which you probably don't want. However what you can do is make a clone of the original dictionary, set the nested property there and than set that whole dictionary. Piece of cake.

//How model.obj1 looks like
obj1: {
    myAttribute1: false,
    myAttribute2: true,
    anotherNestedDict: {
        myAttribute3: false
    }
}

//Make a clone of it
var cloneOfObject1 = JSON.parse(JSON.stringify(this.model.get('obj1')));

//Let's day we want to change myAttribute1 to false and myAttribute3 to true
cloneOfObject1.myAttribute2 = false;
cloneOfObject1.anotherNestedDict.myAttribute3 = true;

//And now we set the whole dictionary
this.model.set('obj1', cloneOfObject1);

//Job done, happy birthday
Share:
83,965

Related videos on Youtube

fortuneRice
Author by

fortuneRice

Updated on July 08, 2022

Comments

  • fortuneRice
    fortuneRice almost 2 years

    I have a simple question about Backbone.js' get and set functions.

    1) With the code below, how can I 'get' or 'set' obj1.myAttribute1 directly?

    Another question:

    2) In the Model, aside from the defaults object, where can/should I declare my model's other attributes, such that they can be accessed via Backbone's get and set methods?

    var MyModel = Backbone.Model.extend({
        defaults: {
            obj1 : {
                "myAttribute1" : false,
                "myAttribute2" : true,
            }
        }
    })
    
    var MyView = Backbone.View.extend({
        myFunc: function(){
            console.log(this.model.get("obj1"));
            //returns the obj1 object
            //but how do I get obj1.myAttribute1 directly so that it returns false?
        }
    });
    

    I know I can do:

    this.model.get("obj1").myAttribute1;
    

    but is that good practice?

    • freethejazz
      freethejazz about 10 years
      While it isn't an answer to the question: Whenever specifying an object (anything passed by reference) in defaults (obj1 in this case), that same object will be shared across all instances of the model. The current practice is to define defaults as a function that returns an object to be used as defaults. backbonejs.org/#Model-defaults (see the italicized note)
    • T J
      T J over 9 years
      @JonathanF Comments aren't meant for answers so you never needed the declaration :)
  • Bill Eisenhauer
    Bill Eisenhauer almost 13 years
    To this answer, I would add the advisement that this solution teeters on widespread Law of Demeter violations. I would consider adding convenience methods that hide the navigation to the nested object. Basically, your callers don't need to know the model's internal structure; after all, it may change and the callers should be none the wiser.
  • wilsonpage
    wilsonpage over 12 years
    Can't get this to work for me. Throws error: Uncaught TypeError: Object #<Object> has no method 'set'
  • Benno
    Benno almost 12 years
    Yeah, this doesn't work for me either... I get the same error as pagewil. I was doing: window.Helper = Backbone.Model.extend({ defaults: { "type": null, "notes": [] } }); window.Events = Backbone.Model.extend({ defaults: { "title": null, "data": new Helper() } } }); (didnt work with model.get("data").get("type"))
  • Christian Nunciato
    Christian Nunciato almost 12 years
    get("attr") returns a plain object, not a Backbone model, so get("attr").set({any: "thing"}) doesn't work.
  • Domenic
    Domenic almost 12 years
    @ChristianNunciato, pagewil, Benno: You seem to have missed the point of the post, which is to nest Backbone models inside Backbone models. Don't nest plain objects inside Backbone models. Working example here: jsfiddle.net/g3U7j
  • Domenic
    Domenic over 11 years
    For future readers, my answer has been updated to incorporate the best of Rusty's answer.
  • Jon Raasch
    Jon Raasch over 11 years
    Asker should flag this as the accepted answer. Domenic's is a great start, but this solves an issue with it.
  • tom
    tom over 11 years
    I didn't inspect backbone.js code, but from my test, if you have a nested custom Model and change a property of it with set(), its parent model will not fire a 'change' event itself; I had to fire the event myself. I really should just inspect the code, but is this your understanding too?
  • Domenic
    Domenic over 11 years
    @tom that is correct. Backbone doesn't special-case for when properties of models are instances of Backbone.Model, and then start doing magical event bubbling.
  • maximus
    maximus almost 11 years
    @Domenic: I have tried it, and the view doesn't change (render is not called) when model of a model is changed. How to connect them to View's render?
  • maximus
    maximus almost 11 years
    @Domenic: For example, do I have to call this.listenTo(this.model, "change", this.render); then to call: this.listenTo(this.model.get("obj1"), "change", this.render); etc?
  • HungryCoder
    HungryCoder almost 11 years
    Are you sure about this? this does not work for me. meta2= m.get('x'); meta2.id=110; m.set('x', meta2). This does not trigger any change event for me :(
  • HungryCoder
    HungryCoder almost 11 years
    I see it works when I clone the attribute like _.clone(m.get('x')). thanks
  • user10
    user10 over 10 years
    @Domenic If we model our data like you describe above, we have to customize model's parse function to set values to obj1. Am i correct?
  • Derek Dahmer
    Derek Dahmer over 10 years
    Thanks @HungryCoder it worked for me too when cloned. Backbone must compare the object you are setting with the object you are getting at set time. So if you don't clone then the two objects, then the two objects being compared are exactly the same at set time.
  • tawheed
    tawheed over 10 years
    Yes it does, if you look at the API there is an example like //You can use index notation to fetch from arrays console.log(model.get('otherSpies.0.name')) //'Lana'
  • mariachi
    mariachi about 10 years
    Works great! But does line 2 in your example require a colon instead of a comma?
  • ambar
    ambar almost 9 years
    @Domenic while doing something similar this.model.get("eventListener").set({"id":2}) Following exception was thrown: "Uncaught TypeError: this.model.get(...).set is not a function" Same goes for using nested get() .
  • allthesignals
    allthesignals over 8 years
    I'm confused. I'm simply trying to access attributes of a model, but seeing get(...).get is not a function. From the model, I have to get('attributes') then get('attribute') (For context, this is in a #groupBy loop called on a Backbone collection, in which the context passed is a Backbone model of the collection).
  • Setup
    Setup almost 7 years
    How would you go about and listen to change events of e.g. myAttribute1?
  • niall.campbell
    niall.campbell about 6 years
    Remember that objects are passed by reference and are mutable, unlike string and number primitives. Backbone's set and constructor methods attempt a shallow clone of any object reference passed as an argument. Any references to other objects in properties of that object aren't cloned. When you set it and retrieve it the reference is the same, which means you can mutate the model without triggering a change.