Event Problem

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jim Red

    Event Problem

    Hi

    i'd like to call a method from an object by an event. but how can i
    access the object?

    xhtml:
    ....
    <div id="layer">Som e Content</div>
    ....



    javascript:
    ....
    var Dragger = function() {
    this.message = "Hello World";

    this.element = document.getEle mentById('layer ');

    this.init();
    }

    Dragger.prototy pe.init() {
    this.element.on mousemove = this.drag;
    }

    Dragger.prototy pe.drag(event) {
    alert(this.mess age);
    }


    var oDragger = new Dragger();
    ....


    How can I access the Message-Variable within the Drag-Method?
    => 'this' is no longer the object, its now en eventobject...

    Can anyone help?

    Thanks //jim
  • Yann-Erwan Perio

    #2
    Re: Event Problem

    Jim Red wrote:

    Hi,
    [color=blue]
    > var Dragger = function() {
    > this.message = "Hello World";
    >
    > this.element = document.getEle mentById('layer ');
    >
    > this.init();
    > }
    >
    > Dragger.prototy pe.init() {
    > this.element.on mousemove = this.drag;
    > }
    >
    > Dragger.prototy pe.drag(event) {
    > alert(this.mess age);
    > }[/color]
    [color=blue]
    > How can I access the Message-Variable within the Drag-Method?
    > => 'this' is no longer the object, its now en eventobject...[/color]

    When you assign "this.drag" you assign the *function* registered as
    Dragger.prototy pe.drag, not the *method* - hence your results, since the
    function has not the "this" value you're looking for.

    If you really want to keep your structure, then simply define an expando
    property on your element
    this.element._t his = this
    so that you can refer to it in the event handler - but beware the
    circular reference, which won't be cleared by IE (you'll have to clear
    it yourself onunload).


    However, I think that you should adopt a different object structure, and
    start with thinking about the nature of the property you're looking for
    ("message"): is it private/public, instance/static? Once you've
    determined how you wanted the property to be, just use the appropriate
    pattern.

    Examples for patterns:

    var Dragger = (function() {
    //all the following variables are private/static
    var somePrivateStat icVariable="foo ";

    //the following is the constructor
    function Constructor() {
    var somePrivateInst anceVariable = "foo";
    this.somePublic InstanceVariabl e = "foo";
    this.someInstan ceMethod=functi on(){} //knows private instance vars
    }
    Constructor.som eStaticPublicVa riable="foo";
    Constructor.pro totype.someProt otypeMethod=fun ction() {}
    })();

    Javascript has a very original object model, with prototypes and
    closures, if you want to have an object-based approach then you'd better
    get familiar with it:

    <URL:http://www.crockford.c om/javascript/index.html>


    In your case, you could separate your javascript object from the DOM
    equivalents, the prototype.drag method isn't IMO really required, for
    instance:

    var Dragger = (function() {
    var Mouse={x:0, y:0};

    document.onmous emove=function( evt){
    //update the mouse object
    }

    function initMousedownFo r(instance){
    //define a mousedown handler that will trigger a startDrag
    instance.elemen t.onmousedown=f unction(evt){
    startDrag(insta nce);
    }
    }

    function initMouseupFor( instance){
    //define a mouseup handler that will trigger a stopDrag
    }

    function startDrag(insta nce) {
    //start a timer, and position the element
    //at each interval, according to the moves of
    //the private static Mouse
    //show the instance.messag e
    }

    function stopDrag(instan ce){
    //clear the timer
    }

    function Constructor(msg , el){
    this.message=ms g;
    this.element=el ;
    this.init();
    }

    Constructor.pro totype.init = function() {
    initMousedownFo r(this);
    initMouseupFor( this);
    }
    })();

    A quick note regarding mousemove handlers: simply register a mousemove
    handler on the document, and use mousedown/mouseup on the target to
    trigger a startDrag and a stopDrag - then follow the drag with the
    global mousemove and a timer (setTimeout or setInterval).


    HTH,
    Yep.

    Comment

    • Richard Cornford

      #3
      Re: Event Problem

      Yann-Erwan Perio wrote:
      <snip>[color=blue]
      > var Dragger = (function() {
      > //all the following variables are private/static
      > var somePrivateStat icVariable="foo ";
      >
      > //the following is the constructor
      > function Constructor() {
      > var somePrivateInst anceVariable = "foo";
      > this.somePublic InstanceVariabl e = "foo";
      > this.someInstan ceMethod=functi on(){} //knows private instance
      > vars }
      > Constructor.som eStaticPublicVa riable="foo";
      > Constructor.pro totype.someProt otypeMethod=fun ction() {}[/color]

      Hadn't you better:-

      return Constructor;

      - about here?
      [color=blue]
      > })();[/color]

      <snip>[color=blue]
      > var Dragger = (function() {
      > var Mouse={x:0, y:0};[/color]
      <snip>[color=blue]
      > function Constructor(msg , el){
      > this.message=ms g;
      > this.element=el ;
      > this.init();
      > }
      >
      > Constructor.pro totype.init = function() {
      > initMousedownFo r(this);
      > initMouseupFor( this);
      > }[/color]

      return Constructor;
      [color=blue]
      > })();[/color]
      <snip>

      Richard.


      Comment

      • Yann-Erwan Perio

        #4
        Re: Event Problem

        Richard Cornford wrote:
        [color=blue]
        > Hadn't you better:-
        >
        > return Constructor;
        >
        > - about here?[/color]

        Yes, definitely:-)
        [color=blue]
        > Richard.[/color]

        Cheers,
        Yep.

        Comment

        • Danny

          #5
          Re: Event Problem


          When using custom objects just do it from the object getting the
          constructor:


          function MYMETHOD() {
          .........
          }


          function SOANDSO() {
          this.something= 'stuff';
          this.bologne=MY METHOD;
          }

          var theduck=SOANDSO ;
          -------------- then you use --------------
          theduck.MYMETHO D();

          Danny

          On Thu, 09 Jun 2005 14:41:39 -0700, Jim Red <jimred73@aol.c om> wrote:
          [color=blue]
          > Hi
          >
          > i'd like to call a method from an object by an event. but how can i
          > access the object?
          >
          > xhtml:
          > ...
          > <div id="layer">Som e Content</div>
          > ...
          >
          >
          >
          > javascript:
          > ...
          > var Dragger = function() {
          > this.message = "Hello World";
          >
          > this.element = document.getEle mentById('layer ');
          >
          > this.init();
          > }
          >
          > Dragger.prototy pe.init() {
          > this.element.on mousemove = this.drag;
          > }
          >
          > Dragger.prototy pe.drag(event) {
          > alert(this.mess age);
          > }
          >
          >
          > var oDragger = new Dragger();
          > ...
          >
          >
          > How can I access the Message-Variable within the Drag-Method?
          > => 'this' is no longer the object, its now en eventobject...
          >
          > Can anyone help?
          >
          > Thanks //jim[/color]



          --
          Using Opera's revolutionary e-mail client: http://www.opera.com/mail/

          Comment

          • Richard Cornford

            #6
            Re: Event Problem

            Danny wrote:[color=blue]
            > When using custom objects just do it from the
            > object getting the constructor:[/color]

            Just do what "from the object getting the constructor"? And what is
            "getting the constructor" supposed to mean?
            [color=blue]
            >
            > function MYMETHOD() {
            > .........
            > }
            >
            >
            > function SOANDSO() {
            > this.something= 'stuff';
            > this.bologne=MY METHOD;
            > }
            >
            > var theduck=SOANDSO ;[/color]

            This line of code assigns a reference to a function (currently referred
            to by the Identifier - SOANDSO -) to the variable - theduck -.
            [color=blue]
            > -------------- then you use --------------
            > theduck.MYMETHO D();[/color]

            The function object now referred to by the Identifier - theduck - has
            no - MYMETHOD - method so this line will error.

            If - SOANDSO - had been used as a constructor, even then the line of
            code would error, as the resulting object instance still would have no -
            MYMETHOD - method.

            Beyond being utter nonsense in itself, non of this even attempts to
            address the problem of retaining an association between an object
            instance, a call to a method of that object instance, and a DOM event
            handler.
            [color=blue]
            > On Thu, 09 Jun 2005 14:41:39 -0700, Jim Red <jimred73@aol.c om> wrote:[/color]
            <snip>

            Please do not top-post to comp.lang.javas cript. See the group's FAQ:-

            <URL: http://www.jibbering.com/faq/ >

            Richard.


            Comment

            • Jim Red

              #7
              Re: Event Problem

              Yann-Erwan Perio wrote:
              <snip>[color=blue]
              > function startDrag(insta nce) {
              > //start a timer, and position the element
              > //at each interval, according to the moves of
              > //the private static Mouse
              > //show the instance.messag e
              > }
              >
              > function stopDrag(instan ce){
              > //clear the timer
              > }[/color]
              </snip>

              First of all, thanks for this long and detailed explanation.

              How can I set the timer?

              interval = setInterval(mov eElement, 1000, instance);

              ....

              function moveElement(ins tance) {
              instance.elemen t.style.x = Mouse.x;
              instance.elemen t.style.y = Mouse.y;
              }

              ....

              is there another way to use the setInterval?

              Thanks

              //jim

              Comment

              • Yann-Erwan Perio

                #8
                Re: Event Problem

                Jim Red wrote:
                [color=blue]
                > First of all, thanks for this long and detailed explanation.[/color]

                If I had time I'd go much more in detail, but if this was helpful then
                I'm happy!
                [color=blue]
                > How can I set the timer?
                >
                > interval = setInterval(mov eElement, 1000, instance);[/color]

                There's two signatures:
                - interval = setInterval ("codeToBeEvalu atedInGlobalCon text", ms)
                - interval = setInterval (functionRef, ms)

                The first argument can be a string (containing code) which will be
                evaluated in the global context, or it can be a function reference (not
                supported by very old browsers, though). The second argument is the
                interval in milliseconds.

                You can clear an interval with
                clearInterval(i nterval);

                In the example I've given, it's suimpler to have a
                this.timer
                property on the instance; you'll change that later.
                [color=blue]
                > instance.elemen t.style.x = Mouse.x;[/color]

                instance.elemen t.style.left = (Mouse.x||0)+"p x";
                [color=blue]
                > is there another way to use the setInterval?[/color]

                You can use setTimeout/clearTimeout, which does not create an interval
                but only a timeout for the "execution" of the first argument (but then
                you can chain timeouts, the code of the first argument including itself
                a timeout and so forth).

                If you look through the archives at http://groups.google.com you'll find
                a great deal of examples of intervals/timeouts.


                HTH,
                Yep.

                Comment

                Working...