2014-12-03 1 views
2

У меня есть два блока «если меньше», которые, похоже, не работают для меня, когда я заменяю правую часть сравнения с Math.PI на мой переменная, this.bottomChainAngleRads.Javascript меньше, чем при использовании переменной для сравнения

Контекст: я оживляющий цепь между двумя передачами, и поэтому итерация по зубам двух передач, чтобы скрыть/показать свои ссылки, как они вращаются

Ранее в коде переменная инициализируется математика, а не строка.

this.bottomChainAngleRads = Math.PI + 2 * Math.atan2(...); 

Тогда я хочу сделать что-то с ним каждый раз в то время:

this.step = function() { 
    console.log('this.bottomChainAngleRads = ' + this.bottomChainAngleRads // Just over PI. Usually about 3.4. 
       + ' ' + $.isNumeric(this.bottomChainAngleRads));   // Always true. 

    // Counting the passing through each if block. Expecting a little in each. 
    var frontDisplay = 0, frontHide = 0, rearDisplay = 0, rearHide = 0; 

    $(this.frontGear.div).find('.geartooth').each(function(index, el) { 
    var totalRadians = measureRotation(el); 
    console.log('front totalRadians = ' + totalRadians + ' ' // From 0 to TWO_PI 
       + (totalRadians < this.bottomChainAngleRads)); // Always false. WTF. 
    if (totalRadians < this.bottomChainAngleRads) { // <================ FAILS. NEVER TRUE. 
    // if (totalRadians < Math.PI) { // MOSTLY CORRECT, but expectedly off by minor angle. 
     ++frontDisplay; 
     // .. do stuff 
    } else { 
     ++frontHide; 
     // .. do other stuff 
    } 
    }); 

    $(this.rearGear.div).find('.geartooth').each(function(index, el) { 
    var totalRadians = measureRotation(el); 
    console.log('rear totalRadians = ' + totalRadians + ' '  // From 0 to TWO_PI 
       + (totalRadians < this.bottomChainAngleRads)); // Always false. WTF. 
    if (totalRadians < this.bottomChainAngleRads) { // <================ FAILS. NEVER TRUE. 
    // if (totalRadians < Math.PI) { // MOSTLY CORRECT, but expectedly off by minor angle. 
     ++rearHide; 
     // .. do stuff 
    } else { 
     ++rearDisplay; 
     // .. do other stuff 
    } 
    }); 

    // Below I expected approximately a 50/50 split on each gear. Instead, I get... 
    console.log('front: ' + frontDisplay + ', ' + frontHide  // Nothing, All. 
       + '; rear: ' + rearDisplay + ', ' + rearHide); // All, Nothing 
} 

Извините за многословный код, но потому, что я чувствую, что я пытался так много вещей, я хотел бы дать большая картина.

+0

Это вопрос с объемом. 'this' внутри' .each' относится к элементу DOM, а не к вашему объекту. Используйте 'var that = this' вне' .each', а затем используйте 'that' everyree – devnull69

ответ

0

Контекст внутри each обратного вызова не Ваш экземпляр объекта больше, this указывает на отдельные элементы DOM (.geartooth), которые, очевидно, не имеют свойство bottomChainAngleRads.

Простейшим решением является сохранение правильной ссылки на контекст. Попробуйте следующее:

var self = this; 
$(this.rearGear.div).find('.geartooth').each(function(index, el) { 
    var totalRadians = measureRotation(el); 
    if (totalRadians < self.bottomChainAngleRads) { 
    ... 
}); 
+0

Спасибо. Теперь я могу остановить голову. – Anm

+0

Вы также можете использовать jQuery's [proxy()] (http://api.jquery.com/jQuery.proxy/) для установки контекстов '.each ($. Proxy (myFunction, this))'. Это особенно полезно для обработчиков событий, где удобно использовать частичные приложения, которые также обрабатывает прокси. – Sukima

+0

Пример: http://jsbin.com/hivila/1/edit?html,js,output – Sukima

Смежные вопросы