Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update attribute of an existing model?

Tags:

backbone.js

I wanted to update the rank attribute of an existing model which I passed from another view. However, I get the error Uncaught TypeError: Object # has no method 'set'.

In the initialize part of the view, I have :

this.collection = new tgcollection({model : this.options.model });

I define a function updateModel intended to update the attribute value as:

updateModel: function(){
    var val= $("#textbox_id").val();
console.log(val);   
console.log(JSON.stringify(this.options.model));
JSON.stringify(this.options.model);
this.options.model.set({"rank": val});
this.render();
//
},

Where am I going wrong? I can see the value and the model with its previous attribute values in the console.

The model:

define(['jquery','underscore', 'backbone', 'deepmodel'], 
       function($,_, Backbone) {
         var model = Backbone.DeepModel.extend({

        // Default attributes for the model.
        defaults : {
            id: null,
                rank: null,

        },

        initialize: function(){
            _.bindAll(this,"update");
                    this.bind('change : cost', this.update);
        },

        update: function(){
            console.log(this.get("cost"));

        },
        // Remove this model from *localStorage*.
        clear : function() {
            this.destroy();
        },

    });
    return model;

});

like image 420
Amateur Avatar asked Dec 21 '22 17:12

Amateur


1 Answers

Just do

this.model.set({"rank": val});

instead of

this.options.model.set({"rank": val});

The model within a view is accessed via this.model not this.options.model

like image 52
schacki Avatar answered Dec 28 '22 05:12

schacki