2012-05-17 27 views
18

私は2つの変数があります。私は2つの変数が私の条件に同意したときにイベントをトリガしたいjavascriptでは、変数の値が変更されたときにイベントをトリガする方法は?

var trafficLightIsGreen = false; 
var someoneIsRunningTheLight = false; 

を:これら二つの真偽値が任意の時点で変更できると仮定すると

if(trafficLightIsGreen && !someoneIsRunningTheLight){ 
    go(); 
} 

、どのようにすることができます自分の条件に応じて変更すると私のgo()メソッドがトリガされますか?

+1

あなたは何を試しましたか? –

+0

getterメソッドとsetterメソッドでオブジェクトにラップし、setterでイベントをトリガーします。 –

+1

私はあなたがこのhttp://www.codeproject.com/Articles/13914/Observer-Design-Pattern-Using-JavaScriptを見たいと思うかもしれないと思います – MilkyWayJoe

答えて

27

Javascriptで変更されました。あなたができることは、特定の値をラップし、値を変更するために呼び出されたときにイベントを生成する一連の関数を提供することです。

function Create(callback) { 
    var isGreen = false; 
    var isRunning = false; 
    return { 
    getIsGreen : function() { return isGreen; }, 
    setIsGreen : function(p) { isGreen = p; callback(isGreen, isRunning); }, 
    getIsRunning : function() { return isRunning; }, 
    setIsRunning : function(p) { isRunning = p; callback(isGreen, isRunning); } 
    }; 
} 

今、あなたは、この関数を呼び出すと、(行くを実行するコールバックをリンク)できます

var traffic = Create(function(isGreen, isRunning) { 
    if (isGreen && !isRunning) { 
    go(); 
    } 
}); 

traffic.setIsGreen(true); 
+0

+1私はちょうど入力し始めました:)すばらしい答え! –

0

setInterval/Timeoutでポーリングせずに行う方法はありません。あなただけのFirefoxをサポートできる場合

、オブジェクトのプロパティが変更されたことを教えてくれますhttps://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/watch

を使用することができます。 JaredParは彼の答えに示したよう

あなたの最善の解決策は、おそらく、あなたが通知を自分で出すことができセッター、それらをオブジェクトの一部を作り、ゲッターを追加された値がある場合に発生するイベントがない

0
function should_i_go_now() { 
    if(trafficLightIsGreen && !someoneIsRunningTheLight) { 
     go(); 
    } else { 
     setTimeout(function(){ 
      should_i_go_now(); 
     },30); 
    } 
} 
setTimeout(function(){ 
    should_i_go_now(); 
},30); 
1

最も信頼できる方法は、そのようにセッターを使用することです:

var trafficLightIsGreen = false; 
var someoneIsRunningTheLight = false; 

var setTrafficLightIsGreen = function(val){ 
    trafficLightIsGreen = val; 
    if (trafficLightIsGreen and !someoneIsRunningTheLight){ 
     go(); 
    }; 
}; 
var setSomeoneIsRunningTheLight = function(val){ 
    trafficLightIsGreen = val; 
    if (trafficLightIsGreen and !someoneIsRunningTheLight){ 
     go(); 
    }; 
}; 

変数に値を代入するのではなく、セッターを呼び出すだけです:

setTrafficLightIsGreen(true); 
0

変数は常にオブジェクトの一部であることができ、その内容を変更する特殊な関数を使用できます。 windowでアクセスしてください。値が限りvariable = 5;に比べて、あなたは形式changeIndex(myVars, 'variable', 5);を使用するように変更された場合

次のコードは、カスタムイベントを発生するために使用することができ

例:あなたは常に引っ張るしたい場合

function changeIndex(obj, prop, value, orgProp) { 
    if(typeof prop == 'string') { // Check to see if the prop is a string (first run) 
     return changeIndex(obj, prop.split('.'), value, prop); 
    } else if (prop.length === 1 && value !== undefined && 
       typeof obj[prop[0]] === typeof value) { 
     // Check to see if the value of the passed argument matches the type of the current value 
     // Send custom event that the value has changed 
     var event = new CustomEvent('valueChanged', {'detail': { 
                  prop : orgProp, 
                  oldValue : obj[prop[0]], 
                  newValue : value 
                 } 
                }); 
     window.dispatchEvent(event); // Send the custom event to the window 
     return obj[prop[0]] = value; // Set the value 
    } else if(value === undefined || typeof obj[prop[0]] !== typeof value) { 
     return; 
    } else { 
     // Recurse through the prop to get the correct property to change 
     return changeIndex(obj[prop[0]], prop.slice(1), value); 
    } 
}; 
window.addEventListener('valueChanged', function(e) { 
    console.log("The value has changed for: " + e.detail.prop); 
}); 
var myVars = {}; 
myVars.trafficLightIsGreen = false; 
myVars.someoneIsRunningTheLight = false; 
myVars.driverName = "John"; 

changeIndex(myVars, 'driverName', "Paul"); // The value has changed for: driverName 
changeIndex(myVars, 'trafficLightIsGreen', true); // The value has changed for: traggicIsGreen 
changeIndex(myVars, 'trafficLightIsGreen', 'false'); // Error. Doesn't set any value 

var carname = "Pontiac"; 
var carNumber = 4; 
changeIndex(window, 'carname', "Honda"); // The value has changed for: carname 
changeIndex(window, 'carNumber', 4); // The value has changed for: carNumber 

windowオブジェクトからchangeIndexを変更すると、objを常にウィンドウに設定できます。

0

あなたがチェック間の1ミリ秒の遅延について持って喜んでいた場合、あなたはたとえば、これはブラウザがクラッシュすることはありません、それに

window.setInterval() 

を置くことができます:

window.setInterval(function() { 
    if (trafficLightIsGreen && !someoneIsRunningTheLight) { 
     go(); 
    } 
}, 1); 
+1

ゲッターとセッターの代わりに 'setInterval'を使用すると、これは良いコーディング手法でしょうか? – lowtechsun

1
//ex: 
/* 
var x1 = {currentStatus:undefined}; 
your need is x1.currentStatus value is change trigger event ? 
below the code is use try it. 
*/ 
function statusChange(){ 
    console.log("x1.currentStatus_value_is_changed"+x1.eventCurrentStatus); 
}; 

var x1 = { 
    eventCurrentStatus:undefined, 
    get currentStatus(){ 
     return this.eventCurrentStatus; 
    }, 
    set currentStatus(val){ 
     this.eventCurrentStatus=val; 
    } 
}; 
console.log("eventCurrentStatus = "+ x1.eventCurrentStatus); 
x1.currentStatus="create" 
console.log("eventCurrentStatus = "+ x1.eventCurrentStatus); 
x1.currentStatus="edit" 
console.log("eventCurrentStatus = "+ x1.eventCurrentStatus); 
console.log("currentStatus = "+ x1.currentStatus); 
関連する問題