Bound JS Object to Element

Shows how data attribute can be a reference to the JS object

by Ben Clayton

HTML

<div id="test">CLICK to run method on all objects found by jQuery selector</div><br/><br/>
<div id="frame"></div>

CSS

body,input {font-family:arial;font-size:12px;}

#test {cursor:pointer;}

JavaScript

function myobject(cfg){
    this.cfg = cfg || {};
    
    //properties
    this.colour=this.cfg.colour || 'Red';
    
    this.jdomref=null;
    
    //methods
    this.render = function (){
        var c=$("<button>Click "+this.colour+"</button><br/>");   
        this.jdomref =$(c).appendTo("#frame");// put jquery refence to element back on object
        this.jdomref.addClass('mybutton');
        this.jdomref.data('obj',this);// attach reference to object to dom element using data attribute
        var p=this;
        this.jdomref.on('click',function(){
            // Method 1:
            // var o = $(this).data('obj');
            // o.myclick();
            
            // Method 2:
            p.myclick()
        });
    }
    this.myclick = function(){
        alert('Colour:'+this.colour)
    }
    this.changeLable = function(){
        this.jdomref.html("Colour "+this.colour.toUpperCase());
    }
    
    return this;
}
//==================================================================================

    
    var obja = new myobject().render();
    var objb = new myobject({colour:'Black'}).render();
    var objc = new myobject({colour:'Silver'}).render();
 
   $('#test').on('click',function(){
       debugger;
       $('.mybutton').each(function(){
           $(this).data('obj').changeLable()
       });
   });