Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Назначить на обработчик события метод обьекта (https://javascript.ru/forum/misc/4054-naznachit-na-obrabotchik-sobytiya-metod-obekta.html)

Logo 18.06.2009 11:06

Назначить на обработчик события метод обьекта
 
В конструкторе, при создании обьекта определенному диву надо назначить обработчик события onclick. По onclick должен вызываться метод созданного объекта. Как это сделать? У меня метод хотя и вызывается, но не у созданного объекта, а сам по себе, а свойства объекта равны undefined

Kolyaj 18.06.2009 11:08

http://javascript.ru/tutorial/object/thiskeyword

Лучше всего в своих функциях установки событий добавить возможность передавать scope, в котором будут вызываться обработчики.

Riim 18.06.2009 11:10

Заверни обработчик в функцию, и в ней вызывай его в нужном контексте.

Logo 18.06.2009 11:48

Цитата:

Заверни обработчик в функцию, и в ней вызывай его в нужном контексте.
Не помогает, если я правильно понял конечно, через call тоже.
Вот простенький пример, иллюстрирующий проблему
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Пример</title>
<style type="text/css">
#button {background:#f00; color:#fff; font-weight:bold; padding:3px 5px; cursor:pointer; float:left}
</style>
<script type="text/javascript">
window.onload= function() {
obj= new myclass(document.getElementById('button'))
}
function myclass(objref) {
	this.message="Я обект, тарм-пам пам"
	this.obj=objref
	myclass.prototype.helloworld = function() {
		alert(this.message) //Должен при клике на кнопку сказать 'Я обект, тарм-пам пам', а сообщает undefined
	}
	
	this.obj.onclick=this.helloworld;
	//this.obj.onclick=this.helloworld.call(this); 
	//this.obj.onclick=function() {this.helloworld()}; 
	//this.obj.onclick=myclass.prototype.helloworld.call(this); //- это все тоже не работает
}
</script>
</head>
<body>
<div id="button">нажмии меня</div>
</body>
</html>

Kolyaj 18.06.2009 11:54

function myclass(objref) {
    var that = this;
    this.message="Я обект, тарм-пам пам"
    this.obj=objref
    this.helloworld = function() {
        alert(that.message) //Должен при клике на кнопку сказать 'Я обект, тарм-пам пам', а сообщает undefined
    }
 
    this.obj.onclick=this.helloworld;
    //this.obj.onclick=this.helloworld.call(this); 
    //this.obj.onclick=function() {this.helloworld()}; 
    //this.obj.onclick=myclass.prototype.helloworld.call(this); //- это все тоже не работает
}


И весь раздел до кучи http://javascript.ru/tutorial/object

Riim 18.06.2009 11:54

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Пример</title>
<style type="text/css">
#button {background:#f00; color:#fff; font-weight:bold; padding:3px 5px; cursor:pointer; float:left}
</style>
<script type="text/javascript">
window.onload = function() {
	new myclass(document.getElementById('button'));
};
function myclass(objref) {
    this.message = "Я обект, тарм-пам пам";
    this.obj = objref;
	var self = this;
    this.obj.onclick = function() {
		self.helloworld();
	};
}

myclass.prototype.helloworld = function() {
    alert(this.message) //Должен при клике на кнопку сказать 'Я обект, тарм-пам пам', а сообщает undefined
};
</script>
</head>
<body>
<div id="button">нажмии меня</div>
</body>
</html>

Logo 18.06.2009 13:06

Спасибо, работает. Но дальше новая проблема. В методе объекта вызываю setInterval, в качестве функции к которой метод того же объекта. Но почему-то, независимо от того в каком объекте ставится setInterval, в качестве функции в нее попадает метод последнего объекта. Вот пример
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Пример</title>
<style type="text/css">
#button, #button2 {background:#f00; color:#fff; font-weight:bold; padding:3px 5px; cursor:pointer; float:left; position:relative}
#button2 {background:#f80;}
</style>
<script type="text/javascript">
window.onload= function() {
	obj= new myclass(document.getElementById('button'))
	obj2= new myclass(document.getElementById('button2'))
}
function myclass(objref, message) {
	this.message=message
	this.obj=objref
	var self = this;
	
	this.offset=0
	this.timer = 0
	this.intervalref
	myclass.prototype.animate = function() {		
		if(this.timer==0) {
			this.intervalref=setInterval(function() {self.animate()}, 5) //при клике кнопка должна плавно съехать вниз на30 px. Правая так и делает, но при
			this.timer= 30 / 3											//нажатии на левую self.animate() вызывает obj2.animate() вместо своей obj.animate()
		} else {
			this.offset+= 3;
			this.obj.style.top=this.offset+'px'		
			this.timer--
		}	
		if(this.timer==0) {
			clearInterval(this.intervalref)	
		}
	}
	

    this.obj.onclick = function() {self.animate()}; 
}
</script>
</head>
<body>
<div id="button">нажмии меня</div>
<div id="button2">нажмии меня 2</div>
</body>
</html>

Kolyaj 18.06.2009 13:14

Цитата:

Сообщение от Logo
Но почему-то, независимо от того в каком объекте ставится setInterval, в качестве функции в нее попадает метод последнего объекта.

Потому что не надо в конструкторе добавлять методы в prototype. Вы ссылку про объекты/наследование почитайте, у вас недопонимание.

Logo 18.06.2009 14:23

Фух, наконец то получилось. Сразу не заметил ваше сообщение. В общем получилось решить задачу, скрестив ваш метод и Riim. А слова prototype я все из своего скрипта повырезал.
Рабочий пример
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Пример</title>
<style type="text/css">
#button, #button2 {background:#f00; color:#fff; font-weight:bold; padding:3px 5px; cursor:pointer; float:left; position:relative}
#button2 {background:#f80;}
</style>
<script type="text/javascript">
window.onload= function() {
	obj= new myclass(document.getElementById('button'))
	obj2= new myclass(document.getElementById('button2'))
}
function myclass(objref, message) {
	this.message=message
	this.obj=objref
	var self = this;
	
	this.changecontent = function () {
	    this.obj.innerHTML=this.obj.innerHTML+' :)'
		this.animate()	
	}
	this.animate = function() {		
		if(this.timer==0) {
			this.intervalref=setInterval(function() {self.animate()}, 5)
			this.timer= 30 / 3
		} else {
			this.offset+= 3;
			this.obj.style.top=this.offset+'px'		
			this.timer--
		}	
		if(this.timer==0) {
			clearInterval(this.intervalref)	
		}
	}
		
	this.offset=0
	this.timer = 0
	this.intervalref
    this.obj.onclick = function() {self.changecontent()}; 
}	
</script>
</head>
<body>
<div id="button">нажмии меня</div>
<div id="button2">нажмии меня 2</div>
</body>
</html>

x-yuri 20.06.2009 06:43

я бы действительно скрестил: вынес все методы в прототип (а что сейчас от варианта Riim я хз)


Часовой пояс GMT +3, время: 10:10.