开发者

JavaScript objects listening to changes in Array

I would like to have an array dynamically generated by keypress, then have different JavaScript objects listening to changes in that array. For example, in games, pressing LEFT/RIGHT/UP/DOWN would 开发者_高级运维store those 4 values in the array, which can be executed by different objects listening in to that array.

Is this a good approach? And if it is, how to go about setting up listeners to that array?


You're probably not looking into using a simple Array, but your custom implementation that applies the Observer pattern. The other (bad) alternative would be to poll changes to the array with a timer, but that doesn't seem feasible for a game.

Actually, since you're writing a game, I would assume that you'll have a game loop that runs on a timer. Each interested object could simply read from the array in each update cycle. There is probably no need to push real-time changes to these objects. Unless, of course, you can't afford to lose any key strokes -- in which case you could buffer the keys in a more complex structure than a simple Array.


How about setting up register functions for each keypress?

var keyArray = [];
function addkey(key) {
    arr.push(key);
    dispatch();
}
$(document).keydown(function(e){
    addkey(e.which);
})
function dispatch() {
    /* CODE */
}


I would recommend a messaging queue model. Have a central MessageQueue that takes events and notifies listeners. Objects that want to do something on certain key presses can register themselves as listeners with the queue, and will be notified when the thing they care about happens.

Let's say you have a predefined set of events "UP", "DOWN", "LEFT", and "RIGHT" events.

var MESSAGE_QUEUE = function() {

    var eventListeners = {
        UP: [],
        DOWN: [],
        LEFT: [],
        RIGHT: []
    };

    return {

        register: function(event, obj) {
            var listeners = eventListeners[event];
            if (listeners) {
                listeners.push(obj);
            }
        },

        fire: function(event) {
            var listeners = eventListeners[event] || [];
            for (var i=0; i<listeners.length; i++) {
                listeners[i].onEvent(event);
            }
        }
    };
}();

Then an object that wants to be notified on DOWN says:

MESSAGE_QUEUE.register("DOWN", this);

this would be expected to defined an onEvent function. Then whatever fires key events:

element.onKeyPress = function(event) {
    // ... figure out if down was presses
    MESSAGE_QUEUE.fire("DOWN");
}

Something like that would be a clean solution. Clearly this could be changed to suit whatever needs you have, such as a variable number of events, or more clear function names, such as onDown, onUp, etc., defined for each listener.


Check out JavaScriptMVC's observe:

https://github.com/jupiterjs/jquerymx/blob/master/lang/observe/observe.js

It does what you are looking for:

o = new Observe.List([])
o.bind('change', function(ev, attr, how , newValue, oldValue ){

})

o.push('hello')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜