views:

187

answers:

4

I'm trying to understand why this does not work. (Basic example with no validation yet)

When I test it, firebug states Product.addPage is not found.

var Product = function ()
{
    var Page = function ()
    {
        var IMAGE = '';

        return {
            image : function ()
            {
                return IMAGE;
            },
            setImage : function (imageSrc_)
            {
                IMAGE = '<img id="image" src="' + imageSrc_ + '" height="100%" width="100%">';
            }
        };
    };
    var PAGES = [];

    return {
        addPage : function ()
        {
            var len = PAGES.length + 1;
            PAGES[len] = new Page();
            return PAGES[len];
        },
        page : function (pageNumber_)
        {
            var result = PAGES[pageNumber_];
            return result;
        }
    };
};

// Begin executing
$(document).ready(function ()
{
    Product.addPage.setImage('http://site/images/small_logo.png');
    alert(Product.page(1).image());
});
+2  A: 

How about Product.addPage().setImage('http://site/images/small_logo.png');?


Edit: Turns out I only caught half the problem. Look at dtsazza's answer for the whole thing.

lc
+8  A: 
Andrzej Doyle
Thanks for the explanation. I know where I was going wrong now.
A: 

This would work too:

Product().addPage().setImage('http://site/images/small_logo.png');
Kieveli
It would on that line - but the next line would not be able to call <code>page(1)</code> on the same instance of product, which it needs to. Thus storing as a local variable is required.
Andrzej Doyle
A: 

How about:

var Product = {
 Page : function() {    
  return {
   _image : '',
   Image : function() {
    return this._image;
   },
   setImage : function(imageSrc_) {
    this._image = '<img id="image" src="' + imageSrc_ + '" height="100%" width="100%">';
   }
  };
 },
 Pages : [],
 addPage : function() {
  var Page = new Product.Page();
  this.Pages.push(Page);
  return Page;
 },
 GetPage : function(pageNumber_) {
  return this.Pages[pageNumber_];
 }
};

// Begin executing
$(document).ready(function ()
{
 Product.addPage().setImage('http://site/images/small_logo.png');
 alert(Product.GetPage(0).Image());
});
Gavin