Search code examples
javascriptbackbone.jsunderscore.js

Backbone change model and change the properties of the new models


Backbone has a model that will change when a property is changed to the new models also have even default properties also change these.

Recovery model and change the property

var model =  window.collections.elements.get('c1');
// property change css.background.value = red
var vals = model.get('css')['background']['value'] = 'red';

model.set( vals );
model.trigger('change');

I add a new property is also changed

// add new model and inherits the model that made the change
var new_m = new Maker.Models.Widget.H2();
window.collections.elements.add(new_m);

console.log( window.collections.elements.get('c2').get('css') );
// property change and new model change css.background.value = red

http://jsfiddle.net/L8cjfged/

Console

UPDATE

Solution 1

McGarnagle thank you

Solution 2

var model = window.collections.elements.get('c1'); var newModel = $.extend( true, {}, model );


Solution

  • So apparently Backbone is not smart enough to clone the default values -- it saves and re-uses the same instance (of course this works fine for value types, but not for reference types).

    To get around this problem, I would use the "initialize" function to set the "css" default, like this:

    Maker.Models.Widget.H2 = Backbone.Model.extend({
        sync: function () { return false; },
        initialize: function() {
            if (!this.has('css')) {
                this.set('css', { 
                    'background' : {
                        value : '',
                        type  : 'text',
                        script : ''
                    } 
                });
            }
        },
    })
    

    http://jsfiddle.net/ueq87c85/3/