Navigacija
Lista poslednjih: 16, 32, 64, 128 poruka.

document.onclick = this.mouse; i onda ne vidi this iz klase! Zasto?

[es] :: Javascript i AJAX :: document.onclick = this.mouse; i onda ne vidi this iz klase! Zasto?

[ Pregleda: 3177 | Odgovora: 8 ] > FB > Twit

Postavi temu Odgovori

Autor

Pretraga teme: Traži
Markiranje Štampanje RSS

MilosDj
Milos Djuric
Belgrade

Član broj: 14174
Poruke: 307
*.dynamic.isp.telekom.rs.



+4 Profil

icon document.onclick = this.mouse; i onda ne vidi this iz klase! Zasto?21.10.2010. u 17:10 - pre 163 meseci
Kao sto naslov kaze:
Code:
function Nesto(){

this.init = function()
 {
 document.onclick = this.mouse;
 }


this.mouse(e)
 {
 this.var; -- ne radi
 this.f(); -- ne radi

 nesto.var; -- radi
 nesto.f(); -- radi
 }

} // end class

var nesto = new Nesto();
Dokle ide var domen za event funkcije? Sto ne radi this? Ima li zamene?
Da li gresim sto class method ubacujem kao event handle?

Negde sam citao da JS ima static metode:
Nesto.myf1 = function(){...}
Nesto.myf2 = function(){...}


Al mi taj kod izgledao nekako debilno. Da li to treba tako? Da li je bolje ubaciti static f kao event handle?
Sta se desava sa this ako je f static? Postoji li self?

Ili je bolje napraviti skroz odvojene f za mouse event hande i tu muljati globalne vars?

I'm not in this world to live up to your expectations and you're not in this world to live up to mine.
 
Odgovor na temu

MilosDj
Milos Djuric
Belgrade

Član broj: 14174
Poruke: 307
*.dynamic.isp.telekom.rs.



+4 Profil

icon Re: document.onclick = this.mouse; i onda ne vidi this iz klase! Zasto?21.10.2010. u 17:57 - pre 163 meseci
Ok, shvatio sam da se u event handle funkciji this odnosi na HTML objekat na koji sam kliknuo.
alert(this); == html object element
alert(typeof(this)); == object


Da li je moja greska sto sam ubacio class method kao event handle?
Izgleda kao da sve mora preko global/static vars?

Ili ja samo veze nemam kako class method da ubacim u onclick, onkeydown, up... i uspesno koristim class this?
I'm not in this world to live up to your expectations and you're not in this world to live up to mine.
 
Odgovor na temu

MilosDj
Milos Djuric
Belgrade

Član broj: 14174
Poruke: 307
*.dynamic.isp.telekom.rs.



+4 Profil

icon Re: document.onclick = this.mouse; i onda ne vidi this iz klase! Zasto?22.10.2010. u 00:19 - pre 163 meseci
Citat:
In JavaScript the this keyword always refers to the “owner” of a function!
Or rather, to the object that a function is a method of.
In the case of event handlers it is very useful if this refers to HTML element event is handled by, so that you have easy access to it.
Sve je jako lepo objasnjeno ovde!

Koliko vidim ima tri nacina da se napravi event handle. I u zavisnosti sta koristim, this se razlicito ponasa.

1.reference function
Code:
<A HREF="somewhere.html" onClick="doSomething(this)">    // HTML

function doSomething(obj)    // JS
{
    // obj now refers to the link
}

2. copy function -> this = html element
Code:
element.onclick = doSomething;    // JS
another_element.onclick = doSomething;    // JS

function doSomething()    // JS
{
    this.style.backgroundColor = '#cc0000';    // this = HTML element
}

3.copy function -> this = html element
Code:
element.addEventListener('click',doSomething,false);
another_element.addEventListener('click',doSomething,false);

function doSomething() {
    this.style.backgroundColor = '#cc0000';    // this = HTML element
}


p.s. bilo mi glupo da ostavim neodgovoreno pitanje sad kad znam :D
I'm not in this world to live up to your expectations and you're not in this world to live up to mine.
 
Odgovor na temu

MilosDj
Milos Djuric
Belgrade

Član broj: 14174
Poruke: 307
*.dynamic.isp.telekom.rs.



+4 Profil

icon Re: document.onclick = this.mouse; i onda ne vidi this iz klase! Zasto?22.10.2010. u 11:40 - pre 163 meseci
Da dodam

2.a) copy function + my_param -> this = html element
Code:
htmlElement.onclick = function(e){ myHandler(e, myparam); }

function myHandler(event, param)
{
    // Do stuff with event OR your param
}

I'm not in this world to live up to your expectations and you're not in this world to live up to mine.
 
Odgovor na temu

Aleksandar Ružičić
Software Architect, Appricot d.o.o.
Beograd

Član broj: 26939
Poruke: 2881

Jabber: krckoorascic@gmail.com
Sajt: krcko.net


+44 Profil

icon Re: document.onclick = this.mouse; i onda ne vidi this iz klase! Zasto?22.10.2010. u 15:21 - pre 163 meseci
konkretan odgovor na prvi post bi bio:

1. treba ti "bind" metoda u Function prototype-u:
Code (javascript):

if (Function.prototype.bind == null) {

    Function.prototype.bind = (function (slice){

        // (C) WebReflection - Mit Style License
        function bind(context) {

            var self = this; // "trapped" function reference

            // only if there is more than an argument
            // we are interested into more complex operations
            // this will speed up common bind creation
            // avoiding useless slices over arguments
            if (1 < arguments.length) {
                // extra arguments to send by default
                var $arguments = slice.call(arguments, 1);
                return function () {
                    return self.apply(
                        context,
                        // thanks @kangax for this suggestion
                        arguments.length ?
                            // concat arguments with those received
                            $arguments.concat(slice.call(arguments)) :
                            // send just arguments, no concat, no slice
                            $arguments
                    );
                };
            }
            // optimized callback
            return function () {
                // speed up when function is called without arguments
                return arguments.length ? self.apply(context, arguments) : self.call(context);
            };
        }

        // the named function
        return bind;

    }(Array.prototype.slice));
}
 

kod preuzet sa http://webreflection.blogspot..../02/functionprototypebind.html


2. koristi bind kada kacis bilo kakve callbackove:
Code (javascript):

function Nesto(){

this.init = function()
 {
 document.onclick = this.mouse.bind(this);
 }


this.mouse = function(e)
 {
    alert(this instanceof Nesto);  // trebalo bi da da "true" :)
 }

} // end class
 


inace ovako neces dobiti originalan this ali moze da se sredi to vrlo lako tako sto ce se kopirati context unutar bind fje i prosledjivati se kao prvi argument, recimo.

mada, sve ovo je bespotrebno, uzmes jednostavno jQuery ili neki drugi js framework i ne gubis vreme...




edit: dodat syntax-highlighting u code blokove

[Ovu poruku je menjao Aleksandar Ružičić dana 29.12.2010. u 01:32 GMT+1]
 
Odgovor na temu

misk0
.: Lugano :. _.: CH :.

SuperModerator
Član broj: 634
Poruke: 2824
*.adsl.ticino.com.

ICQ: 46802502


+49 Profil

icon Re: document.onclick = this.mouse; i onda ne vidi this iz klase! Zasto?24.10.2010. u 20:24 - pre 163 meseci
JS izvrsava funkciju (metod) u kontekstu odakle je pozvana a ne gdje je definisana. I sa jQuery moras definisati parametar koji ce upucivati na kontekst iz definicije.
:: Nemoj se svadjati sa budalom, ljudi cesto nece primjetiti razliku ::
 
Odgovor na temu

MilosDj
Milos Djuric
Belgrade

Član broj: 14174
Poruke: 307
*.dynamic.isp.telekom.rs.



+4 Profil

icon Re: document.onclick = this.mouse; i onda ne vidi this iz klase! Zasto?24.10.2010. u 22:20 - pre 163 meseci
Fala ljudi
Shvatio sam da this zavisi od toga ko je postao "vlasnik" kopirane funkcije tj. metode. Quirksmode.com ima odlicna objasnjenja.

Fala za bind informaciju. Vidim da tu ima jos lepih stvari tipa call i apply Vreme da se uci.

I'm not in this world to live up to your expectations and you're not in this world to live up to mine.
 
Odgovor na temu

MilosDj
Milos Djuric
Belgrade

Član broj: 14174
Poruke: 307
*.dynamic.isp.telekom.rs.



+4 Profil

icon Re: document.onclick = this.mouse; i onda ne vidi this iz klase! Zasto?23.11.2010. u 16:27 - pre 162 meseci
Trebalo mi je "samo" mesec dana da ukapiram .bind

Dodatna pitanja:

1. document.onclick = this.mouse.bind(this); // lepo radi

Ali ako hocu da koristim "modernije" event handlere onda moram da koristim:

addEventHandler(nav, 'click', this.onMouseClick.bind(this));
addEventHandler(nav, 'click', bind(this, this.onMouseClick));
Code:

// var a = bind(obj, obj.method);
if (typeof (bind) == 'undefined'){
    function bind (obj, method) {return function () { return method.apply(obj, arguments); }    // function is return value!!!
}
} // --------------------------end if ! bind-------------------------

function addEventHandler(node, etype, f){
    if (node.addEventListener) {node.addEventListener(etype, f, false);}    // w3c; false buble up
    else if (node.attachEvent) {node.attachEvent('on'+etype, f);}    // MS only bubble up
    else {node['on'+etype] = f;}    // All
} // -------------------- end addEventHandler------------------
Oba bindovanja rade jer bind kao rezultat vraca funkciju, koja onda radi call/apply itd... To bi trebalo da sam shvatio.

Pitanje je da li mogu da vezem <html elem this> nekako s tim bindovanjima. Za sada elem dobijam preko click:
Code:
    var elem = e.target ? e.target : e.srcElement;    // html elem you clicked on
    while (elem.nodeType !== 1) {elem = elem.parentNode;}    // if clicked on txt node
Ali bi bilo lepo kad bih imao this = object i elem = html.this;
Predpostavljam da negde treba pustiti html.this kao parametar.


2. Koliko ja razumem elem.onclick = myf; je standardna JavaScript dodela funkcija na objekat. U ovom slucaju DOM objekat elem. To ne bi trebalo nikad da se izbaci iz jezika. Jedini nacin da to nestane je da se izmeni DOM. Tj da DOM node prestane da bude JS object. Da li sam u pravu?

3. addEventHandler sluzi samo za dodavanje vise event funkcija. Ostalo je isto kao pod 2. Ili nije?
Takodje, koji se unutrasnji mehanizam koristi za vise f na jednom onclick?

4. Dodam par funkcija na onclick sa addEventHandler(document, 'click',myf1,2,3) i onda kasnije upotrebim document.onclick = myf5;
Da li sam tako obrisao sve prethodne myf1,2,3 i postavio samo myf5 na onclick?
I'm not in this world to live up to your expectations and you're not in this world to live up to mine.
 
Odgovor na temu

MilosDj
Milos Djuric
Belgrade

Član broj: 14174
Poruke: 307
*.dynamic.isp.telekom.rs.



+4 Profil

icon Re: document.onclick = this.mouse; i onda ne vidi this iz klase! Zasto?23.11.2010. u 19:18 - pre 162 meseci
Dodatak :

5. Da li je moguce bindovati anonimnu f?
Code:
a) addEventHandler(nav, 'click', bind(this, function () {    window.location='#' + this.getCurrentId();}))

b) addEventHandler(nav, 'click', this.buttonAslink.bind(this));
this.buttonAslink = function () {window.location='#' + this.getCurrentId();};

c) function.bind(this) {window.location='#' + this.getCurrentId();}
//pa da mogu celu da je gurnem kao event handler :D


6. Kojim redosledom se izvrsavaju multiple event handles?
Uradio sam da prvo ide
Code:
addEventHandler( nav, 'click', this.setCurrentId.bind(this) );
addEventHandler( nav, 'click', this.displayStuff);
// pravilan rad displayStuff zavisi od pravilnog setovanja currentId.

Isto je i za button. Prvo setuje this.id pa onda druga f uzima getId
Sve lepo radi na FF ali me zanima koliko je to sigurno?

Ranije sam set id i display stuff zamotao u jednu anonimnu i to stavio na onclick.

I'm not in this world to live up to your expectations and you're not in this world to live up to mine.
 
Odgovor na temu

[es] :: Javascript i AJAX :: document.onclick = this.mouse; i onda ne vidi this iz klase! Zasto?

[ Pregleda: 3177 | Odgovora: 8 ] > FB > Twit

Postavi temu Odgovori

Navigacija
Lista poslednjih: 16, 32, 64, 128 poruka.