Search code examples
famo.us

How to remove EventListener?


In the documentation it s given that removeListener -- /famous/core/Surface.js

removeListener (type, fn) 
Unbind an event by type and handler. This undoes the work of 'on'

So what I want to accomplish is.. There are four surfaces, when I click one, it removes click action from other three, so the user will not be able to click them.

removeEventListener('click', function() {
   console.log("removed"); 
});

What is wrong I am doing? Thanks.


Solution

  • To get the surface that was clicked in a Famo.us event you can use e.origin. You can then use this surface to compare against all surfaces and unbind the events accordingly. To properly use removeListener, you want to pass it the event type, as well as the function you wish to remove.

    Here is a full example or what you described. If you click on one of the squares, it becomes the only square that is further clickable.

    Hope this helps!

    var Engine          = require("famous/core/Engine");
    var Surface         = require("famous/core/Surface");
    var Transform       = require("famous/core/Transform");
    var StateModifer    = require("famous/modifiers/StateModifier");
    
    var context = Engine.createContext();
    
    var surfaces = [];
    
    var handleClick = function(e){
    
        var count = parseInt(e.origin.getContent()) + 1 ;
        e.origin.setContent(count);
    
        for (var i = 0; i < surfaces.length; i++) {
            var surface = surfaces[i];
            if (surface != e.origin) {
                surface.removeListener('click',handleClick);
            };
        };
    
    }
    
    var colors = ["red","green","blue","purple"];
    
    for (var i = 0; i < 4; i++) {
        var surface = new Surface({
            size:[100,100],
            content: "0",
            properties: {
                backgroundColor: colors[i],
                color: 'white',
                lineHeight:'100px',
                textAlign:'center'
            }
        })
    
        surface.state = new StateModifer({
            transform:Transform.translate(0,i*100,0)
        })
    
    
        surface.on("click",handleClick);
    
        surfaces.push(surface);
    
        context.add(surface.state).add(surface);
    
    };