31

我有两个变量:

var trafficLightIsGreen = false; 
var someoneIsRunningTheLight = false;

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

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

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

4

7 回答 7

37

在 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);
于 2012-05-17T15:35:59.377 回答
2

最可靠的方法是使用这样的设置器:

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);
于 2012-05-17T15:38:38.457 回答
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);
于 2015-02-11T05:20:44.267 回答
0

如果不使用轮询,就没有办法做到这一点setInterval/Timeout

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

它将告诉您对象的属性何时更改。

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

于 2012-05-17T15:34:24.623 回答
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);
于 2012-05-17T15:37:35.037 回答
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 设置为窗口。

于 2014-07-24T14:28:52.893 回答
0

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

window.setInterval()

例如,这不会使您的浏览器崩溃:

window.setInterval(function() {
    if (trafficLightIsGreen && !someoneIsRunningTheLight) {
        go();
    }
}, 1);
于 2014-11-15T14:23:37.120 回答