Question

So this is curious. I've written my own little responsive switch statement:

setView = function(x){
    switch(true){
        case x > 1250:
            if(view != desktop){
                view = desktop;
                startView();
            }
            break;
        case x <= 1250 && x >= 924:
            if(view != tablet){
                view = tablet;
                startView();
            }
            break;
        default:
            if(view != mobile){
                view = mobile;
                startView();
            }           
            break;
    }
}

where x is the size of the browser. when switching view from tablet to mobile, mobile has retained some of tablet's functions. Is this expected behavior? It seems to me like this should not happen.

I've condensed my code into a fiddle to demonstrate what I'm talking about.

Expected behavior:

  • If starting as mobile, the default occurs. Swapping to tablet, tablet override occurs.
  • If starting as tablet, tablet override occurs. Swapping to mobile, default occurs

Observed behavior:

  • If starting as mobile, the default occurs. Swapping to tablet, tablet override occurs. Swapping back to mobile, tablet override occurs.
  • If starting as tablet, tablet override occurs. Swapping to mobile, tablet override occurs

From my understanding, prototype should alter all instances, while the simple assignment foo.attribute = should only alter the instance. Is my understanding of prototype flawed? Why is this happening? I've fixed the problem by reassigning the mobile.component.hook default in mobile._component, but it seems to me like I shouldn't have to do this.

Was it helpful?

Solution

The problem is that both views share the same Component object, as you create only one and assign it to the prototype of the View.

To make the views have separate Component object you need to create one instance for each view that you create:

//Setting up everything
function View(){
  this.component = new Component();
}
function Component(){}
Component.prototype.hook = function(){alert("Should be default")}
View.prototype._component = function(){throw "this function is called on Component change, so override.";};

Demo: http://jsfiddle.net/2mJdG/2/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top