在javascript中,如何在变量值改变时触发事件?

时间:2012-05-17 15:30:41

标签: javascript

我有两个变量:

var trafficLightIsGreen = false; 
var someoneIsRunningTheLight = false;

当两个变量符合我的条件时,我想触发一个事件:

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

假设这两个布尔值可以在任何时刻发生变化,当我们根据我的条件改变时,如何触发go()方法呢?

7 个答案:

答案 0 :(得分:30)

在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); }
  };
}

现在你可以调用这个函数并链接回调来执行 go()

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

traffic.setIsGreen(true);

答案 1 :(得分:2)

//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);

答案 2 :(得分:1)

最可靠的方法是使用这样的setter:

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(); 
    };
};

然后您只需调用setter:

,而不是为变量赋值
setTrafficLightIsGreen(true);

答案 3 :(得分:0)

如果不使用setInterval/Timeout进行投票,则无法执行此操作。

如果您只支持Firefox,则可以使用https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/watch

当对象的属性发生变化时,它将告诉您。

你最好的解决方案可能是让它们成为一个对象的一部分并添加你自己可以发送通知的getter,setter,正如JaredPar在他的回答中所示

答案 4 :(得分: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);

答案 5 :(得分:0)

您始终可以将变量作为对象的一部分,然后使用特殊函数来修改它的内容。或通过window访问它们。

只要您使用格式changeIndex(myVars, 'variable', 5);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设置为窗口。

答案 6 :(得分:0)

如果你愿意在两次检查之间有大约1毫秒的延迟,你可以放置

window.setInterval()

就此而言,例如,这不会让您的浏览器崩溃:

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