canjscanjs-model

canjs findOne deferred


I learned that instead of using model.findAll and write code in call back function of findAll we can achieve same by using new model.List({}). E.g., jsfiddle --> http://jsfiddle.net/CRZXH/48/ .. in this jsfiddle example List implementation works but findOne fails.

   var people = new Person.List({});

        return can.Component({
            tag: 'people',
            template: initView,
            scope: {
                people: people
                }
        })

Above example works fine, initially people is assigned with empty object but after ajax call complete people variable is updated with list and view updates on its own.

How to achieve the same in case of findOne?

 var person = PersonModel.findOne({});

    can.Component({
        tag: 'person',
        template: initView,
        scope: person
    })

This fails....

I did work around as below :

 var person;
    PersonModel.findOne({},function(data){
      person = data
    });

    can.Component({
        tag: 'person',
        template: initView,
        scope: person
    })

This works only if I add asyn=false in findeOne ajax call.


Solution

  • I got solution for this problem from http://webchat.freenode.net/ @daffl

    Solution : http://jsfiddle.net/CRZXH/49/

    can.Model.extend('Person', {
        findOne: 'GET api/metadata',
        getMetadata: function() {
            var result = new Person();
            Person.findOne().then(function(data) {
                result.attr(data.attr(), true);
            });
            return result;
        }
    }, {});
    // Person component which uses findOne
    can.Component({
        tag: 'person',
        scope: function() {
            return {
                person: Person.getMetadata()
            }
        }
    })