Search code examples
javascriptbackbone.jsbackbone-viewsbackbone-model

Get the changed "this.model" attribute value


A Backbone.js noob question. The code I'm working with currently looks like this

My DataModel Model :

define(['jquery', 'underscore', 'backbone'], function($, _, Backbone) {
    var DataModel = Backbone.Model.extend({
        // Defaults attribute values
        defaults : {
            completed : false,
        },
        url : 'path/to/my/data.json',
    });
    return DataModel;
});

And I have another Model called ServiceModel which is an instance of DataModel which looks like this

define(['jquery', 'underscore', 'backbone', '../models/DataModel'], function($, _, Backbone, DataModel) {

    // SupplierService as an Object Literal.
    SupplierService = {};

    // Instatiate the DataModel()
    var ServiceModel = new DataModel();
    var that = ServiceModel;

    ServiceModel.fetch().done(function() {
        data = ServiceModel.toJSON();

        SupplierService.figures.calculate(data)
    });

    SupplierService.figures = (function() {
        // I set completed to true here
        function constructor(d) {
        // some work done here
            that.set({
                completed : true,
            });
        }

        return {
            calculate : function(d) {
                constructor(d)
            },
        }
    })();

    return ServiceModel;
});

My View :

define(['jquery', 'underscore', 'backbone', '../../models/ServiceModel'], function($, _, Backbone, ServiceModel) {
    var AppVIew = Backbone.View.extend({
        model : ServiceModel,
        initialize : function() {
            console.log(this.model.get('completed'));
        },
    });
    return AppVIew;
});



My Output prints false and not true. This is how it looks when I print this.model

enter image description here

Why is it that when I this.model.get('completed') I get false.

I am doing the correct thing?? Any help/advice will be appreciated, to go further.

Thanks in advance.


Solution

  • In View:initialize you have got default model value, then in a couple of seconds ServiceModel.fetch() has finished request and updated model value with true

    From my perspective:
    1 move out DataModel from SupplierService
    2 rewrite SupplierService in the same way as DataModel
    3 pass SupplierService as dependency to AppVIew
    4 in AppView:initialize put

    serviceModel = new ServiceModel();
    supplierService = new SupplierService();
    
    serviceModel.fetch().done(function() {
       var data = serviceModel.toJSON();
    
       supplierService.figures.calculate(data)
    });