Skip to content

Instantly share code, notes, and snippets.

@tivac
Last active October 4, 2015 11:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tivac/2629600 to your computer and use it in GitHub Desktop.
Save tivac/2629600 to your computer and use it in GitHub Desktop.
Parent/Child Y.View extension

Parent/Child Y.Views

As I worked with Y.App it became clear that while Y.View is a great abstraction it would be easy to overwhelm a single instance with way too much functionality. This is my attempt to solve that issue by allowing multiple child views to be attached to a single parent view via an extension.

Usage

The extension is mixed into the parent view like any other extension using Y.Base.create.

var Parent = Y.Base.create("view", Y.View, [
    Extensions.ViewParent
], {
    ...
});

The extension uses the children attribute, so when instantiating or initializing the parent you'll want to add the child views.

var Parent = Y.Base.create(..., {
    ...,
    initializer : function(config) {
        this.set("children", {
            carousel : new Y.View({ ... }),
            featured : new Y.View({ ... }),
            sidebar  : new Y.View({ ... }),
            hot      : new Y.View({ ... })
        });
    }
});

Parent will require a render method since Y.View only provides a no-op stub by default.

var Parent = Y.Base.create(..., {
    ...,
    
    render : function() {
        this.get("container").setContent(this.template());
        
        return this;
    }
});

In this example the Parent handles setting its child views automatically, so we just need to instantiate it.

var parent = new Parent({ container : ".bd" }).render();

The extension will automatically render the child views into parent.container using the HTML5 data attributes child to determine where they should render themselves. Each child view's name in the views object should map to a DOM element with the same data-child attribute.

<div class="bd yui3-g">
    <div class="main yui3-u">
        <!-- "carousel" child will render into this div -->
        <div class="carousel" data-child="carousel"></div>
        
        <div class="yui3-g lists">
            <!-- "featured" child will render into this div -->
            <div class="yui3-u-1-2" data-child="featured"></div>
            
            <!-- "hot" child will render into this div -->
            <div class="yui3-u-1-2" data-child="hot"></div>
        </div>
    </div>
    
    <!-- "sidebar" child will render into this div -->
    <div class="sidebar yui3-u" data-child="sidebar"></div>
</div>

Child views are regular views, they don't need to do anything special to work with a parent. The only thing the extension does is ensure that events from the child view will bubble to the parent. Unfortunately, to do this it has to add a _viewparentchild property onto each child instance. It also adds a parent attribute to every child view with a reference to the parent Y.View instance.

You could potentially also nest parents to achieve a multi-level heirarchy of views but that definitely hasn't been tested & things might go crazy.

License

Copyright (c) 2013 Patrick Cavit

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
/*jshint yui:true */
YUI.add("extension-view-parent", function(Y) {
"use strict";
var ViewParent;
ViewParent = function() {};
ViewParent.ATTRS = {
children : {
value : false
}
};
ViewParent.prototype = {
initializer : function() {
this._viewParentHandles = [
//Make sure new child views bubble
this.on("childrenChange", this._childrenChange, this),
//Stick children into rendered DOM after the parent has rendered itself
Y.Do.after(this.renderChildren, this, "render", this)
];
//catch initial values of views ATTR
this._childrenChange({
newVal : this.get("children")
});
},
//destroy child views & clean up all handles
destructor : function() {
Y.Object.each(this.get("children"), function(view) {
view.destroy();
});
new Y.EventTarget(this._viewParentHandles).detach();
this._viewParentHandles = null;
},
renderChild : function(name, view) {
var parent = this.get("container"),
slot = parent.one("[data-child=\"" + name + "\"]"),
css;
if(!slot) {
return;
}
css = Y.Array.dedupe([
"child",
name,
view.name,
slot.get("className")
]);
view.render();
slot.replace(
view.get("container").addClass(css.join(" "))
);
},
//render all the child views & inject them into the placeholders
renderChildren : function() {
var children = this.get("children"),
name;
if(!children) {
return;
}
this.get("container").addClass("parent");
for(name in children) {
this.renderChild(name, children[name]);
}
},
//make sure custom events from child views bubble to parent view
_childrenChange : function(e) {
var self = this;
Y.Object.each(e.newVal, function(view) {
Y.stamp(view, true);
view.set("parent", self);
view.addTarget(self);
});
}
};
Y.namespace("Extensions").ViewParent = ViewParent;
}, "@VERSION@", {
requires : [
"view",
"event-custom"
]
});
<div class="bd yui3-g">
<div class="main yui3-u">
<div class="carousel" data-child="carousel"></div>
<div class="yui3-g lists">
<div class="item-list featured yui3-u-1-2" data-child="featured"></div>
<div class="item-list hot yui3-u-1-2" data-child="hot"></div>
</div>
</div>
<div class="sidebar yui3-u" data-child="sidebar"></div>
</div>
<div class="{{type}}">
<h3>{{title}}</h3>
<ol class="items">
{{#items}}
{{> item}}
{{/items}}
</ol>
<button class="browse r-arrow" data-tag="{{type}}">{{i18n "gemstore.home.browse"}}</button>
</div>
/*global YUI:true */
YUI.add("view-home-list", function(Y) {
var Templates = Y.namespace("GW2.Templates");
Y.namespace("GW2.Views").HomeList = Y.Base.create("homeListView", Y.View, [], {
template : Templates["home-list"],
events : {
".browse" : {
click : "_clickBrowse"
}
},
render : function() {
var items = this.get("models");
this.get("container").setHTML(this.template({
type : this.get("type"),
title : this.get("title"),
items : items.toJSON()
}));
return this;
},
_clickBrowse : function(e) {
e.preventDefault();
this.fire("search", {
search : {
tag : e.currentTarget.getData("tag")
}
});
}
}, {
ATTRS : {
type : null,
title : null
}
});
}, "@VERSION@", {
requires : [
"base",
"view",
"gw2-template-home-list",
"gw2-template-home-item",
"gw2-template-item-buttons"
]
});
/*global YUI:true */
YUI.add("view-home", function(Y) {
var L = Y.Lang,
gw2 = Y.namespace("GW2"),
Views = Y.namespace("GW2.Views"),
Extensions = Y.namespace("GW2.Extensions");
Views.Home = Y.Base.create("homeView", Y.View, [
Extensions.ViewParent
], {
template : Y.namespace("GW2.Templates").home,
initializer : function(config) {
this.set("views", {
carousel : new Views.HomeCarousel({
models : config.carousel
}),
featured : new Views.HomeList({
type : "featured",
models : config.featured
}),
hot : new Views.HomeList({
type : "hot",
models : config.hot
}),
sidebar : new Views.HomeSidebar({
history : config.history
})
});
},
//NO-OP
destructor : function() {},
render : function() {
this.get("container").setContent(this.template());
return this;
}
}, {
ATTRS : {
items : null
}
});
}, "@VERSION@", {
requires : [
"base",
"view",
"view-home-carousel",
"view-home-list",
"view-home-sidebar",
"extension-view-purchasing",
"extension-view-classer",
"extension-view-tooltips",
"tabview",
"scrollview",
"scrollview-paginator",
"gw2-template-home"
]
});
@matthewrobb
Copy link

I usually end up storing instances of "sub-views" on the parent instance. It's very common in cases where a "list" view using a collection of models uses two different API calls, one for listing and one for retrieving more information about an individual model. The choice there is to bind the entire list render to ANY collection or model activity or use sub-view instances that bind to the model events directly.

@alanning
Copy link

Internally addTarget uses Y.stamp so you may not need the _bubbled property as it looks like multiple calls to addTarget with the same parameters will not create duplicates. Did you run into issues where event targets were getting duplicated somehow before you added the _bubbled property?

@tivac
Copy link
Author

tivac commented Feb 13, 2013

@alanning Late response, but Y.stamp only actually modifies the object if you pass a truthy second parameter.

That being said, I now handle making sure the views are stamped using Y.stamp instead of my own custom property 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment