JS and OO: Tying objects to elements

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

    #1

    JS and OO: Tying objects to elements

    I am having trouble trying to more closely relate objects (as
    functions) in javascript with HTML elements. For example, I have an
    object 'class' MyImage:

    function MyImage(file)
    {
    var img = document.create Element('IMG');
    img.src = file;
    img.myProperty = 'myValue';

    return img;
    }

    This uses the DOM to construct and return an HTML IMG element. I can
    then instantiate this and refer directly to the img attributes as well
    as any properties I have defined, e.g.

    var myImage = new MyImage('mypict ure.jpg');
    document.body.a ppendChild(myIm age);
    myImage.style.w idth = 300;
    myImage.myPrope rty = 'anotherValue';

    The problem comes when I then try to define methods on the object's
    prototype, e.g.

    MyImage.prototy pe.myMethod = function()
    {
    alert("shiver in eternal darkness");
    }

    When called, this gives the error: "Object doesn't support this
    property or method".

    Is what I am doing by returning a created HTML element from the object
    constructor valid and acceptable? If so, how do I define methods on
    the object?

    Any help would be much appreciated.
  • Berislav Lopac

    #2
    Re: JS and OO: Tying objects to elements

    Martin wrote:[color=blue]
    > I am having trouble trying to more closely relate objects (as
    > functions) in javascript with HTML elements. For example, I have an
    > object 'class' MyImage:
    >
    > function MyImage(file)
    > {
    > var img = document.create Element('IMG');
    > img.src = file;
    > img.myProperty = 'myValue';
    >
    > return img;
    > }
    >
    > This uses the DOM to construct and return an HTML IMG element. I can
    > then instantiate this and refer directly to the img attributes as well
    > as any properties I have defined, e.g.
    >
    > var myImage = new MyImage('mypict ure.jpg');[/color]

    By this, you have created a new MyImage object.

    You can do what you want in two ways:

    a) In the line above, delete 'new'. This will return a DOM Element object to
    the myImage variable.
    b) Do not return from MyImage function. This way the above line will create
    a new MyImage object, which might be a wrapper for images. If you define img
    internal variable as this.img, that will create a member of the MyImage
    class which could be reached (in this example) as myImage.img.

    For more information on OO in Javascript, I recommend
    http://www.crockford.com/javascript/private.html and other articles about JS
    on http://www.crockford.com/

    Berislav

    --
    If the Internet is a Marx Brothers movie, and Web, e-mail, and IRC are
    Groucho, Chico, and Harpo, then Usenet is Zeppo.


    Comment

    • Michael Winter

      #3
      Re: JS and OO: Tying objects to elements

      On 1 Sep 2004 01:49:40 -0700, Martin <djmanmaster@gm x.net> wrote:
      [color=blue]
      > I am having trouble trying to more closely relate objects (as functions)
      > in javascript with HTML elements. For example, I have an object 'class'
      > MyImage:
      >
      > function MyImage(file)
      > {
      > var img = document.create Element('IMG');[/color]

      Make sure that you feature test DOM methods and objects before using them.
      [color=blue]
      > img.src = file;
      > img.myProperty = 'myValue';
      >
      > return img;[/color]

      Returning an object other than null from a constructor returns that
      object. To me, that seems pointless. If you want to create objects based
      on some sort of pattern, use a factory. This can be something as simple as
      a global function, or an object with static methods that instantiate,
      modify, then return the object.

      [snip]
      [color=blue]
      > The problem comes when I then try to define methods on the object's
      > prototype, e.g.
      >
      > MyImage.prototy pe.myMethod = function()
      > {
      > alert("shiver in eternal darkness");
      > }
      >
      > When called, this gives the error: "Object doesn't support this
      > property or method".
      >
      > Is what I am doing by returning a created HTML element from the object
      > constructor valid and acceptable?[/color]

      If you return null or a non-object, the result of the constructor
      instantiation will be just like normal. If you return an object, the
      result will be that object. So, yes it's valid, but it seems to defeat the
      object of a constructor.
      [color=blue]
      > If so, how do I define methods on the object?[/color]

      With user-defined objects, what you have done is fine. However, you aren't
      dealing with a user-defined object anymore (part of the confusion
      resulting from your code). You've got a host object.

      Whilst some browsers do allow the prototyping of user-defined members on
      host object, IE certainly doesn't. You'll either have to attach the
      members on a per-item basis, or encapsulate the functionality in your own
      objects.

      Mike

      --
      Michael Winter
      Replace ".invalid" with ".uk" to reply by e-mail.

      Comment

      • Martin

        #4
        Re: JS and OO: Tying objects to elements

        Thanks. I think I understand.

        I thought it would be neat to have the DOM element synonymous with the
        JS object. This would be useful if you had a more complex object made up
        of many DOM elements, all contained within, for example, a div. The
        containing div would be created, have the other elements appended to it,
        and then be returned from the constructor. For example, if you had a
        Graph object:

        function Graph()
        {
        var div = createElement(' DIV');
        ...
        this.title = createElement(' SPAN');
        ...
        div.appendChild (title);
        div.appendChild (chart);

        return div;
        }

        var myGraph = new Graph();
        myGraph.title.s tyle...
        myGraph.chart.s tyle... etc.

        However, it would appear that returning DOM elements from a constructor
        is not a good thing. Therefore you would have to make the div a member
        of the object too, and then refer to:

        myGraph.div.tit le.style...

        This is what Berislav suggested as option (b) above. I must admit that I
        don't quite understand what option (a) achieves (removing 'new'), since
        you still can't add methods to the prototype of the object.

        The only other option I see is the following:

        function Graph()
        {
        var div = ...
        this.myMethod = myMethod;
        ...
        return div;
        }
        function myMethod()
        {
        // this method is a member of Graph
        }

        I assume this is what Michael meant by "attaching members on a per-item
        basis". Although I'm not sure if you can refer to the keyword 'this'
        inside myMethod.


        _______________ _______
        replace 'nospam' with 'net' for email.

        *** Sent via Developersdex http://www.developersdex.com ***
        Don't just participate in USENET...get rewarded for it!

        Comment

        • Michael Winter

          #5
          Re: JS and OO: Tying objects to elements

          On 01 Sep 2004 13:02:28 GMT, Martin <djmanmaster@gm x.nospam> wrote:
          [color=blue]
          > Thanks. I think I understand.[/color]

          Unfortunately, it seems you missed a point that both I and Berislav made.

          In the normal scheme of things,

          function MyConstructor() {
          this.myProperty = 'Test';
          }

          var myObject = new MyConstructor() ;
          alert(myObject. myProperty);

          the code above would display, "Test". An object is made from a function
          that acts as a constructor.

          However, if you return an object the affects of normal operation are
          ignored. An object isn't made out of the constructor; the returned object
          is what results. This can be demonstrated by:

          function MyConstructor() {
          this.myProperty = 'Test';
          return {}; // Return an object
          }

          var myObject = new MyConstructor() ;
          alert(myObject. myProperty);

          Instead of "Test", the alert shows "undefined" . The object that would have
          normally resulted has been destroyed, including the property, myProperty.
          [color=blue]
          > I thought it would be neat to have the DOM element synonymous with the
          > JS object. This would be useful if you had a more complex object made up
          > of many DOM elements, all contained within, for example, a div. The
          > containing div would be created, have the other elements appended to it,
          > and then be returned from the constructor.[/color]

          To do this, you need to encapsulate everything inside a user-defined
          object:

          function Graph() {
          this.div = document.create Element('DIV');
          // ...
          this.title = document.create Element('SPAN') ;
          // ...
          this.div.append Child(this.titl e);
          }

          var myGraph = new Graph();
          // myGraph.div.<wh atever>

          Alternatively, you could use a proper OO approach and make the data
          private:

          function Graph() {
          var div = document.create Element('DIV'),
          title = document.create Element('SPAN') ;

          // ...
          div.appendChild (title);

          this.setTitleSt yle = function(prop, value) {
          if(title.style) {title.style[prop] = value;}
          };
          // Other "privaledge d" methods
          }

          [snip]
          [color=blue]
          > However, it would appear that returning DOM elements from a constructor
          > is not a good thing.[/color]

          Returning any object[1] is a bad thing. Just like in C++ and Java,
          constructors should not return values.

          [snip]
          [color=blue]
          > function Graph()
          > {
          > var div = ...
          > this.myMethod = myMethod;
          > ...
          > return div;
          > }
          > function myMethod()
          > {
          > // this method is a member of Graph
          > }[/color]

          You should now see that that won't work. There is no Graph object as a
          result of using the Graph constructor. All you get is a DIV host object,
          and the property, myMethod, will not be a part of it.

          If you want to use the host object as the encapsulating object, then use a
          standard function to create the various contained objects and return the
          DIV that way:

          function Graph_myMethod( ) {
          // ...
          }

          function createGraph() {
          var div = document.create Element('DIV');

          div.myMethod = Graph_myMethod;
          // ...
          return div;
          }

          var myGraph = createGraph();

          The variable, myGraph, now references a DIV element that contains the
          method, myMethod.

          myGraph.myMetho d(); // calls Graph_myMethod with the this operator
          // set to the object referred to by myGraph

          [snip]

          Hope that helps,
          Mike


          [1] Except possibly the this object, but that's redundant.

          --
          Michael Winter
          Replace ".invalid" with ".uk" to reply by e-mail.

          Comment

          • Mike Foster

            #6
            Re: JS and OO: Tying objects to elements

            Martin wrote:[color=blue]
            > I am having trouble trying to more closely relate objects (as
            > functions) in javascript with HTML elements.
            > ...[/color]

            You've received some very good replies to this question - but
            I thought I would throw mine in as well :-)

            I have a demo that is related to the question:



            Feedback (good or bad) is welcome.

            Comment

            • Thomas 'PointedEars' Lahn

              #7
              Re: JS and OO: Tying objects to elements

              Martin wrote:
              [color=blue]
              > I am having trouble trying to more closely relate objects (as
              > functions) in javascript with HTML elements. For example, I have
              > an object 'class' MyImage:[/color]

              There are no classes in ECMAScript < 4, JavaScript < 2 and JScript < 6.
              You have defined a constructor.
              [color=blue]
              > function MyImage(file)
              > {
              > var img = document.create Element('IMG');
              > img.src = file;
              > img.myProperty = 'myValue';
              >
              > return img;
              > }
              >
              > This uses the DOM to construct and return an HTML IMG element. I can
              > then instantiate this and refer directly to the img attributes as well
              > as any properties I have defined, e.g.
              >
              > var myImage = new MyImage('mypict ure.jpg');
              > document.body.a ppendChild(myIm age);
              > myImage.style.w idth = 300;
              > myImage.myPrope rty = 'anotherValue';
              >
              > The problem comes when I then try to define methods on the object's
              > prototype, e.g.
              >
              > MyImage.prototy pe.myMethod = function()
              > {
              > alert("shiver in eternal darkness");
              > }
              >
              > When called, this gives the error: "Object doesn't support this
              > property or method".[/color]

              How do you call the method?
              [color=blue]
              > Is what I am doing by returning a created HTML element from the
              > object constructor valid and acceptable?[/color]

              Yes and no. A constructor must not return an object reference if not
              intended to be a factory. You may not use this method as a constructor
              (using the "new" keyword) if you want to return a reference to the DOM
              object, only as a factory (calling it and evaluate the result).
              [color=blue]
              > If so, how do I define methods on the object?[/color]

              Exactly as you did.
              [color=blue]
              > Any help would be much appreciated.[/color]

              You're welcome.


              PointedEars
              --
              Life is like a grapefruit. -- F. Prefect

              Comment

              Working...