Skip to content

Instantly share code, notes, and snippets.

@evocateur
Forked from tivac/_README.md
Created May 15, 2013 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evocateur/5585987 to your computer and use it in GitHub Desktop.
Save evocateur/5585987 to your computer and use it in GitHub Desktop.

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.
YUI.add("extension-view-parent", function(Y) {
"use strict";
var ViewParent = function() {};
ViewParent.ATTRS = {
children : null
};
ViewParent.prototype = {
initializer: function() {
this._viewParentHandles = [
this.on("childrenChange", this._childrenChange, this),
Y.Do.after(this.renderChildren, this, "render", this)
];
// start off with initial state
this._childrenChange({
newVal : this.get("children")
});
},
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 node = this.get("container").one("[data-child=\"" + name + "\"]");
if(!node) {
return;
}
view.render();
node.replace(
view.get("container").addClass("child " + name + " " + node.get("className"))
);
},
renderChildren: function() {
var children = this.get("children"),
child;
if(!children) {
return;
}
this.get("container").addClass("parent");
for(child in children) {
this.renderChild(child, children[child]);
}
},
_childrenChange: function(e) {
var self = this;
Y.Object.each(e.newVal, function(child) {
// already stamped, bail
if("_viewparentchild" in child) {
return;
}
child._viewparentchild = true;
child.set("parent", self);
child.addTarget(self);
});
}
};
Y.namespace("Extensions").ViewParent = ViewParent;
}, "@VERSION@", {
requires: [
// YUI
"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"
]
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment