Search code examples
javascriptjquerycubism.js

Pass parameters to javascript functions which is bind to events


I have a function like this :

 var that = this;
 this.context.on('focus', function(i) {
     var htmlElement = ele;
     var style = {left: 'auto', color: '#000000'};

     if(i !== null) {
         i = that.context.size()/2;
         style.left = i + 'px';
         //find htmlElement in DOM and apply style to it
     }
});

The htmlElement and style will var for me in different calls. I need to pass an option such as

var options = {style: someVaue, htmlELement: somelement}

to the function so that it could be called multiple times with different options. If I pass the options like this :

var that = this;
this.context.on('focus', function(i, options) {
    //use options.style and options.htmlElement 
});

It doesn't work that way. Clearly I am doing something wrong since the function bind to focus event of this.context has i as an param but can't accept any other param. Any kind of help/suggestion is appreciated.


Solution

  • I think I have worked out a solution. Thanks everyone for their help. Here is how the options could be passed:

    var that = this;
    this.context.on('focus', function(i) {
        var options = {i: i, style: someValue, htmlElement: someElement};
        that.setStyle(options);
    });
    
    setStyle: function(options) {
        var htmlElement = options.htmlElement;
        var style = options.style;
    
        if(options.i !== null) {
            options.i = that.context.size()/2;
            style.left = i + 'px';
            //find htmlElement in DOM and apply style to it
        }
    }
    

    Please feel free to comment!!!