Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js View determine which attribute of model is change

How can I know which attribute of the view model is changed in the render function? (In the render function, "e" is the model, but I need only the attribute which is changed.) I need to know this to know which template to use. Or is there another method to do this?

window.Person = Backbone.Model.extend({});

window.Njerzit = Backbone.Collection.extend({
    model: Person,
    url: '/Home/Njerzit'
});

window.PersonView = Backbone.View.extend({
    tagName: 'span',

    initialize: function () {
        _.bindAll(this, 'render');
        this.model.bind('change', this.render);
    },

    render: function (e) {
        //if model name is changed, I need to render another template
        this.template = _.template($('#PersonTemplate').html());
        var renderContent = this.template(this.model.toJSON());
        $(this.el).html(renderContent);
        return this;
    }
});
like image 543
Florim Maxhuni Avatar asked Dec 28 '11 21:12

Florim Maxhuni


People also ask

How can we get the attribute value of a model in Backbone JS?

js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)

Is Backbone JS still used?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

What is El property of backbone JS view?

The Backbone. js View el method defines the element that is used as the view reference. this. el is created from the view's tagName, className, id and attributes properties, if specified.


2 Answers

I believe the changedAttributes function is what you're looking for

changedAttributesmodel.changedAttributes([attributes])
Retrieve a hash of only the model's attributes that have changed. Optionally, an external attributes hash can be passed in, returning the attributes in that hash which differ from the model. This can be used to figure out which portions of a view should be updated, or what calls need to be made to sync the changes to the server.

or to check if a specific attribute has changed use the hasChanged function

hasChangedmodel.hasChanged([attribute])
Has the model changed since the last "change" event? If an attribute is passed, returns true if that specific attribute has changed.

var nameChanged = this.model.hasChanged("name");
  • From Backbone Docs
like image 72
Bobby Avatar answered Oct 15 '22 17:10

Bobby


You can bind to change:name if you only want to notify if the name has changed: http://documentcloud.github.com/backbone/#Model-set

like image 45
Andreas Köberle Avatar answered Oct 15 '22 16:10

Andreas Köberle