使用Require.js调用函数

时间:2014-06-25 14:59:56

标签: jquery backbone.js requirejs

我有一个名为navigationView的JavaScript文件,如下所示:

define(['underscore', 'backbone'], function (_, Backbone) {
function navigationBuild() {
    $.ajax({
        async: false,
        url: "http://myapi/articles/categories",
        type: "GET",
        headers: { "Accept": "application/json;odata=verbose" },
        success: function (data) {

            // Append values to Navigation
            $.each(data, function (navigationindex, navigationvalue) {
                $('nav').append('<a href="#/' + navigationvalue.shortName + '">' + navigationvalue.displayName + '</a> ');
            });
        }
    });
}
});

我试图用Require.js调用它,以便每个页面都加载它。这构建了我的导航。这是我的app.js,我尝试进行函数调用,但它给出了一个错误“Uncaught TypeError:无法读取未定义的属性'navigationBuild'”。我怀疑我的navigationView文件中需要返回值。

require.config({
paths: {
    jquery: "libs/jquery-2.1.0.min",
    underscore: "libs/underscore-min",
    backbone: "libs/backbone-min",
    navigation: "views/navigationView"
},
shim: {
    underscore: {
        exports: "_"
    },
    backbone: {
        deps: ['underscore', 'jquery'],
        exports: 'Backbone'
    },
}
});

require(['navigation'], function(navigation) {
navigation.navigationBuild();
});

require(['routers/siteRouter'], function (router) {
new router;
 });

如何使用Require.js从JavaScript文件调用函数?

1 个答案:

答案 0 :(得分:1)

在您的navigation.js文件中,您不会返回任何内容。修改它,以便将函数分配给变量并返回该变量。

例如

define(['underscore', 'backbone'], function (_, Backbone) {
   var navigationBuild = function () {
    $.ajax({
        async: false,
        url: "http://myapi/articles/categories",
        type: "GET",
        headers: { "Accept": "application/json;odata=verbose" },
        success: function (data) {

            // Append values to Navigation
            $.each(data, function (navigationindex, navigationvalue) {
                $('nav').append('<a href="#/' + navigationvalue.shortName + '">' + navigationvalue.displayName + '</a> ');
            });
        }
    });
}

return navigationBuild;
});




require(['navigation'], function(navigation) {
   navigation();
});

这就是说它可能更整洁,更灵活,而是返回一个有方法的对象,例如

define(['underscore', 'backbone'], function (_, Backbone) {
  var navObj = {
     build: function () {
       ....
      }
   };


  return navObj;

});

require(['navigation'], function(navigation) {
   navigation.build();
})