javascriptjsonrequirejscanjscanjs-model

can-model cannot getting data from .json file


I am trying to implement MVC using AMD in canjs. For that I am using requirejs. This is my domains.json file:

[            
"1":{"uid":     "1","urls": "domain1.abc.com"},
"2":{"uid":    "2","urls": "domain2.abc.com"},
"3":{"uid":    "3","urls": "domain3.abc.com"}
]

This is my domainModel:

define(['can'], function(can){
  SearchModel= can.Model({
     id: 'uid',
     findAll: 'GET /domains.json'
  },{})
  return SearchModel;
})

This is my controller:

define(['can','jquery'],function(can,$){
 domainController=can.Control({defaults:{view:"../view/search.hbs" }},           
  {
    init : function(element,options){   
        this.element.html(can.view(this.options.view,{
            searchlist : this.options.search
        }))
    }
});
return domainController;
} 

This is my main js:

equirejs(['can','controller/domainController','model/domainModel'],
 function(can, domainController,domainModel) {
   var Application = can.Control.extend({
    defaults :{ }
   },{  
        init: function(element,options){
         console.log('loaded');
         domainModel.findAll({}, function(domains){
            domainObject:{searchdomains : domains}
                 new domainController('#search',domainObject)
            });
        }
    })
return Application;
});

I am tracing out my code.I put breakpoints.On model breakpoints I am not getting values in local variables in chrome devtools.

The url property has 'undefined/{id}' value and findAll method having four properties i.e. arguments,caller,length and name having a value null, null, 0 and "" respectively

I have checked my url of model by navigating through localhost on browser and it is correct. Then why model cannot getting the values of json file?


Solution

  • You should get an error message since your data is not what Model expects for findAll. Your JSON should be an array (or at least have a length property):

    [
      {"uid":     "1","urls": "domain1.abc.com"},
      {"uid":    "2","urls": "domain2.abc.com"},
      {"uid":    "3","urls": "domain3.abc.com"}
    ]
    

    You also probably want to set the id property in you SearchModel to uid:

    define(['can'], function(can){
      SearchModel= can.Model({
         id: 'uid',
         findAll: 'GET /domains.json'
      },{})
      return SearchModel;
    })