www.webdeveloper.com
Results 1 to 4 of 4

Thread: Object method on button?

  1. #1
    Join Date
    Dec 2011
    Posts
    55

    Object method on button?

    I know it's easy to call a function to activate when you click an HTML button. Is it possible to have the same thing happen with an Objects method? Such as onclick="object.method();" And if so, what is the proper way to call it? Seems nothing I try works.

  2. #2
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    The named instance of the object must exist at the time that it is installed. Can you give a full code example?

  3. #3
    Join Date
    Oct 2012
    Posts
    12
    I know it's trouble-free to describe a meaning to make active when you clack an HTML key.




    **Links removed by Site Administrator so it doesn't look like you're spamming us. Please don't post them again.**

  4. #4
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,774
    You need to bind the "this" variable to a different context, and assign the function object reference to the onclick.

    Function.prototype.bind is included in the newer versions of the ECMAScript specification, so you'll need this snippet below to support older browsers:
    Code:
    if (!Function.prototype.bind) {
    	Function.prototype.bind = function(context) {
    		var self = this;
    		var fn = function() {
    			return self.apply(context, arguments);
    		};
    
    		fn.cleanup = function() {
    			self = fn = context = null;
    		};
    
    		return fn;
    	};
    }
    And to use it:
    Code:
    var myObject = {
      doSomething: function(event) {
        var button = event.target || event.srcElement;
        // do something with button
        // "this" points to myObject
        alert(this === myObject); // alerts "true"
      }
    };
    
    var element = document.getElementById("some_id");
    element.onclick = myObject.doSomething.bind(myObject);
    Perhaps a more traditional object oriented approach:
    Code:
    function Foo(element) {
    	this.element = element;
    	this.element.onclick = this.handleClick.bind(this);
    }
    Foo.prototype = {
    	element: null,
    	
    	handleClick: function(event) {
    		var element = event.target || event.srcElement;
    		this.showButton(element);
    	},
    	
    	showButton: function(button) {
    		alert(button.nodeName + "#" + button.id);
    	}
    };
    
    var foo = new Foo(document.getElementById("some_id"));

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles