0

I've an issue in rendering the object which is not ready on the moment when the template is rendered. Thus it is rendering the empty view without databinding.

What's the correct way to use deferred objects or some other method for ensuring the databinding?

var Project = can.Model.extend({
    findOne: 'GET /v1/project?id={id}'
})
 var ProjectControl = can.Control.extend({
    selectedProject: '',
    init: function(el, options) {
        /*Get data and initialize objects*/
        var self = this;
        Models.Project.findOne({
            id: 3
        }, function(project) {
            self.selectedProject = project;
        });
    },
    'route': function() {
        /*root route*/
        $('#projectView').html(can.view('projectViewTemplate', this.selectedProject));
    }

})

var pc = new Controllers.ProjectControl('body');
can.route.ready();
window.location.hash = '#!'

I've tried initialising the selectedProject with the empty model, but this seems a bit dump way for doing it:

 new Models.Project({name:'Empty project'}, phases:[]) //Dump way for doing the databinding

Also this wont solve the problem when I need to use the sub-objects of project like project phases.

edit: I found quite awkward way for waiting the sub-object of the project. I bound the handler for the change of the model, so now even the refresh works. Is there any more elegant way for doing this?

'edit/:id route': function(data) {
    var data = data;
    var self = this;
    this.selectedProject.bind('name', function(ev) {
        $('#projectView').html(can.view(self.defaults.phaseEditProject, {
            'phase': self.selectedProject.phases[data.id],
        }));
    })
},
ramblinjan
  • 6,578
  • 3
  • 30
  • 38
Heikki Mustonen
  • 301
  • 3
  • 15

1 Answers1

1

do this:

init: function(el, options) {
    /*Get data and initialize objects*/
    var self = this;
    self.selectedProject = Models.Project.findOne({
        id: 3
    }).done(function(project) {
        self.selectedProject = project;
    });
},

Passing a deferred into can.view waits for the deferred to resolve then uses its resolved value. Subsequently, if the route changes, the project will be there in the selectedProject slot, ready to use.

air_hadoken
  • 611
  • 4
  • 5
  • Not working. This seemed to work: init: function(el, options) { var self = this; this.selectedProject.attr({ id: 3 }) Models.Project.findOne({ id: 3 }, function(project) { self.selectedProject = project; }); } – Heikki Mustonen May 20 '14 at 06:14