変数は常にオブジェクトの一部であることができ、その内容を変更する特殊な関数を使用できます。 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を常にウィンドウに設定できます。
あなたは何を試しましたか? –
getterメソッドとsetterメソッドでオブジェクトにラップし、setterでイベントをトリガーします。 –
私はあなたがこのhttp://www.codeproject.com/Articles/13914/Observer-Design-Pattern-Using-JavaScriptを見たいと思うかもしれないと思います – MilkyWayJoe