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());
});
From stackoverflow
-
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.
-
You're trying to reference the addPage property of the Product function (which in this case is a constructor), rather than on the returned object.
You probably want something like:
which also adds the brackets to the addPage call (though this is not the problem that FireBug will have been complaining about as it will not be able to find that method anyway).// Begin executing $(document).ready(function () { var product = new Product(); product.addPage().setImage('http://site/images/small_logo.png'); alert(product.page(1).image()); });
-
This would work too:
Product().addPage().setImage('http://site/images/small_logo.png');
Andrzej Doyle : It would on that line - but the next line would not be able to callpage(1)
on the same instance of product, which it needs to. Thus storing as a local variable is required. -
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()); });
0 comments:
Post a Comment