Error in instantiating canjs controller using requirejs

341 Views Asked by At

I am using canjs and require js to create a mvc application. I am new to both of them.

I have created a base js class --home.php and loaded jquery, canjs and requirejs in home.php.

I have two separate folders named controller and model

in the model - home_m.js i have the following code

var Description = can.Model.extend({
    findAll: 'GET ../webService/ajax/ajax_router.php?q=desc',
    create: 'POST ../webService/ajax/ajax_router.php',
    update: 'PUT ../webService/ajax/ajax_router.php/{id}',
    destroy: 'DELETE ../webService/ajax/ajax_router.php/{id}'
}, {});

In controller i have home_c.js file. The code is as follows

require(['../model/home_m'], function(homeModel){

  var Descriptions = can.Control.extend({
    'init': function(element, options){
        var self = this;
        console.log(self);
         Description.findAll({}, function(des){
             console.log(des);
         });
      }
  });
});

And at last in home.js I have this code

require(['../controller/home_c'], function(m, c) {
 new Descriptions('#abc', {});
});

But this gives the error -

What am I doing wrong.

ReferenceError: Descriptions is not defined

If i declare a var a = 5 in the controller/home_c.js and try to alert the value of a in home.js file then its working. Is there any problem with the canjs code?

Thanks

1

There are 1 best solutions below

1
On BEST ANSWER

This is not a CanJS problem but more how AMD (and RequireJS works). If you define your models and controls like this:

// models/home_m.js
define(['can/model'], function(Model) {
    return Model.extend({
        findAll: 'GET ../webService/ajax/ajax_router.php?q=desc',
        create: 'POST ../webService/ajax/ajax_router.php',
        update: 'PUT ../webService/ajax/ajax_router.php/{id}',
        destroy: 'DELETE ../webService/ajax/ajax_router.php/{id}'
    }, {}); 
});

// controller/home_c.js
define(['can/control', '../model/home_m'], function(Control, homeModel){
  return Control.extend({
    'init': function(element, options){
        var self = this;
        console.log(self);
         Description.findAll({}, function(des){
             console.log(des);
         });
      }
  });
});

// home.js
require(['../controller/home_c'], function(Descriptions) {
 new Descriptions('#abc', {});
});

Things should work the way they are supposed to.