如何在jquery中调用变量中的函数赋值

时间:2016-02-19 18:47:56

标签: javascript jquery ajax

我声明了一个函数并将其赋值给一个变量,函数内部是其他函数。通常,在第一次加载页面时,它会加载函数等。当我在ajax成功回调中使用变量时,它表示init()函数不是函数。

这是我的样本jquery函数,分配给名为GRID的变量:

    var Grid = (function() {
       function init( config ) { ... }
         .
         .
         .
       function addItems( $items ) { ... }
      return { init: init, . . . addItems: addItems }
    }

();

我有一个这个ajax电话

     function updateItems{
      .
      .
      .
      .
       jQuery.ajax({

            type: 'get',
            url:  ajaxURL,
            data: ajaxData,
            dataType: 'json',

            //Ajax call is successful
            success: function ( response ) {
                //Add new posts
               Grid.init();

            },
            error: function () {

            }
        });
        .
        .
        .
        }

代码有什么问题?为什么Inspector会返回一个错误,指出 Grid.init()不是函数?请帮忙

4 个答案:

答案 0 :(得分:3)

var Grid = (function() {
   function init( config ) { ... }
     .
     .
     .
   function addItems( $items ) { ... }

   // explicitly return the functions, or properties you want to be attached to `Grid`
   return {
       init: init,
       .
       .
       .
       addItems: addItems
   }
// assuming you want this to be immediately invoked function expression
})();

答案 1 :(得分:0)

您在iife范围内定义了init,但不要将其添加为Grid的函数。

你应该做

Grid.init = function(){}

答案 2 :(得分:0)

尝试这样

var Grid = {
   init  : function( config ) { ... }
     .
     .
     .
   addItems : function( $items ) { ... }
}

你应该将init定义为Grid内的属性,该属性的值是函数的返回值,希望它有所帮助

答案 3 :(得分:0)

我试图在那里复制你的案例:JSFiddle

网格:

var Grid = (function() {
  function init(config) {
    console.log('--- INIT')
  }

  function addItems($items) {
    console.log('--- ADD ITEMS')
  }

  return { init: init, addItems: addItems };
})();

然后使用Ajax调用函数:

function updateItems() {
  jQuery.ajax({
      type: 'get',
      url:  ajaxURL,
      dataType: 'json',
      success: function(response) {
         Grid.init();
         Grid.addItems();
      }
  });
}

我称这个功能为:

updateItems();

对我来说一切都很好。控制台输出:

  

--- INIT

     

---添加项目

你能发现代码的不同吗?

您确定Grid是全局的还是与updateItems相同的范围?

相关问题