highwingers
highwingers

Reputation: 1669

JavaScript class to populate object

I am trying to populate an object by using a JavaScript class. I am not even sure if I am doing it correctly, I am very new to JavaScript OOP.

var ImagesViewModel = {}; // Global object

function ImagesClass() {

    this.addImage = function (iUrl) {
        ImagesViewModel.push({ "ImageUrl": iUrl }) //<  Error is here
    }

}

var k = new ImagesClass()
k.addImage("http://www.yahoo.com")
k.addImage("http://www.xbox.com")

Basically I need an easy way to populate ImagesViewModel with multiple properties. Do I need to specify properties within ImagesViewModel? Maybe I can do all of this without having to specify a global variable?

I am getting the error

Object has no method PUSH

Upvotes: 0

Views: 1450

Answers (3)

PSL
PSL

Reputation: 123739

What you want is an array and not an object, push is a method on Array prototype and you are trying to use it on object.

Change:

var ImagesViewModel = {};

To:

var ImagesViewModel = [];

You can do it this way as well so that each instance of ImagesClass has its own set of images.

function ImagesClass() {
    var  _images = [];

    this.addImage = function (iUrl) {
       _images.push({ "ImageUrl": iUrl }) //<  Error is here
    }

    this.getImages = function(){
      return _images;
    }
}

and use it as:

var k = new ImagesClass();
k.addImage("http://www.yahoo.com");
k.addImage("http://www.xbox.com");
var ImagesViewModel = k.getImages(); //You can either set it directly or as a property of object
console.log(ImagesViewModel);

Demo

Upvotes: 4

Ryan Nigro
Ryan Nigro

Reputation: 4619

From a design perspective, you probably don't want your viewmodel to just be a flat array (even though you declared it as an object, as other posters pointed out).

I'd suggest declaring an array declaration to hold the images inside of your ImagesViewModel object.

var ImagesViewModel = { // ViewModel generic OBJECT
  this.Images = new Array(); // prototype ARRAY object
}; 

function ImagesClass() {    
    this.addImage = function (iUrl) {    
        ImagesViewModel.Images.push({ "ImageUrl": iUrl }) 
    }

}

Upvotes: 1

Jay Huang
Jay Huang

Reputation: 356

the push method is only for Arrays, here you are trying to push() to an object, which is why it isn't working.

You will need to change var ImagesViewModel = {}; to var ImagesViewModel = [];

Upvotes: 1

Related Questions