1

relevant parts of the code:

function myObj(wgtId, options, parentPage) {
    if (!wgtId) return;

    this.colors=['red','pink'];
    hmiWidget.call(this, wgtId, options, parentPage);
}

myObj.prototype = new hmiWidget();  // Inheriting the base class Widget

myObj.prototype.setValue = function (newValue) {
    var index = newValue;
    var color = this.colors[index];
    this.elem.style.backgroundColor = color;
};

$hmi.fn.myObj = function (options, parentPage) {
    return new myObj(this.wgtId, options, parentPage);
};

Usage:

  $(".myClass").myObj( {colors:['#ccccff','#000099']} );  // start with blue
  . . .
  objWidget.setValue(newVal); 

All this works well.

Now I need to change the colors array for specific instance.

I tried to use -

objWidget.colors[0] = "#ccffcc"; 

but it affected all instances. (I do not understand why all instances are affected.)

from Javascript object members that are prototyped as arrays become shared by all class instances I understand that I cannot add and use

code:
myObj.prototype.setColor = function (index, newColor) {
    this.colors[index] = newColor;
}
usage:
objWidget.setColor(0, "#009900");

because 'prototype' will share my colors array between all instances.

so how can I affect colors array of only one instance?

Community
  • 1
  • 1
Atara
  • 3,523
  • 6
  • 37
  • 56

2 Answers2

0

Is it possible that you are using the same instance for each object, that's why changing color value, it get changed everywhere. Try creating new instance for each .myClass

$hmi.fn.myObj = function (options, parentPage) {
    return this.each(function(){
        (new myObj(this.wgtId, options, parentPage));           
    });
};

Tell me if you need more help.

  • tried it. but it did not help. (need to add ')' at the end of line 3 in the proposed code ). – Atara Jun 22 '15 at 09:52
-1

finally I by-passed the problem by using simple variables col0, col1 instead of using the array.

not optimal but solved my current needs. :(

Atara
  • 3,523
  • 6
  • 37
  • 56