optical rotary encoders have two photodetectors next to each other to detect the direction of the encoder wheel as well as the pulse count. one detector will sink current slightly before the other, depending on direction.
an rs flip flop gets signals from both detectors. the and gate provides the clock. the two nand gates then direct the clock to either up or down inputs on the counter depending on which detector was first.