2013-04-29 3 views
1

Этот код создает бесконечный цикл для второго вызова диалога, если строка 99 раскоментирована. Я не понимаю, почему. Очевидно, это потому, что в строке 95 «myCallback» получает «save.callback» ниже и поэтому вызывается от себя. Но почему это не перезаписывается тем, что происходит от опций?callback создает бесконечный цикл

Как исправить этот код?

Вот рабочий пример на jsfiddle: http://jsfiddle.net/JvcnG/

Вот код:

function Sandbox() { 
    // turning arguments into an array 
    var args = Array.prototype.slice.call(arguments), 
     // the last argument is the callback 
     callback = args.pop(), 
     // modules can be passed as an array or as individual parameters 
     modules = (args[0] && "string" === typeof args[0]) ? args : args[0], 
     i; 

    // make sure the function is called 
    // as a constructor 
    if (!(this instanceof Sandbox)) { 
     return new Sandbox(modules, callback); 
    } 

    // add properties to 'this' as needed: 
    this.a = 1; 
    this.b = 2; 

    // now add modules to the core 'this' object 
    // no modules or "*" both mean "use all modules" 
    if (!modules || '*' === modules) { 
     modules = []; 
     for (i in Sandbox.modules) { 
      if (Sandbox.modules.hasOwnProperty(i)) { 
       modules.push(i); 
      } 
     } 
    } 

    // initialize the required modules 
    for (i = 0; i < modules.length; i += 1) { 
     Sandbox.modules[modules[i]](this); 
    } 

    // call the callback 
    callback(this); 

    // any prototype properties as needed 
    Sandbox.prototype = { 
     name: "Sandbox", 
     version: "1.0", 
     getName: function() { 
      return this.name; 
     } 
    } 
}; 

var box = {}; 

Sandbox.modules = {}; 

Sandbox.modules.news = function (box) { 
    var box = box || {}, 
    dialog = null; 

    box.removeDialog = function (object) { 
     var dialog = object || box.dialog; 
     dialog.remove(); 
    }; 

    box.getEntries = function (options) { 
     var color = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')'; 
     $('#main').css('color', color); 
    }; 

    box.editEntry = function (options) { 
     var triggerElement = options.triggerElement 
     save = options.save; 

     triggerElement.live('click', function() { 
      box.displayDialog({ 
       save: save 
      }); 
     }); 
    }; 

    box.displayDialog = function (options) { 
     var save = options.save || null, 
      dialog = $('<div id="dialog-modal">loading</div>'); 

     box.dialog = dialog; 

     dialog.html('<button id="save" class="save">Save</button>') 
      .dialog({ 
      modal: true, 
      autoOpen: false, 
      height: 'auto', 
      position: 'top' 
     }).dialog('open'); 

     // do we have a save function? 
     if (null != save) { 
      var buttonSave = $('button.save', dialog); 
      myCallback = save.callback; 
      save.callback = function() { 
       box.removeDialog(dialog); 
       if (myCallback != undefined && typeof myCallback == 'function') { 
        //myCallback(); // creates an endless loop 
       } 
      }; 

      buttonSave.on('click', function() { 
       box.updateData(save); 
      }); 
     } 
    }; 

    box.updateData = function (options) { 
     var callback = options.callback; 
     $('#footer').append('<p>ok</p>'); 
     if (callback != undefined && typeof callback == 'function') { 
      callback(); 
     } 
    } 
} 

// page ready 
$.ready(
Sandbox(['news'], function (box) { 
    var getEntries = function() { 
     box.getEntries(); 
    }; 
    box.getEntries(); 

    box.editEntry({ 
     triggerElement: $('#main'), 
     save: { 
      callback: getEntries 
     } 
    }); 
})); 
+0

Я раскомментировать код на линии 99 и я в состоянии открыть диалоги несколько раз, по крайней мере, в Chrome. Есть ли дополнительная информация, которую вы могли бы дать нам, чтобы помочь решить проблему? –

+0

У меня эта проблема в Firefox 20.0 - Windows и Ubuntu, а также в Internet Explorer. Если «console.log (myCallback)» перед строкой 99, она выдает функцию [бесконечное время]. Я могу щелкнуть это в firebug и приземлиться в строке 98. – DarsVaeda

+0

В Chrome действие сохранения происходит очень медленно после второго вызова. Но он все еще работает, очевидно, Chrome предотвращает бесконечные циклы и просто отменяет запросы молча. – DarsVaeda

ответ

0

Я нашел проблему! Это просто опечатка. Вместо «,» я написал «;» позволяя «myCallback» попасть в глобальную область видимости ...

Это:

// do we have a save function? 
if (null != save) { 
    var buttonSave = $('button.save', dialog); 
    myCallback = save.callback; 
    save.callback = function() { 
     box.removeDialog(dialog); 
     if (myCallback != undefined && typeof myCallback == 'function') { 
      //myCallback(); // creates an endless loop 
     } 
    }; 

    buttonSave.on('click', function() { 
     box.updateData(save); 
    }); 
} 

Должен быть заменен следующим образом:

// do we have a save function? 
if (null != save) { 
    var buttonSave = $('button.save', dialog), 
    myCallback = save.callback; 
    save.callback = function() { 
     box.removeDialog(dialog); 
     if (myCallback != undefined && typeof myCallback == 'function') { 
      //myCallback(); // creates an endless loop 
     } 
    }; 

    buttonSave.on('click', function() { 
     box.updateData(save); 
    }); 
} 
Смежные вопросы