|
From: vunet on 23 Apr 2008 11:22 If I initializer my object as var obj = new SomeObject(); then I have some method inside of the object as: function SomeObject(){ ....... this.showLink = function(){ return "<a href='javascript:void(0)' onClick='obj.showMessage()'></ a>" } this.showMessage = function(){ alert("My Message is Here") } ....... } Obviously, "onClick='obj.showMessage()' " is a wrong refrence because we may call it obj2 or have multiple objects. How can I reference any function of an initialized object on click of a link? Thank you for suggestions.
From: Thomas 'PointedEars' Lahn on 23 Apr 2008 14:28 vunet wrote: > If I initializer my object as > > var obj = new SomeObject(); > > then I have some method inside of the object as: > > function SomeObject(){ > ...... > this.showLink = function(){ > return "<a href='javascript:void(0)' onClick='obj.showMessage()'></ > a>" > } > this.showMessage = function(){ alert("My Message is Here") } > ...... > } > > Obviously, "onClick='obj.showMessage()' " is a wrong refrence because > we may call it obj2 or have multiple objects. How can I reference any > function of an initialized object on click of a link? Don't use strings. And move all methods that don't require a closure to the prototype object. function isMethod(o, p) { return (o && /\s*(function|object|unknown)\s*/i.test(typeof o[p]) && o[p]); } function SomeObject() { this.showLink = function() { if (isMethod(document, "createElement")) { var a = document.createElement("a"); if (a) { a.href = "javascript:void(0)"; var me = this; var f = function(e) { me.showMessage(); if (isMethod(e, "preventDefault")) e.preventDefault(); if (typeof e.returnValue != "undefined") e.returnValue = false; return false; }; if (isMethod(a, "addEventListener")) { a.addEventListener("click", f, false); } else { a.onclick = f; } } } return a; }; } SomeObject.prototype = { constructor: SomeObject, showMessage: function(){ alert("My Message is Here") } }; That said, don't misuse `a' elements like this. > Thank you for suggestions. You're welcome. PointedEars -- var bugRiddenCrashPronePieceOfJunk = ( navigator.userAgent.indexOf('MSIE 5') != -1 && navigator.userAgent.indexOf('Mac') != -1 ) // Plone, register_function.js:16
|
Pages: 1 Prev: comp.lang.javascript FAQ - META 2008-04-23 Next: onKeyUp event not firing...or just bad code? |