"&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/
```
And associate it by name using a view's `templateName` property:
``` javascript
AView = Ember.View.extend({
templateName: 'some-template'
});
```
Using a value for `templateName` that does not have a Handlebars template with a
matching `data-template-name` attribute will throw an error.
Assigning a value to both `template` and `templateName` properties will throw an error.
For views classes that may have a template later defined (e.g. as the block portion of a `{{view}}`
Handlebars helper call in another template or in a subclass), you can provide a `defaultTemplate`
property set to compiled template function. If a template is not later provided for the view
instance the `defaultTemplate` value will be used:
``` javascript
AView = Ember.View.extend({
defaultTemplate: Ember.Handlebars.compile('I was the default'),
template: null,
templateName: null
});
```
Will result in instances with an HTML representation of:
``` html
I was the default
```
If a `template` or `templateName` is provided it will take precedence over `defaultTemplate`:
``` javascript
AView = Ember.View.extend({
defaultTemplate: Ember.Handlebars.compile('I was the default')
});
aView = AView.create({
template: Ember.Handlebars.compile('I was the template, not default')
});
```
Will result in the following HTML representation when rendered:
``` html
I was the template, not default
```
## Layouts
Views can have a secondary template that wraps their main template. Like
primary templates, layouts can be any function that accepts an optional context
parameter and returns a string of HTML that will be inserted inside view's tag. Views whose HTML
element is self closing (e.g. ``) cannot have a layout and this property will be ignored.
Most typically in Ember a layout will be a compiled Ember.Handlebars template.
A view's layout can be set directly with the `layout` property or reference an
existing Handlebars template by name with the `layoutName` property.
A template used as a layout must contain a single use of the Handlebars `{{yield}}`
helper. The HTML contents of a view's rendered `template` will be inserted at this location:
``` javascript
AViewWithLayout = Ember.View.extend({
layout: Ember.Handlebars.compile("
{{yield}}
")
template: Ember.Handlebars.compile("I got wrapped"),
});
```
Will result in view instances with an HTML representation of:
``` html
I got wrapped
```
See `Handlebars.helpers.yield` for more information.
## Responding to Browser Events
Views can respond to user-initiated events in one of three ways: method implementation,
through an event manager, and through `{{action}}` helper use in their template or layout.
### Method Implementation
Views can respond to user-initiated events by implementing a method that matches the
event name. A `jQuery.Event` object will be passed as the argument to this method.
``` javascript
AView = Ember.View.extend({
click: function(event){
// will be called when when an instance's
// rendered element is clicked
}
});
```
### Event Managers
Views can define an object as their `eventManager` property. This object can then
implement methods that match the desired event names. Matching events that occur
on the view's rendered HTML or the rendered HTML of any of its DOM descendants
will trigger this method. A `jQuery.Event` object will be passed as the first
argument to the method and an `Ember.View` object as the second. The `Ember.View`
will be the view whose rendered HTML was interacted with. This may be the view with
the `eventManager` property or one of its descendent views.
``` javascript
AView = Ember.View.extend({
eventManager: Ember.Object.create({
doubleClick: function(event, view){
// will be called when when an instance's
// rendered element or any rendering
// of this views's descendent
// elements is clicked
}
})
});
```
An event defined for an event manager takes precedence over events of the same
name handled through methods on the view.
``` javascript
AView = Ember.View.extend({
mouseEnter: function(event){
// will never trigger.
},
eventManager: Ember.Object.create({
mouseEnter: function(event, view){
// takes presedence over AView#mouseEnter
}
})
});
```
Similarly a view's event manager will take precedence for events of any views
rendered as a descendent. A method name that matches an event name will not be called
if the view instance was rendered inside the HTML representation of a view that has
an `eventManager` property defined that handles events of the name. Events not handled
by the event manager will still trigger method calls on the descendent.
``` javascript
OuterView = Ember.View.extend({
template: Ember.Handlebars.compile("outer {{#view InnerView}}inner{{/view}} outer"),
eventManager: Ember.Object.create({
mouseEnter: function(event, view){
// view might be instance of either
// OutsideView or InnerView depending on
// where on the page the user interaction occured
}
})
});
InnerView = Ember.View.extend({
click: function(event){
// will be called if rendered inside
// an OuterView because OuterView's
// eventManager doesn't handle click events
},
mouseEnter: function(event){
// will never be called if rendered inside
// an OuterView.
}
});
```
### Handlebars `{{action}}` Helper
See `Handlebars.helpers.action`.
### Event Names
Possible events names for any of the responding approaches described above are:
Touch events: 'touchStart', 'touchMove', 'touchEnd', 'touchCancel'
Keyboard events: 'keyDown', 'keyUp', 'keyPress'
Mouse events: 'mouseDown', 'mouseUp', 'contextMenu', 'click', 'doubleClick', 'mouseMove',
'focusIn', 'focusOut', 'mouseEnter', 'mouseLeave'
Form events: 'submit', 'change', 'focusIn', 'focusOut', 'input'
HTML5 drag and drop events: 'dragStart', 'drag', 'dragEnter', 'dragLeave', 'drop', 'dragEnd'
## Handlebars `{{view}}` Helper
Other `Ember.View` instances can be included as part of a view's template by using the `{{view}}`
Handlebars helper. See `Handlebars.helpers.view` for additional information.
@class View
@namespace Ember
@extends Ember.Object
@uses Ember.Evented
*/
Ember.View = Ember.CoreView.extend(
/** @scope Ember.View.prototype */ {
concatenatedProperties: ['classNames', 'classNameBindings', 'attributeBindings'],
/**
@property isView
@type Boolean
@default true
@final
*/
isView: true,
// ..........................................................
// TEMPLATE SUPPORT
//
/**
The name of the template to lookup if no template is provided.
Ember.View will look for a template with this name in this view's
`templates` object. By default, this will be a global object
shared in `Ember.TEMPLATES`.
@property templateName
@type String
@default null
*/
templateName: null,
/**
The name of the layout to lookup if no layout is provided.
Ember.View will look for a template with this name in this view's
`templates` object. By default, this will be a global object
shared in `Ember.TEMPLATES`.
@property layoutName
@type String
@default null
*/
layoutName: null,
/**
The hash in which to look for `templateName`.
@property templates
@type Ember.Object
@default Ember.TEMPLATES
*/
templates: Ember.TEMPLATES,
/**
The template used to render the view. This should be a function that
accepts an optional context parameter and returns a string of HTML that
will be inserted into the DOM relative to its parent view.
In general, you should set the `templateName` property instead of setting
the template yourself.
@property template
@type Function
*/
template: Ember.computed(function(key, value) {
if (value !== undefined) { return value; }
var templateName = get(this, 'templateName'),
template = this.templateForName(templateName, 'template');
return template || get(this, 'defaultTemplate');
}).property('templateName'),
/**
The controller managing this view. If this property is set, it will be
made available for use by the template.
@property controller
@type Object
*/
controller: Ember.computed(function(key, value) {
var parentView;
if (arguments.length === 2) {
return value;
} else {
parentView = get(this, 'parentView');
return parentView ? get(parentView, 'controller') : null;
}
}).property(),
/**
A view may contain a layout. A layout is a regular template but
supersedes the `template` property during rendering. It is the
responsibility of the layout template to retrieve the `template`
property from the view (or alternatively, call `Handlebars.helpers.yield`,
`{{yield}}`) to render it in the correct location.
This is useful for a view that has a shared wrapper, but which delegates
the rendering of the contents of the wrapper to the `template` property
on a subclass.
@property layout
@type Function
*/
layout: Ember.computed(function(key, value) {
if (arguments.length === 2) { return value; }
var layoutName = get(this, 'layoutName'),
layout = this.templateForName(layoutName, 'layout');
return layout || get(this, 'defaultLayout');
}).property('layoutName'),
templateForName: function(name, type) {
if (!name) { return; }
var templates = get(this, 'templates'),
template = get(templates, name);
if (!template) {
throw new Ember.Error(fmt('%@ - Unable to find %@ "%@".', [this, type, name]));
}
return template;
},
/**
The object from which templates should access properties.
This object will be passed to the template function each time the render
method is called, but it is up to the individual function to decide what
to do with it.
By default, this will be the view itself.
@property context
@type Object
*/
context: Ember.computed(function(key, value) {
if (arguments.length === 2) {
set(this, '_context', value);
return value;
} else {
return get(this, '_context');
}
}).volatile(),
/**
@private
Private copy of the view's template context. This can be set directly
by Handlebars without triggering the observer that causes the view
to be re-rendered.
The context of a view is looked up as follows:
1. Supplied context (usually by Handlebars)
2. Specified controller
3. `parentView`'s context (for a child of a ContainerView)
The code in Handlebars that overrides the `_context` property first
checks to see whether the view has a specified controller. This is
something of a hack and should be revisited.
@property _context
*/
_context: Ember.computed(function(key, value) {
var parentView, controller;
if (arguments.length === 2) {
return value;
}
if (controller = get(this, 'controller')) {
return controller;
}
parentView = get(this, '_parentView');
if (parentView) {
return get(parentView, '_context');
}
return this;
}),
/**
@private
If a value that affects template rendering changes, the view should be
re-rendered to reflect the new value.
@method _displayPropertyDidChange
*/
_displayPropertyDidChange: Ember.observer(function() {
this.rerender();
}, 'context', 'controller'),
/**
If false, the view will appear hidden in DOM.
@property isVisible
@type Boolean
@default null
*/
isVisible: true,
/**
@private
Array of child views. You should never edit this array directly.
Instead, use appendChild and removeFromParent.
@property childViews
@type Array
@default []
*/
childViews: childViewsProperty,
_childViews: [],
// When it's a virtual view, we need to notify the parent that their
// childViews will change.
_childViewsWillChange: Ember.beforeObserver(function() {
if (this.isVirtual) {
var parentView = get(this, 'parentView');
if (parentView) { Ember.propertyWillChange(parentView, 'childViews'); }
}
}, 'childViews'),
// When it's a virtual view, we need to notify the parent that their
// childViews did change.
_childViewsDidChange: Ember.observer(function() {
if (this.isVirtual) {
var parentView = get(this, 'parentView');
if (parentView) { Ember.propertyDidChange(parentView, 'childViews'); }
}
}, 'childViews'),
/**
Return the nearest ancestor that is an instance of the provided
class.
@property nearestInstanceOf
@param {Class} klass Subclass of Ember.View (or Ember.View itself)
@return Ember.View
@deprecated
*/
nearestInstanceOf: function(klass) {
Ember.deprecate("nearestInstanceOf is deprecated and will be removed from future releases. Use nearestOfType.");
var view = get(this, 'parentView');
while (view) {
if(view instanceof klass) { return view; }
view = get(view, 'parentView');
}
},
/**
Return the nearest ancestor that is an instance of the provided
class or mixin.
@proprty nearestOfType
@param {Class,Mixin} klass Subclass of Ember.View (or Ember.View itself),
or an instance of Ember.Mixin.
@return Ember.View
*/
nearestOfType: function(klass) {
var view = get(this, 'parentView'),
isOfType = klass instanceof Ember.Mixin ?
function(view) { return klass.detect(view); } :
function(view) { return klass.detect(view.constructor); };
while (view) {
if( isOfType(view) ) { return view; }
view = get(view, 'parentView');
}
},
/**
Return the nearest ancestor that has a given property.
@property nearestWithProperty
@param {String} property A property name
@return Ember.View
*/
nearestWithProperty: function(property) {
var view = get(this, 'parentView');
while (view) {
if (property in view) { return view; }
view = get(view, 'parentView');
}
},
/**
Return the nearest ancestor whose parent is an instance of
`klass`.
@property nearestChildOf
@param {Class} klass Subclass of Ember.View (or Ember.View itself)
@return Ember.View
*/
nearestChildOf: function(klass) {
var view = get(this, 'parentView');
while (view) {
if(get(view, 'parentView') instanceof klass) { return view; }
view = get(view, 'parentView');
}
},
/**
Return the nearest ancestor that is an Ember.CollectionView
@property collectionView
@return Ember.CollectionView
*/
collectionView: Ember.computed(function() {
return this.nearestOfType(Ember.CollectionView);
}),
/**
Return the nearest ancestor that is a direct child of
an Ember.CollectionView
@property itemView
@return Ember.View
*/
itemView: Ember.computed(function() {
return this.nearestChildOf(Ember.CollectionView);
}),
/**
Return the nearest ancestor that has the property
`content`.
@property contentView
@return Ember.View
*/
contentView: Ember.computed(function() {
return this.nearestWithProperty('content');
}),
/**
@private
When the parent view changes, recursively invalidate
collectionView, itemView, and contentView
@method _parentViewDidChange
*/
_parentViewDidChange: Ember.observer(function() {
if (this.isDestroying) { return; }
this.invokeRecursively(function(view) {
view.propertyDidChange('collectionView');
view.propertyDidChange('itemView');
view.propertyDidChange('contentView');
});
if (get(this, 'parentView.controller') && !get(this, 'controller')) {
this.notifyPropertyChange('controller');
}
}, '_parentView'),
_controllerDidChange: Ember.observer(function() {
if (this.isDestroying) { return; }
this.forEachChildView(function(view) {
view.propertyDidChange('controller');
});
}, 'controller'),
cloneKeywords: function() {
var templateData = get(this, 'templateData');
var keywords = templateData ? Ember.copy(templateData.keywords) : {};
set(keywords, 'view', get(this, 'concreteView'));
set(keywords, 'controller', get(this, 'controller'));
return keywords;
},
/**
Called on your view when it should push strings of HTML into a
Ember.RenderBuffer. Most users will want to override the `template`
or `templateName` properties instead of this method.
By default, Ember.View will look for a function in the `template`
property and invoke it with the value of `context`. The value of
`context` will be the view's controller unless you override it.
@method render
@param {Ember.RenderBuffer} buffer The render buffer
*/
render: function(buffer) {
// If this view has a layout, it is the responsibility of the
// the layout to render the view's template. Otherwise, render the template
// directly.
var template = get(this, 'layout') || get(this, 'template');
if (template) {
var context = get(this, 'context');
var keywords = this.cloneKeywords();
var data = {
view: this,
buffer: buffer,
isRenderData: true,
keywords: keywords
};
// Invoke the template with the provided template context, which
// is the view by default. A hash of data is also passed that provides
// the template with access to the view and render buffer.
Ember.assert('template must be a function. Did you mean to call Ember.Handlebars.compile("...") or specify templateName instead?', typeof template === 'function');
// The template should write directly to the render buffer instead
// of returning a string.
var output = template(context, { data: data });
// If the template returned a string instead of writing to the buffer,
// push the string onto the buffer.
if (output !== undefined) { buffer.push(output); }
}
},
invokeForState: function(name) {
var stateName = this.state, args, fn;
// try to find the function for the state in the cache
if (fn = invokeForState[stateName][name]) {
args = a_slice.call(arguments);
args[0] = this;
return fn.apply(this, args);
}
// otherwise, find and cache the function for this state
var parent = this, states = parent.states, state;
while (states) {
state = states[stateName];
while (state) {
fn = state[name];
if (fn) {
invokeForState[stateName][name] = fn;
args = a_slice.call(arguments, 1);
args.unshift(this);
return fn.apply(this, args);
}
state = state.parentState;
}
states = states.parent;
}
},
/**
Renders the view again. This will work regardless of whether the
view is already in the DOM or not. If the view is in the DOM, the
rendering process will be deferred to give bindings a chance
to synchronize.
If children were added during the rendering process using `appendChild`,
`rerender` will remove them, because they will be added again
if needed by the next `render`.
In general, if the display of your view changes, you should modify
the DOM element directly instead of manually calling `rerender`, which can
be slow.
@method rerender
*/
rerender: function() {
return this.invokeForState('rerender');
},
clearRenderedChildren: function() {
var lengthBefore = this.lengthBeforeRender,
lengthAfter = this.lengthAfterRender;
// If there were child views created during the last call to render(),
// remove them under the assumption that they will be re-created when
// we re-render.
// VIEW-TODO: Unit test this path.
var childViews = this._childViews;
for (var i=lengthAfter-1; i>=lengthBefore; i--) {
if (childViews[i]) { childViews[i].destroy(); }
}
},
/**
@private
Iterates over the view's `classNameBindings` array, inserts the value
of the specified property into the `classNames` array, then creates an
observer to update the view's element if the bound property ever changes
in the future.
@method _applyClassNameBindings
*/
_applyClassNameBindings: function() {
var classBindings = get(this, 'classNameBindings'),
classNames = get(this, 'classNames'),
elem, newClass, dasherizedClass;
if (!classBindings) { return; }
// Loop through all of the configured bindings. These will be either
// property names ('isUrgent') or property paths relative to the view
// ('content.isUrgent')
a_forEach(classBindings, function(binding) {
// Variable in which the old class value is saved. The observer function
// closes over this variable, so it knows which string to remove when
// the property changes.
var oldClass;
// Extract just the property name from bindings like 'foo:bar'
var parsedPath = Ember.View._parsePropertyPath(binding);
// Set up an observer on the context. If the property changes, toggle the
// class name.
var observer = function() {
// Get the current value of the property
newClass = this._classStringForProperty(binding);
elem = this.$();
if (!elem) {
removeObserver(this, parsedPath.path, observer);
return;
}
// If we had previously added a class to the element, remove it.
if (oldClass) {
elem.removeClass(oldClass);
// Also remove from classNames so that if the view gets rerendered,
// the class doesn't get added back to the DOM.
classNames.removeObject(oldClass);
}
// If necessary, add a new class. Make sure we keep track of it so
// it can be removed in the future.
if (newClass) {
elem.addClass(newClass);
oldClass = newClass;
} else {
oldClass = null;
}
};
// Get the class name for the property at its current value
dasherizedClass = this._classStringForProperty(binding);
if (dasherizedClass) {
// Ensure that it gets into the classNames array
// so it is displayed when we render.
classNames.push(dasherizedClass);
// Save a reference to the class name so we can remove it
// if the observer fires. Remember that this variable has
// been closed over by the observer.
oldClass = dasherizedClass;
}
addObserver(this, parsedPath.path, observer);
this.one('willClearRender', function() {
removeObserver(this, parsedPath.path, observer);
});
}, this);
},
/**
@private
Iterates through the view's attribute bindings, sets up observers for each,
then applies the current value of the attributes to the passed render buffer.
@method _applyAttributeBindings
@param {Ember.RenderBuffer} buffer
*/
_applyAttributeBindings: function(buffer) {
var attributeBindings = get(this, 'attributeBindings'),
attributeValue, elem, type;
if (!attributeBindings) { return; }
a_forEach(attributeBindings, function(binding) {
var split = binding.split(':'),
property = split[0],
attributeName = split[1] || property;
// Create an observer to add/remove/change the attribute if the
// JavaScript property changes.
var observer = function() {
elem = this.$();
if (!elem) { return; }
attributeValue = get(this, property);
Ember.View.applyAttributeBindings(elem, attributeName, attributeValue);
};
addObserver(this, property, observer);
this.one('willClearRender', function() {
removeObserver(this, property, observer);
});
// Determine the current value and add it to the render buffer
// if necessary.
attributeValue = get(this, property);
Ember.View.applyAttributeBindings(buffer, attributeName, attributeValue);
}, this);
},
/**
@private
Given a property name, returns a dasherized version of that
property name if the property evaluates to a non-falsy value.
For example, if the view has property `isUrgent` that evaluates to true,
passing `isUrgent` to this method will return `"is-urgent"`.
@method _classStringForProperty
@param property
*/
_classStringForProperty: function(property) {
var parsedPath = Ember.View._parsePropertyPath(property);
var path = parsedPath.path;
var val = get(this, path);
if (val === undefined && Ember.isGlobalPath(path)) {
val = get(Ember.lookup, path);
}
return Ember.View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName);
},
// ..........................................................
// ELEMENT SUPPORT
//
/**
Returns the current DOM element for the view.
@property element
@type DOMElement
*/
element: Ember.computed(function(key, value) {
if (value !== undefined) {
return this.invokeForState('setElement', value);
} else {
return this.invokeForState('getElement');
}
}).property('_parentView'),
/**
Returns a jQuery object for this view's element. If you pass in a selector
string, this method will return a jQuery object, using the current element
as its buffer.
For example, calling `view.$('li')` will return a jQuery object containing
all of the `li` elements inside the DOM element of this view.
@property $
@param {String} [selector] a jQuery-compatible selector string
@return {jQuery} the CoreQuery object for the DOM node
*/
$: function(sel) {
return this.invokeForState('$', sel);
},
mutateChildViews: function(callback) {
var childViews = this._childViews,
idx = childViews.length,
view;
while(--idx >= 0) {
view = childViews[idx];
callback.call(this, view, idx);
}
return this;
},
forEachChildView: function(callback) {
var childViews = this._childViews;
if (!childViews) { return this; }
var len = childViews.length,
view, idx;
for(idx = 0; idx < len; idx++) {
view = childViews[idx];
callback.call(this, view);
}
return this;
},
/**
Appends the view's element to the specified parent element.
If the view does not have an HTML representation yet, `createElement()`
will be called automatically.
Note that this method just schedules the view to be appended; the DOM
element will not be appended to the given element until all bindings have
finished synchronizing.
This is not typically a function that you will need to call directly
when building your application. You might consider using Ember.ContainerView
instead. If you do need to use appendTo, be sure that the target element you
are providing is associated with an Ember.Application and does not have an
ancestor element that is associated with an Ember view.
@method appendTo
@param {String|DOMElement|jQuery} A selector, element, HTML string, or jQuery object
@return {Ember.View} receiver
*/
appendTo: function(target) {
// Schedule the DOM element to be created and appended to the given
// element after bindings have synchronized.
this._insertElementLater(function() {
Ember.assert("You cannot append to an existing Ember.View. Consider using Ember.ContainerView instead.", !Ember.$(target).is('.ember-view') && !Ember.$(target).parents().is('.ember-view'));
this.$().appendTo(target);
});
return this;
},
/**
Replaces the content of the specified parent element with this view's element.
If the view does not have an HTML representation yet, `createElement()`
will be called automatically.
Note that this method just schedules the view to be appended; the DOM
element will not be appended to the given element until all bindings have
finished synchronizing
@method replaceIn
@param {String|DOMElement|jQuery} A selector, element, HTML string, or jQuery object
@return {Ember.View} received
*/
replaceIn: function(target) {
Ember.assert("You cannot replace an existing Ember.View. Consider using Ember.ContainerView instead.", !Ember.$(target).is('.ember-view') && !Ember.$(target).parents().is('.ember-view'));
this._insertElementLater(function() {
Ember.$(target).empty();
this.$().appendTo(target);
});
return this;
},
/**
@private
Schedules a DOM operation to occur during the next render phase. This
ensures that all bindings have finished synchronizing before the view is
rendered.
To use, pass a function that performs a DOM operation..
Before your function is called, this view and all child views will receive
the `willInsertElement` event. After your function is invoked, this view
and all of its child views will receive the `didInsertElement` event.
view._insertElementLater(function() {
this.createElement();
this.$().appendTo('body');
});
@method _insertElementLater
@param {Function} fn the function that inserts the element into the DOM
*/
_insertElementLater: function(fn) {
this._scheduledInsert = Ember.run.scheduleOnce('render', this, '_insertElement', fn);
},
/**
@private
*/
_insertElement: function (fn) {
this._scheduledInsert = null;
this.invokeForState('insertElement', fn);
},
/**
Appends the view's element to the document body. If the view does
not have an HTML representation yet, `createElement()` will be called
automatically.
Note that this method just schedules the view to be appended; the DOM
element will not be appended to the document body until all bindings have
finished synchronizing.
@method append
@return {Ember.View} receiver
*/
append: function() {
return this.appendTo(document.body);
},
/**
Removes the view's element from the element to which it is attached.
@method remove
@return {Ember.View} receiver
*/
remove: function() {
// What we should really do here is wait until the end of the run loop
// to determine if the element has been re-appended to a different
// element.
// In the interim, we will just re-render if that happens. It is more
// important than elements get garbage collected.
this.destroyElement();
this.invokeRecursively(function(view) {
view.clearRenderedChildren();
});
},
/**
The ID to use when trying to locate the element in the DOM. If you do not
set the elementId explicitly, then the view's GUID will be used instead.
This ID must be set at the time the view is created.
@property elementId
@type String
*/
elementId: Ember.computed(function(key, value) {
return value !== undefined ? value : Ember.guidFor(this);
}),
// TODO: Perhaps this should be removed from the production build somehow.
_elementIdDidChange: Ember.beforeObserver(function() {
throw "Changing a view's elementId after creation is not allowed.";
}, 'elementId'),
/**
Attempts to discover the element in the parent element. The default
implementation looks for an element with an ID of elementId (or the view's
guid if elementId is null). You can override this method to provide your
own form of lookup. For example, if you want to discover your element
using a CSS class name instead of an ID.
@method findElementInParentElement
@param {DOMElement} parentElement The parent's DOM element
@return {DOMElement} The discovered element
*/
findElementInParentElement: function(parentElem) {
var id = "#" + get(this, 'elementId');
return Ember.$(id)[0] || Ember.$(id, parentElem)[0];
},
/**
Creates a DOM representation of the view and all of its
child views by recursively calling the `render()` method.
After the element has been created, `didInsertElement` will
be called on this view and all of its child views.
@method createElement
@return {Ember.View} receiver
*/
createElement: function() {
if (get(this, 'element')) { return this; }
var buffer = this.renderToBuffer();
set(this, 'element', buffer.element());
return this;
},
/**
Called when a view is going to insert an element into the DOM.
@event willInsertElement
*/
willInsertElement: Ember.K,
/**
Called when the element of the view has been inserted into the DOM.
Override this function to do any set up that requires an element in the
document body.
@event didInsertElement
*/
didInsertElement: Ember.K,
/**
Called when the view is about to rerender, but before anything has
been torn down. This is a good opportunity to tear down any manual
observers you have installed based on the DOM state
@event willClearRender
*/
willClearRender: Ember.K,
/**
@private
Run this callback on the current view and recursively on child views.
@method invokeRecursively
@param fn {Function}
*/
invokeRecursively: function(fn) {
fn.call(this, this);
this.forEachChildView(function(view) {
view.invokeRecursively(fn);
});
},
/**
Invalidates the cache for a property on all child views.
@method invalidateRecursively
*/
invalidateRecursively: function(key) {
this.forEachChildView(function(view) {
view.propertyDidChange(key);
});
},
/**
@private
Invokes the receiver's willInsertElement() method if it exists and then
invokes the same on all child views.
NOTE: In some cases this was called when the element existed. This no longer
works so we let people know. We can remove this warning code later.
@method _notifyWillInsertElement
*/
_notifyWillInsertElement: function() {
this.invokeRecursively(function(view) {
view.trigger('willInsertElement');
});
},
/**
@private
Invokes the receiver's didInsertElement() method if it exists and then
invokes the same on all child views.
@method _notifyDidInsertElement
*/
_notifyDidInsertElement: function() {
this.invokeRecursively(function(view) {
view.trigger('didInsertElement');
});
},
/**
@private
Triggers the `willClearRender` event (which invokes the `willClearRender()`
method if it exists) on this view and all child views.
@method _notifyWillClearRender
*/
_notifyWillClearRender: function() {
this.invokeRecursively(function(view) {
view.trigger('willClearRender');
});
},
/**
Destroys any existing element along with the element for any child views
as well. If the view does not currently have a element, then this method
will do nothing.
If you implement willDestroyElement() on your view, then this method will
be invoked on your view before your element is destroyed to give you a
chance to clean up any event handlers, etc.
If you write a willDestroyElement() handler, you can assume that your
didInsertElement() handler was called earlier for the same element.
Normally you will not call or override this method yourself, but you may
want to implement the above callbacks when it is run.
@method destroyElement
@return {Ember.View} receiver
*/
destroyElement: function() {
return this.invokeForState('destroyElement');
},
/**
Called when the element of the view is going to be destroyed. Override
this function to do any teardown that requires an element, like removing
event listeners.
@event willDestroyElement
*/
willDestroyElement: function() {},
/**
@private
Triggers the `willDestroyElement` event (which invokes the `willDestroyElement()`
method if it exists) on this view and all child views.
Before triggering `willDestroyElement`, it first triggers the `willClearRender`
event recursively.
@method _notifyWillDestroyElement
*/
_notifyWillDestroyElement: function() {
this._notifyWillClearRender();
this.invokeRecursively(function(view) {
view.trigger('willDestroyElement');
});
},
_elementWillChange: Ember.beforeObserver(function() {
this.forEachChildView(function(view) {
Ember.propertyWillChange(view, 'element');
});
}, 'element'),
/**
@private
If this view's element changes, we need to invalidate the caches of our
child views so that we do not retain references to DOM elements that are
no longer needed.
@method _elementDidChange
*/
_elementDidChange: Ember.observer(function() {
this.forEachChildView(function(view) {
Ember.propertyDidChange(view, 'element');
});
}, 'element'),
/**
Called when the parentView property has changed.
@event parentViewDidChange
*/
parentViewDidChange: Ember.K,
instrumentName: 'render.view',
instrumentDetails: function(hash) {
hash.template = get(this, 'templateName');
this._super(hash);
},
_renderToBuffer: function(parentBuffer, bufferOperation) {
this.lengthBeforeRender = this._childViews.length;
var buffer = this._super(parentBuffer, bufferOperation);
this.lengthAfterRender = this._childViews.length;
return buffer;
},
renderToBufferIfNeeded: function () {
return this.invokeForState('renderToBufferIfNeeded', this);
},
beforeRender: function(buffer) {
this.applyAttributesToBuffer(buffer);
},
afterRender: Ember.K,
applyAttributesToBuffer: function(buffer) {
// Creates observers for all registered class name and attribute bindings,
// then adds them to the element.
this._applyClassNameBindings();
// Pass the render buffer so the method can apply attributes directly.
// This isn't needed for class name bindings because they use the
// existing classNames infrastructure.
this._applyAttributeBindings(buffer);
a_forEach(get(this, 'classNames'), function(name){ buffer.addClass(name); });
buffer.id(get(this, 'elementId'));
var role = get(this, 'ariaRole');
if (role) {
buffer.attr('role', role);
}
if (get(this, 'isVisible') === false) {
buffer.style('display', 'none');
}
},
// ..........................................................
// STANDARD RENDER PROPERTIES
//
/**
Tag name for the view's outer element. The tag name is only used when
an element is first created. If you change the tagName for an element, you
must destroy and recreate the view element.
By default, the render buffer will use a `
` tag for views.
@property tagName
@type String
@default null
*/
// We leave this null by default so we can tell the difference between
// the default case and a user-specified tag.
tagName: null,
/**
The WAI-ARIA role of the control represented by this view. For example, a
button may have a role of type 'button', or a pane may have a role of
type 'alertdialog'. This property is used by assistive software to help
visually challenged users navigate rich web applications.
The full list of valid WAI-ARIA roles is available at:
http://www.w3.org/TR/wai-aria/roles#roles_categorization
@property ariaRole
@type String
@default null
*/
ariaRole: null,
/**
Standard CSS class names to apply to the view's outer element. This
property automatically inherits any class names defined by the view's
superclasses as well.
@property classNames
@type Array
@default ['ember-view']
*/
classNames: ['ember-view'],
/**
A list of properties of the view to apply as class names. If the property
is a string value, the value of that string will be applied as a class
name.
// Applies the 'high' class to the view element
Ember.View.create({
classNameBindings: ['priority']
priority: 'high'
});
If the value of the property is a Boolean, the name of that property is
added as a dasherized class name.
// Applies the 'is-urgent' class to the view element
Ember.View.create({
classNameBindings: ['isUrgent']
isUrgent: true
});
If you would prefer to use a custom value instead of the dasherized
property name, you can pass a binding like this:
// Applies the 'urgent' class to the view element
Ember.View.create({
classNameBindings: ['isUrgent:urgent']
isUrgent: true
});
This list of properties is inherited from the view's superclasses as well.
@property classNameBindings
@type Array
@default []
*/
classNameBindings: [],
/**
A list of properties of the view to apply as attributes. If the property is
a string value, the value of that string will be applied as the attribute.
// Applies the type attribute to the element
// with the value "button", like
Ember.View.create({
attributeBindings: ['type'],
type: 'button'
});
If the value of the property is a Boolean, the name of that property is
added as an attribute.
// Renders something like
Ember.View.create({
attributeBindings: ['enabled'],
enabled: true
});
@property attributeBindings
*/
attributeBindings: [],
// .......................................................
// CORE DISPLAY METHODS
//
/**
@private
Setup a view, but do not finish waking it up.
- configure childViews
- register the view with the global views hash, which is used for event
dispatch
@method init
*/
init: function() {
this._super();
// setup child views. be sure to clone the child views array first
this._childViews = this._childViews.slice();
Ember.assert("Only arrays are allowed for 'classNameBindings'", Ember.typeOf(this.classNameBindings) === 'array');
this.classNameBindings = Ember.A(this.classNameBindings.slice());
Ember.assert("Only arrays are allowed for 'classNames'", Ember.typeOf(this.classNames) === 'array');
this.classNames = Ember.A(this.classNames.slice());
var viewController = get(this, 'viewController');
if (viewController) {
viewController = get(viewController);
if (viewController) {
set(viewController, 'view', this);
}
}
},
appendChild: function(view, options) {
return this.invokeForState('appendChild', view, options);
},
/**
Removes the child view from the parent view.
@method removeChild
@param {Ember.View} view
@return {Ember.View} receiver
*/
removeChild: function(view) {
// If we're destroying, the entire subtree will be
// freed, and the DOM will be handled separately,
// so no need to mess with childViews.
if (this.isDestroying) { return; }
// update parent node
set(view, '_parentView', null);
// remove view from childViews array.
var childViews = this._childViews;
Ember.EnumerableUtils.removeObject(childViews, view);
this.propertyDidChange('childViews'); // HUH?! what happened to will change?
return this;
},
/**
Removes all children from the parentView.
@method removeAllChildren
@return {Ember.View} receiver
*/
removeAllChildren: function() {
return this.mutateChildViews(function(view) {
this.removeChild(view);
});
},
destroyAllChildren: function() {
return this.mutateChildViews(function(view) {
view.destroy();
});
},
/**
Removes the view from its parentView, if one is found. Otherwise
does nothing.
@method removeFromParent
@return {Ember.View} receiver
*/
removeFromParent: function() {
var parent = get(this, '_parentView');
// Remove DOM element from parent
this.remove();
if (parent) { parent.removeChild(this); }
return this;
},
/**
You must call `destroy` on a view to destroy the view (and all of its
child views). This will remove the view from any parent node, then make
sure that the DOM element managed by the view can be released by the
memory manager.
@method willDestroy
*/
willDestroy: function() {
// calling this._super() will nuke computed properties and observers,
// so collect any information we need before calling super.
var childViews = this._childViews,
parent = get(this, '_parentView'),
childLen;
// destroy the element -- this will avoid each child view destroying
// the element over and over again...
if (!this.removedFromDOM) { this.destroyElement(); }
// remove from non-virtual parent view if viewName was specified
if (this.viewName) {
var nonVirtualParentView = get(this, 'parentView');
if (nonVirtualParentView) {
set(nonVirtualParentView, this.viewName, null);
}
}
// remove from parent if found. Don't call removeFromParent,
// as removeFromParent will try to remove the element from
// the DOM again.
if (parent) { parent.removeChild(this); }
this.state = 'destroyed';
childLen = childViews.length;
for (var i=childLen-1; i>=0; i--) {
childViews[i].removedFromDOM = true;
childViews[i].destroy();
}
// next remove view from global hash
if (!this.isVirtual) delete Ember.View.views[get(this, 'elementId')];
},
/**
Instantiates a view to be added to the childViews array during view
initialization. You generally will not call this method directly unless
you are overriding createChildViews(). Note that this method will
automatically configure the correct settings on the new view instance to
act as a child of the parent.
@method createChildView
@param {Class} viewClass
@param {Hash} [attrs] Attributes to add
@return {Ember.View} new instance
*/
createChildView: function(view, attrs) {
if (Ember.CoreView.detect(view)) {
attrs = attrs || {};
attrs._parentView = this;
attrs.templateData = attrs.templateData || get(this, 'templateData');
view = view.create(attrs);
// don't set the property on a virtual view, as they are invisible to
// consumers of the view API
if (view.viewName) { set(get(this, 'concreteView'), view.viewName, view); }
} else {
Ember.assert('You must pass instance or subclass of View', view instanceof Ember.CoreView);
Ember.assert("You can only pass attributes when a class is provided", !attrs);
if (!get(view, 'templateData')) {
set(view, 'templateData', get(this, 'templateData'));
}
set(view, '_parentView', this);
}
return view;
},
becameVisible: Ember.K,
becameHidden: Ember.K,
/**
@private
When the view's `isVisible` property changes, toggle the visibility
element of the actual DOM element.
@method _isVisibleDidChange
*/
_isVisibleDidChange: Ember.observer(function() {
var $el = this.$();
if (!$el) { return; }
var isVisible = get(this, 'isVisible');
$el.toggle(isVisible);
if (this._isAncestorHidden()) { return; }
if (isVisible) {
this._notifyBecameVisible();
} else {
this._notifyBecameHidden();
}
}, 'isVisible'),
_notifyBecameVisible: function() {
this.trigger('becameVisible');
this.forEachChildView(function(view) {
var isVisible = get(view, 'isVisible');
if (isVisible || isVisible === null) {
view._notifyBecameVisible();
}
});
},
_notifyBecameHidden: function() {
this.trigger('becameHidden');
this.forEachChildView(function(view) {
var isVisible = get(view, 'isVisible');
if (isVisible || isVisible === null) {
view._notifyBecameHidden();
}
});
},
_isAncestorHidden: function() {
var parent = get(this, 'parentView');
while (parent) {
if (get(parent, 'isVisible') === false) { return true; }
parent = get(parent, 'parentView');
}
return false;
},
clearBuffer: function() {
this.invokeRecursively(function(view) {
this.buffer = null;
});
},
transitionTo: function(state, children) {
this.state = state;
if (children !== false) {
this.forEachChildView(function(view) {
view.transitionTo(state);
});
}
},
// .......................................................
// EVENT HANDLING
//
/**
@private
Handle events from `Ember.EventDispatcher`
@method handleEvent
@param eventName {String}
@param evt {Event}
*/
handleEvent: function(eventName, evt) {
return this.invokeForState('handleEvent', eventName, evt);
}
});
/*
Describe how the specified actions should behave in the various
states that a view can exist in. Possible states:
* preRender: when a view is first instantiated, and after its
element was destroyed, it is in the preRender state
* inBuffer: once a view has been rendered, but before it has
been inserted into the DOM, it is in the inBuffer state
* inDOM: once a view has been inserted into the DOM it is in
the inDOM state. A view spends the vast majority of its
existence in this state.
* destroyed: once a view has been destroyed (using the destroy
method), it is in this state. No further actions can be invoked
on a destroyed view.
*/
// in the destroyed state, everything is illegal
// before rendering has begun, all legal manipulations are noops.
// inside the buffer, legal manipulations are done on the buffer
// once the view has been inserted into the DOM, legal manipulations
// are done on the DOM element.
var DOMManager = {
prepend: function(view, html) {
view.$().prepend(html);
},
after: function(view, html) {
view.$().after(html);
},
html: function(view, html) {
view.$().html(html);
},
replace: function(view) {
var element = get(view, 'element');
set(view, 'element', null);
view._insertElementLater(function() {
Ember.$(element).replaceWith(get(view, 'element'));
});
},
remove: function(view) {
view.$().remove();
},
empty: function(view) {
view.$().empty();
}
};
Ember.View.reopen({
states: Ember.View.states,
domManager: DOMManager
});
Ember.View.reopenClass({
/**
@private
Parse a path and return an object which holds the parsed properties.
For example a path like "content.isEnabled:enabled:disabled" wil return the
following object:
{
path: "content.isEnabled",
className: "enabled",
falsyClassName: "disabled",
classNames: ":enabled:disabled"
}
@method _parsePropertyPath
@static
*/
_parsePropertyPath: function(path) {
var split = path.split(':'),
propertyPath = split[0],
classNames = "",
className,
falsyClassName;
// check if the property is defined as prop:class or prop:trueClass:falseClass
if (split.length > 1) {
className = split[1];
if (split.length === 3) { falsyClassName = split[2]; }
classNames = ':' + className;
if (falsyClassName) { classNames += ":" + falsyClassName; }
}
return {
path: propertyPath,
classNames: classNames,
className: (className === '') ? undefined : className,
falsyClassName: falsyClassName
};
},
/**
@private
Get the class name for a given value, based on the path, optional className
and optional falsyClassName.
- if a className or falsyClassName has been specified:
- if the value is truthy and className has been specified, className is returned
- if the value is falsy and falsyClassName has been specified, falsyClassName is returned
- otherwise null is returned
- if the value is true, the dasherized last part of the supplied path is returned
- if the value is not false, undefined or null, the value is returned
- if none of the above rules apply, null is returned
@method _classStringForValue
@param path
@param val
@param className
@param falsyClassName
@static
*/
_classStringForValue: function(path, val, className, falsyClassName) {
// When using the colon syntax, evaluate the truthiness or falsiness
// of the value to determine which className to return
if (className || falsyClassName) {
if (className && !!val) {
return className;
} else if (falsyClassName && !val) {
return falsyClassName;
} else {
return null;
}
// If value is a Boolean and true, return the dasherized property
// name.
} else if (val === true) {
// Normalize property path to be suitable for use
// as a class name. For exaple, content.foo.barBaz
// becomes bar-baz.
var parts = path.split('.');
return Ember.String.dasherize(parts[parts.length-1]);
// If the value is not false, undefined, or null, return the current
// value of the property.
} else if (val !== false && val !== undefined && val !== null) {
return val;
// Nothing to display. Return null so that the old class is removed
// but no new class is added.
} else {
return null;
}
}
});
/**
Global views hash
@property views
@static
@type Hash
*/
Ember.View.views = {};
// If someone overrides the child views computed property when
// defining their class, we want to be able to process the user's
// supplied childViews and then restore the original computed property
// at view initialization time. This happens in Ember.ContainerView's init
// method.
Ember.View.childViewsProperty = childViewsProperty;
Ember.View.applyAttributeBindings = function(elem, name, value) {
var type = Ember.typeOf(value);
var currentValue = elem.attr(name);
// if this changes, also change the logic in ember-handlebars/lib/helpers/binding.js
if ((type === 'string' || (type === 'number' && !isNaN(value))) && value !== currentValue) {
elem.attr(name, value);
} else if (value && type === 'boolean') {
elem.attr(name, name);
} else if (!value) {
elem.removeAttr(name);
}
};
})();
(function() {
/**
@module ember
@submodule ember-views
*/
var get = Ember.get, set = Ember.set;
Ember.View.states = {
_default: {
// appendChild is only legal while rendering the buffer.
appendChild: function() {
throw "You can't use appendChild outside of the rendering process";
},
$: function() {
return undefined;
},
getElement: function() {
return null;
},
// Handle events from `Ember.EventDispatcher`
handleEvent: function() {
return true; // continue event propagation
},
destroyElement: function(view) {
set(view, 'element', null);
if (view._scheduledInsert) {
Ember.run.cancel(view._scheduledInsert);
view._scheduledInsert = null;
}
return view;
},
renderToBufferIfNeeded: function () {
return false;
}
}
};
Ember.View.reopen({
states: Ember.View.states
});
})();
(function() {
/**
@module ember
@submodule ember-views
*/
Ember.View.states.preRender = {
parentState: Ember.View.states._default,
// a view leaves the preRender state once its element has been
// created (createElement).
insertElement: function(view, fn) {
view.createElement();
view._notifyWillInsertElement();
// after createElement, the view will be in the hasElement state.
fn.call(view);
view.transitionTo('inDOM');
view._notifyDidInsertElement();
},
renderToBufferIfNeeded: function(view) {
return view.renderToBuffer();
},
empty: Ember.K,
setElement: function(view, value) {
if (value !== null) {
view.transitionTo('hasElement');
}
return value;
}
};
})();
(function() {
/**
@module ember
@submodule ember-views
*/
var get = Ember.get, set = Ember.set, meta = Ember.meta;
Ember.View.states.inBuffer = {
parentState: Ember.View.states._default,
$: function(view, sel) {
// if we don't have an element yet, someone calling this.$() is
// trying to update an element that isn't in the DOM. Instead,
// rerender the view to allow the render method to reflect the
// changes.
view.rerender();
return Ember.$();
},
// when a view is rendered in a buffer, rerendering it simply
// replaces the existing buffer with a new one
rerender: function(view) {
Ember.deprecate("Something you did caused a view to re-render after it rendered but before it was inserted into the DOM. Because this is avoidable and the cause of significant performance issues in applications, this behavior is deprecated. If you want to use the debugger to find out what caused this, you can set ENV.RAISE_ON_DEPRECATION to true.");
view._notifyWillClearRender();
view.clearRenderedChildren();
view.renderToBuffer(view.buffer, 'replaceWith');
},
// when a view is rendered in a buffer, appending a child
// view will render that view and append the resulting
// buffer into its buffer.
appendChild: function(view, childView, options) {
var buffer = view.buffer;
childView = this.createChildView(childView, options);
view._childViews.push(childView);
childView.renderToBuffer(buffer);
view.propertyDidChange('childViews');
return childView;
},
// when a view is rendered in a buffer, destroying the
// element will simply destroy the buffer and put the
// state back into the preRender state.
destroyElement: function(view) {
view.clearBuffer();
view._notifyWillDestroyElement();
view.transitionTo('preRender');
return view;
},
empty: function() {
Ember.assert("Emptying a view in the inBuffer state is not allowed and should not happen under normal circumstances. Most likely there is a bug in your application. This may be due to excessive property change notifications.");
},
renderToBufferIfNeeded: function (view) {
return view.buffer;
},
// It should be impossible for a rendered view to be scheduled for
// insertion.
insertElement: function() {
throw "You can't insert an element that has already been rendered";
},
setElement: function(view, value) {
if (value === null) {
view.transitionTo('preRender');
} else {
view.clearBuffer();
view.transitionTo('hasElement');
}
return value;
}
};
})();
(function() {
/**
@module ember
@submodule ember-views
*/
var get = Ember.get, set = Ember.set, meta = Ember.meta;
Ember.View.states.hasElement = {
parentState: Ember.View.states._default,
$: function(view, sel) {
var elem = get(view, 'element');
return sel ? Ember.$(sel, elem) : Ember.$(elem);
},
getElement: function(view) {
var parent = get(view, 'parentView');
if (parent) { parent = get(parent, 'element'); }
if (parent) { return view.findElementInParentElement(parent); }
return Ember.$("#" + get(view, 'elementId'))[0];
},
setElement: function(view, value) {
if (value === null) {
view.transitionTo('preRender');
} else {
throw "You cannot set an element to a non-null value when the element is already in the DOM.";
}
return value;
},
// once the view has been inserted into the DOM, rerendering is
// deferred to allow bindings to synchronize.
rerender: function(view) {
view._notifyWillClearRender();
view.clearRenderedChildren();
view.domManager.replace(view);
return view;
},
// once the view is already in the DOM, destroying it removes it
// from the DOM, nukes its element, and puts it back into the
// preRender state if inDOM.
destroyElement: function(view) {
view._notifyWillDestroyElement();
view.domManager.remove(view);
set(view, 'element', null);
if (view._scheduledInsert) {
Ember.run.cancel(view._scheduledInsert);
view._scheduledInsert = null;
}
return view;
},
empty: function(view) {
var _childViews = view._childViews, len, idx;
if (_childViews) {
len = _childViews.length;
for (idx = 0; idx < len; idx++) {
_childViews[idx]._notifyWillDestroyElement();
}
}
view.domManager.empty(view);
},
// Handle events from `Ember.EventDispatcher`
handleEvent: function(view, eventName, evt) {
if (view.has(eventName)) {
// Handler should be able to re-dispatch events, so we don't
// preventDefault or stopPropagation.
return view.trigger(eventName, evt);
} else {
return true; // continue event propagation
}
}
};
Ember.View.states.inDOM = {
parentState: Ember.View.states.hasElement,
insertElement: function(view, fn) {
throw "You can't insert an element into the DOM that has already been inserted";
}
};
})();
(function() {
/**
@module ember
@submodule ember-views
*/
var destroyedError = "You can't call %@ on a destroyed view", fmt = Ember.String.fmt;
Ember.View.states.destroyed = {
parentState: Ember.View.states._default,
appendChild: function() {
throw fmt(destroyedError, ['appendChild']);
},
rerender: function() {
throw fmt(destroyedError, ['rerender']);
},
destroyElement: function() {
throw fmt(destroyedError, ['destroyElement']);
},
empty: function() {
throw fmt(destroyedError, ['empty']);
},
setElement: function() {
throw fmt(destroyedError, ["set('element', ...)"]);
},
renderToBufferIfNeeded: function() {
throw fmt(destroyedError, ["renderToBufferIfNeeded"]);
},
// Since element insertion is scheduled, don't do anything if
// the view has been destroyed between scheduling and execution
insertElement: Ember.K
};
})();
(function() {
})();
(function() {
/**
@module ember
@submodule ember-views
*/
var get = Ember.get, set = Ember.set, meta = Ember.meta;
var forEach = Ember.EnumerableUtils.forEach;
var childViewsProperty = Ember.computed(function() {
return get(this, '_childViews');
}).property('_childViews');
/**
A `ContainerView` is an `Ember.View` subclass that allows for manual or programatic
management of a view's `childViews` array that will correctly update the `ContainerView`
instance's rendered DOM representation.
## Setting Initial Child Views
The initial array of child views can be set in one of two ways. You can provide
a `childViews` property at creation time that contains instance of `Ember.View`:
``` javascript
aContainer = Ember.ContainerView.create({
childViews: [Ember.View.create(), Ember.View.create()]
});
```
You can also provide a list of property names whose values are instances of `Ember.View`:
``` javascript
aContainer = Ember.ContainerView.create({
childViews: ['aView', 'bView', 'cView'],
aView: Ember.View.create(),
bView: Ember.View.create()
cView: Ember.View.create()
});
```
The two strategies can be combined:
``` javascript
aContainer = Ember.ContainerView.create({
childViews: ['aView', Ember.View.create()],
aView: Ember.View.create()
});
```
Each child view's rendering will be inserted into the container's rendered HTML in the same
order as its position in the `childViews` property.
## Adding and Removing Child Views
The views in a container's `childViews` array should be added and removed by manipulating
the `childViews` property directly.
To remove a view pass that view into a `removeObject` call on the container's `childViews` property.
Given an empty `` the following code
``` javascript
aContainer = Ember.ContainerView.create({
classNames: ['the-container'],
childViews: ['aView', 'bView'],
aView: Ember.View.create({
template: Ember.Handlebars.compile("A")
}),
bView: Ember.View.create({
template: Ember.Handlebars.compile("B")
})
});
aContainer.appendTo('body');
```
Results in the HTML
``` html
A
B
```
Removing a view
``` javascript
aContainer.get('childViews'); // [aContainer.aView, aContainer.bView]
aContainer.get('childViews').removeObject(aContainer.get('bView'));
aContainer.get('childViews'); // [aContainer.aView]
```
Will result in the following HTML
``` html
A
```
Similarly, adding a child view is accomplished by adding `Ember.View` instances to the
container's `childViews` property.
Given an empty `` the following code
``` javascript
aContainer = Ember.ContainerView.create({
classNames: ['the-container'],
childViews: ['aView', 'bView'],
aView: Ember.View.create({
template: Ember.Handlebars.compile("A")
}),
bView: Ember.View.create({
template: Ember.Handlebars.compile("B")
})
});
aContainer.appendTo('body');
```
Results in the HTML
``` html
A
B
```
Adding a view
``` javascript
AnotherViewClass = Ember.View.extend({
template: Ember.Handlebars.compile("Another view")
});
aContainer.get('childViews'); // [aContainer.aView, aContainer.bView]
aContainer.get('childViews').pushObject(AnotherViewClass.create());
aContainer.get('childViews'); // [aContainer.aView, aContainer.bView, ]
```
Will result in the following HTML
``` html
A
B
Another view
```
Direct manipulation of childViews presence or absence in the DOM via calls to
`remove` or `removeFromParent` or calls to a container's `removeChild` may not behave
correctly.
Calling `remove()` on a child view will remove the view's HTML, but it will remain as part of its
container's `childView`s property.
Calling `removeChild()` on the container will remove the passed view instance from the container's
`childView`s but keep its HTML within the container's rendered view.
Calling `removeFromParent()` behaves as expected but should be avoided in favor of direct
manipulation of a container's `childViews` property.
``` javascript
aContainer = Ember.ContainerView.create({
classNames: ['the-container'],
childViews: ['aView', 'bView'],
aView: Ember.View.create({
template: Ember.Handlebars.compile("A")
}),
bView: Ember.View.create({
template: Ember.Handlebars.compile("B")
})
});
aContainer.appendTo('body');
```
Results in the HTML
``` html
A
B
```
Calling `aContainer.get('aView').removeFromParent()` will result in the following HTML
``` html
B
```
And the `Ember.View` instance stored in `aContainer.aView` will be removed from `aContainer`'s
`childViews` array.
## Templates and Layout
A `template`, `templateName`, `defaultTemplate`, `layout`, `layoutName` or `defaultLayout`
property on a container view will not result in the template or layout being rendered.
The HTML contents of a `Ember.ContainerView`'s DOM representation will only be the rendered HTML
of its child views.
## Binding a View to Display
If you would like to display a single view in your ContainerView, you can set its `currentView`
property. When the `currentView` property is set to a view instance, it will be added to the
ContainerView's `childViews` array. If the `currentView` property is later changed to a
different view, the new view will replace the old view. If `currentView` is set to `null`, the
last `currentView` will be removed.
This functionality is useful for cases where you want to bind the display of a ContainerView to
a controller or state manager. For example, you can bind the `currentView` of a container to
a controller like this:
``` javascript
App.appController = Ember.Object.create({
view: Ember.View.create({
templateName: 'person_template'
})
});
```
``` handlebars
{{view Ember.ContainerView currentViewBinding="App.appController.view"}}
```
## Use lifecycle hooks
This is an example of how you could implement reusable currentView view.
``` javascript
App.ContainerView = Ember.ContainerView.extend({
appendCurrentView: function(currentView, callback) {
currentView.set('isVisible', true);
if (!this.get('childViews').contains(currentView)) {
this._super(currentView, callback);
} else {
callback();
}
},
removeCurrentView: function(currentView, callback) {
if (currentView.get('isShared')) {
currentView.set('isVisible', false);
callback();
} else {
this._super(currentView, callback);
}
}
});
````
This is an example of how you could implement animations.
```` javascript
App.ContainerView = Ember.ContainerView.extend({
presentCurrentView: function(currentView, callback) {
currentView.$().animate({top: '0px'}, callback);
},
dismissCurrentView: function(currentView, callback) {
currentView.$().animate({top: '-100px'}, callback);
}
});
````
@class ContainerView
@namespace Ember
@extends Ember.View
*/
Ember.ContainerView = Ember.View.extend({
init: function() {
this._super();
var childViews = get(this, 'childViews');
Ember.defineProperty(this, 'childViews', childViewsProperty);
var _childViews = this._childViews;
forEach(childViews, function(viewName, idx) {
var view;
if ('string' === typeof viewName) {
view = get(this, viewName);
view = this.createChildView(view);
set(this, viewName, view);
} else {
view = this.createChildView(viewName);
}
_childViews[idx] = view;
}, this);
// Make the _childViews array observable
Ember.A(_childViews);
// Sets up an array observer on the child views array. This
// observer will detect when child views are added or removed
// and update the DOM to reflect the mutation.
get(this, 'childViews').addArrayObserver(this, {
willChange: 'childViewsWillChange',
didChange: 'childViewsDidChange'
});
// Make sure we initialize with currentView if it is present
var currentView = get(this, 'currentView');
if (currentView) { this._currentViewDidChange(); }
},
/**
@private
Instructs each child view to render to the passed render buffer.
@method render
@param {Ember.RenderBuffer} buffer the buffer to render to
*/
render: function(buffer) {
this.forEachChildView(function(view) {
view.renderToBuffer(buffer);
});
},
instrumentName: 'render.container',
/**
@private
When the container view is destroyed, tear down the child views
array observer.
@method willDestroy
*/
willDestroy: function() {
get(this, 'childViews').removeArrayObserver(this, {
willChange: 'childViewsWillChange',
didChange: 'childViewsDidChange'
});
this._super();
},
/**
@private
When a child view is removed, destroy its element so that
it is removed from the DOM.
The array observer that triggers this action is set up in the
`renderToBuffer` method.
@method childViewsWillChange
@param {Ember.Array} views the child views array before mutation
@param {Number} start the start position of the mutation
@param {Number} removed the number of child views removed
**/
childViewsWillChange: function(views, start, removed) {
if (removed === 0) { return; }
var changedViews = views.slice(start, start+removed);
this.initializeViews(changedViews, null, null);
this.invokeForState('childViewsWillChange', views, start, removed);
},
/**
@private
When a child view is added, make sure the DOM gets updated appropriately.
If the view has already rendered an element, we tell the child view to
create an element and insert it into the DOM. If the enclosing container view
has already written to a buffer, but not yet converted that buffer into an
element, we insert the string representation of the child into the appropriate
place in the buffer.
@method childViewsDidChange
@param {Ember.Array} views the array of child views afte the mutation has occurred
@param {Number} start the start position of the mutation
@param {Number} removed the number of child views removed
@param {Number} the number of child views added
*/
childViewsDidChange: function(views, start, removed, added) {
var len = get(views, 'length');
// No new child views were added; bail out.
if (added === 0) return;
var changedViews = views.slice(start, start+added);
this.initializeViews(changedViews, this, get(this, 'templateData'));
// Let the current state handle the changes
this.invokeForState('childViewsDidChange', views, start, added);
},
initializeViews: function(views, parentView, templateData) {
forEach(views, function(view) {
set(view, '_parentView', parentView);
if (!get(view, 'templateData')) {
set(view, 'templateData', templateData);
}
});
},
currentView: null,
/**
This method is responsible for presenting a new view.
Default implementation will simply call the callback.
You can override this method if you want to add an animation for example.
@method presentCurrentView
@param {Ember.View} currentView a view to present
@param {Function} callback the callback called once operation is terminated
*/
presentCurrentView: function(currentView, callback) {
callback();
},
/**
This method is responsible for adding view to containerView
@method appendCurrentView
@param {Ember.View} currentView a view to present
@param {Function} callback the callback called once view is appended
*/
appendCurrentView: function(currentView, callback) {
var childViews = get(this, 'childViews');
currentView.one('didInsertElement', callback);
childViews.pushObject(currentView);
},
/**
This method is responsible for dismissing a view.
Default implementation will simply call the callback.
You can override this method if you want to add an animation for example.
@method dismissCurrentView
@param {Ember.View} currentView a view to dismiss
@param {Function} callback the callback called once operation is terminated
*/
dismissCurrentView: function(currentView, callback) {
callback();
},
/**
This method is responsible for removing a view from the containerView
You may want to override it in case you implementing views sharing for example
@method removeCurrentView
@param {Ember.View} currentView a view to present
@param {Function} callback the callback called once view is removed
*/
removeCurrentView: function(currentView, callback) {
var childViews = get(this, 'childViews');
currentView.one('didDisappear', function() {
currentView.destroy();
});
childViews.removeObject(currentView);
callback();
},
_currentViewWillChange: Ember.beforeObserver(function() {
var currentView = get(this, 'currentView'),
containerView = this;
if (currentView) {
set(currentView, 'isBeingDismissed', true);
currentView.trigger('willDisappear', currentView);
this.dismissCurrentView(currentView, function() {
containerView.removeCurrentView(currentView, function() {
set(currentView, 'isBeingDismissed', false);
currentView.trigger('didDisappear', currentView);
});
});
}
}, 'currentView'),
_currentViewDidChange: Ember.observer(function() {
var currentView = get(this, 'currentView'),
containerView = this;
if (currentView) {
set(currentView, 'isBeingPresented', true);
currentView.trigger('willAppear', currentView);
this.appendCurrentView(currentView, function() {
containerView.presentCurrentView(currentView, function() {
set(currentView, 'isBeingPresented', false);
currentView.trigger('didAppear', currentView);
});
});
}
}, 'currentView'),
_ensureChildrenAreInDOM: function () {
this.invokeForState('ensureChildrenAreInDOM', this);
}
});
// Ember.ContainerView extends the default view states to provide different
// behavior for childViewsWillChange and childViewsDidChange.
Ember.ContainerView.states = {
parent: Ember.View.states,
inBuffer: {
childViewsDidChange: function(parentView, views, start, added) {
var buffer = parentView.buffer,
startWith, prev, prevBuffer, view;
// Determine where to begin inserting the child view(s) in the
// render buffer.
if (start === 0) {
// If views were inserted at the beginning, prepend the first
// view to the render buffer, then begin inserting any
// additional views at the beginning.
view = views[start];
startWith = start + 1;
view.renderToBuffer(buffer, 'prepend');
} else {
// Otherwise, just insert them at the same place as the child
// views mutation.
view = views[start - 1];
startWith = start;
}
for (var i=startWith; i` and the following code:
``` javascript
someItemsView = Ember.CollectionView.create({
classNames: ['a-collection'],
content: ['A','B','C'],
itemViewClass: Ember.View.extend({
template: Ember.Handlebars.compile("the letter: {{view.content}}")
})
});
someItemsView.appendTo('body');
```
Will result in the following HTML structure
``` html
the letter: A
the letter: B
the letter: C
```
## Automatic matching of parent/child tagNames
Setting the `tagName` property of a `CollectionView` to any of
"ul", "ol", "table", "thead", "tbody", "tfoot", "tr", or "select" will result
in the item views receiving an appropriately matched `tagName` property.
Given an empty `` and the following code:
``` javascript
anUndorderedListView = Ember.CollectionView.create({
tagName: 'ul',
content: ['A','B','C'],
itemViewClass: Ember.View.extend({
template: Ember.Handlebars.compile("the letter: {{view.content}}")
})
});
anUndorderedListView.appendTo('body');
```
Will result in the following HTML structure
``` html
the letter: A
the letter: B
the letter: C
```
Additional tagName pairs can be provided by adding to `Ember.CollectionView.CONTAINER_MAP `
``` javascript
Ember.CollectionView.CONTAINER_MAP['article'] = 'section'
```
## Empty View
You can provide an `Ember.View` subclass to the `Ember.CollectionView` instance as its
`emptyView` property. If the `content` property of a `CollectionView` is set to `null`
or an empty array, an instance of this view will be the `CollectionView`s only child.
``` javascript
aListWithNothing = Ember.CollectionView.create({
classNames: ['nothing']
content: null,
emptyView: Ember.View.extend({
template: Ember.Handlebars.compile("The collection is empty")
})
});
aListWithNothing.appendTo('body');
```
Will result in the following HTML structure
``` html
The collection is empty
```
## Adding and Removing items
The `childViews` property of a `CollectionView` should not be directly manipulated. Instead,
add, remove, replace items from its `content` property. This will trigger
appropriate changes to its rendered HTML.
## Use in templates via the `{{collection}}` Ember.Handlebars helper
Ember.Handlebars provides a helper specifically for adding `CollectionView`s to templates.
See `Ember.Handlebars.collection` for more details
@class CollectionView
@namespace Ember
@extends Ember.ContainerView
@since Ember 0.9
*/
Ember.CollectionView = Ember.ContainerView.extend(
/** @scope Ember.CollectionView.prototype */ {
/**
A list of items to be displayed by the Ember.CollectionView.
@property content
@type Ember.Array
@default null
*/
content: null,
/**
@private
This provides metadata about what kind of empty view class this
collection would like if it is being instantiated from another
system (like Handlebars)
@property emptyViewClass
*/
emptyViewClass: Ember.View,
/**
An optional view to display if content is set to an empty array.
@property emptyView
@type Ember.View
@default null
*/
emptyView: null,
/**
@property itemViewClass
@type Ember.View
@default Ember.View
*/
itemViewClass: Ember.View,
init: function() {
var ret = this._super();
this._contentDidChange();
return ret;
},
_contentWillChange: Ember.beforeObserver(function() {
var content = this.get('content');
if (content) { content.removeArrayObserver(this); }
var len = content ? get(content, 'length') : 0;
this.arrayWillChange(content, 0, len);
}, 'content'),
/**
@private
Check to make sure that the content has changed, and if so,
update the children directly. This is always scheduled
asynchronously, to allow the element to be created before
bindings have synchronized and vice versa.
@method _contentDidChange
*/
_contentDidChange: Ember.observer(function() {
var content = get(this, 'content');
if (content) {
Ember.assert(fmt("an Ember.CollectionView's content must implement Ember.Array. You passed %@", [content]), Ember.Array.detect(content));
content.addArrayObserver(this);
}
var len = content ? get(content, 'length') : 0;
this.arrayDidChange(content, 0, null, len);
}, 'content'),
willDestroy: function() {
var content = get(this, 'content');
if (content) { content.removeArrayObserver(this); }
this._super();
},
arrayWillChange: function(content, start, removedCount) {
// If the contents were empty before and this template collection has an
// empty view remove it now.
var emptyView = get(this, 'emptyView');
if (emptyView && emptyView instanceof Ember.View) {
emptyView.removeFromParent();
}
// Loop through child views that correspond with the removed items.
// Note that we loop from the end of the array to the beginning because
// we are mutating it as we go.
var childViews = get(this, 'childViews'), childView, idx, len;
len = get(childViews, 'length');
var removingAll = removedCount === len;
if (removingAll) {
this.invokeForState('empty');
}
for (idx = start + removedCount - 1; idx >= start; idx--) {
childView = childViews[idx];
if (removingAll) { childView.removedFromDOM = true; }
childView.destroy();
}
},
/**
Called when a mutation to the underlying content array occurs.
This method will replay that mutation against the views that compose the
Ember.CollectionView, ensuring that the view reflects the model.
This array observer is added in contentDidChange.
@method arrayDidChange
@param {Array} addedObjects the objects that were added to the content
@param {Array} removedObjects the objects that were removed from the content
@param {Number} changeIndex the index at which the changes occurred
*/
arrayDidChange: function(content, start, removed, added) {
var itemViewClass = get(this, 'itemViewClass'),
childViews = get(this, 'childViews'),
addedViews = [], view, item, idx, len, itemTagName;
if ('string' === typeof itemViewClass) {
itemViewClass = get(itemViewClass);
}
Ember.assert(fmt("itemViewClass must be a subclass of Ember.View, not %@", [itemViewClass]), Ember.View.detect(itemViewClass));
len = content ? get(content, 'length') : 0;
if (len) {
for (idx = start; idx < start+added; idx++) {
item = content.objectAt(idx);
view = this.createChildView(itemViewClass, {
content: item,
contentIndex: idx
});
addedViews.push(view);
}
} else {
var emptyView = get(this, 'emptyView');
if (!emptyView) { return; }
emptyView = this.createChildView(emptyView);
addedViews.push(emptyView);
set(this, 'emptyView', emptyView);
}
childViews.replace(start, 0, addedViews);
},
createChildView: function(view, attrs) {
view = this._super(view, attrs);
var itemTagName = get(view, 'tagName');
var tagName = (itemTagName === null || itemTagName === undefined) ? Ember.CollectionView.CONTAINER_MAP[get(this, 'tagName')] : itemTagName;
set(view, 'tagName', tagName);
return view;
}
});
/**
A map of parent tags to their default child tags. You can add
additional parent tags if you want collection views that use
a particular parent tag to default to a child tag.
@property CONTAINER_MAP
@type Hash
@static
@final
*/
Ember.CollectionView.CONTAINER_MAP = {
ul: 'li',
ol: 'li',
table: 'tr',
thead: 'tr',
tbody: 'tr',
tfoot: 'tr',
tr: 'td',
select: 'option'
};
})();
(function() {
})();
(function() {
/*globals jQuery*/
/**
Ember Views
@module ember
@submodule ember-views
@require ember-runtime
@main ember-views
*/
})();
(function() {
var get = Ember.get, set = Ember.set;
/**
@module ember
@submodule ember-states
*/
/**
@class State
@namespace Ember
@extends Ember.Object
@uses Ember.Evented
*/
Ember.State = Ember.Object.extend(Ember.Evented,
/** @scope Ember.State.prototype */{
isState: true,
/**
A reference to the parent state.
@property parentState
@type Ember.State
*/
parentState: null,
start: null,
/**
The name of this state.
@property name
@type String
*/
name: null,
/**
The full path to this state.
@property path
@type String
*/
path: Ember.computed(function() {
var parentPath = get(this, 'parentState.path'),
path = get(this, 'name');
if (parentPath) {
path = parentPath + '.' + path;
}
return path;
}).property(),
/**
@private
Override the default event firing from Ember.Evented to
also call methods with the given name.
@method trigger
@param name
*/
trigger: function(name) {
if (this[name]) {
this[name].apply(this, [].slice.call(arguments, 1));
}
this._super.apply(this, arguments);
},
init: function() {
var states = get(this, 'states'), foundStates;
set(this, 'childStates', Ember.A());
set(this, 'eventTransitions', get(this, 'eventTransitions') || {});
var name, value, transitionTarget;
// As a convenience, loop over the properties
// of this state and look for any that are other
// Ember.State instances or classes, and move them
// to the `states` hash. This avoids having to
// create an explicit separate hash.
if (!states) {
states = {};
for (name in this) {
if (name === "constructor") { continue; }
if (value = this[name]) {
if (transitionTarget = value.transitionTarget) {
this.eventTransitions[name] = transitionTarget;
}
this.setupChild(states, name, value);
}
}
set(this, 'states', states);
} else {
for (name in states) {
this.setupChild(states, name, states[name]);
}
}
set(this, 'pathsCache', {});
set(this, 'pathsCacheNoContext', {});
},
setupChild: function(states, name, value) {
if (!value) { return false; }
if (value.isState) {
set(value, 'name', name);
} else if (Ember.State.detect(value)) {
value = value.create({
name: name
});
}
if (value.isState) {
set(value, 'parentState', this);
get(this, 'childStates').pushObject(value);
states[name] = value;
return value;
}
},
lookupEventTransition: function(name) {
var path, state = this;
while(state && !path) {
path = state.eventTransitions[name];
state = state.get('parentState');
}
return path;
},
/**
A Boolean value indicating whether the state is a leaf state
in the state hierarchy. This is false if the state has child
states; otherwise it is true.
@property isLeaf
@type Boolean
*/
isLeaf: Ember.computed(function() {
return !get(this, 'childStates').length;
}),
/**
A boolean value indicating whether the state takes a context.
By default we assume all states take contexts.
@property hasContext
@default true
*/
hasContext: true,
/**
This is the default transition event.
@event setup
@param {Ember.StateManager} manager
@param context
@see Ember.StateManager#transitionEvent
*/
setup: Ember.K,
/**
This event fires when the state is entered.
@event enter
@param {Ember.StateManager} manager
*/
enter: Ember.K,
/**
This event fires when the state is exited.
@event exit
@param {Ember.StateManager} manager
*/
exit: Ember.K
});
Ember.State.reopenClass({
/**
Creates an action function for transitioning to the named state while preserving context.
The following example StateManagers are equivalent:
aManager = Ember.StateManager.create({
stateOne: Ember.State.create({
changeToStateTwo: Ember.State.transitionTo('stateTwo')
}),
stateTwo: Ember.State.create({})
})
bManager = Ember.StateManager.create({
stateOne: Ember.State.create({
changeToStateTwo: function(manager, context){
manager.transitionTo('stateTwo', context)
}
}),
stateTwo: Ember.State.create({})
})
@method transitionTo
@static
@param {String} target
*/
transitionTo: function(target) {
var transitionFunction = function(stateManager, contextOrEvent) {
var contexts = [], transitionArgs,
Event = Ember.$ && Ember.$.Event;
if (contextOrEvent && (Event && contextOrEvent instanceof Event)) {
if (contextOrEvent.hasOwnProperty('contexts')) {
contexts = contextOrEvent.contexts.slice();
}
}
else {
contexts = [].slice.call(arguments, 1);
}
contexts.unshift(target);
stateManager.transitionTo.apply(stateManager, contexts);
};
transitionFunction.transitionTarget = target;
return transitionFunction;
}
});
})();
(function() {
/**
@module ember
@submodule ember-states
*/
var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt;
var arrayForEach = Ember.ArrayPolyfills.forEach;
/**
A Transition takes the enter, exit and resolve states and normalizes
them:
* takes any passed in contexts into consideration
* adds in `initialState`s
@class Transition
@private
*/
var Transition = function(raw) {
this.enterStates = raw.enterStates.slice();
this.exitStates = raw.exitStates.slice();
this.resolveState = raw.resolveState;
this.finalState = raw.enterStates[raw.enterStates.length - 1] || raw.resolveState;
};
Transition.prototype = {
/**
Normalize the passed in enter, exit and resolve states.
This process also adds `finalState` and `contexts` to the Transition object.
@method normalize
@param {Ember.StateManager} manager the state manager running the transition
@param {Array} contexts a list of contexts passed into `transitionTo`
*/
normalize: function(manager, contexts) {
this.matchContextsToStates(contexts);
this.addInitialStates();
this.removeUnchangedContexts(manager);
return this;
},
/**
Match each of the contexts passed to `transitionTo` to a state.
This process may also require adding additional enter and exit
states if there are more contexts than enter states.
@method matchContextsToStates
@param {Array} contexts a list of contexts passed into `transitionTo`
*/
matchContextsToStates: function(contexts) {
var stateIdx = this.enterStates.length - 1,
matchedContexts = [],
state,
context;
// Next, we will match the passed in contexts to the states they
// represent.
//
// First, assign a context to each enter state in reverse order. If
// any contexts are left, add a parent state to the list of states
// to enter and exit, and assign a context to the parent state.
//
// If there are still contexts left when the state manager is
// reached, raise an exception.
//
// This allows the following:
//
// |- root
// | |- post
// | | |- comments
// | |- about (* current state)
//
// For `transitionTo('post.comments', post, post.get('comments')`,
// the first context (`post`) will be assigned to `root.post`, and
// the second context (`post.get('comments')`) will be assigned
// to `root.post.comments`.
//
// For the following:
//
// |- root
// | |- post
// | | |- index (* current state)
// | | |- comments
//
// For `transitionTo('post.comments', otherPost, otherPost.get('comments')`,
// the `` state will be added to the list of enter and exit
// states because its context has changed.
while (contexts.length > 0) {
if (stateIdx >= 0) {
state = this.enterStates[stateIdx--];
} else {
if (this.enterStates.length) {
state = get(this.enterStates[0], 'parentState');
if (!state) { throw "Cannot match all contexts to states"; }
} else {
// If re-entering the current state with a context, the resolve
// state will be the current state.
state = this.resolveState;
}
this.enterStates.unshift(state);
this.exitStates.unshift(state);
}
// in routers, only states with dynamic segments have a context
if (get(state, 'hasContext')) {
context = contexts.pop();
} else {
context = null;
}
matchedContexts.unshift(context);
}
this.contexts = matchedContexts;
},
/**
Add any `initialState`s to the list of enter states.
@method addInitialStates
*/
addInitialStates: function() {
var finalState = this.finalState, initialState;
while(true) {
initialState = get(finalState, 'initialState') || 'start';
finalState = get(finalState, 'states.' + initialState);
if (!finalState) { break; }
this.finalState = finalState;
this.enterStates.push(finalState);
this.contexts.push(undefined);
}
},
/**
Remove any states that were added because the number of contexts
exceeded the number of explicit enter states, but the context has
not changed since the last time the state was entered.
@method removeUnchangedContexts
@param {Ember.StateManager} manager passed in to look up the last
context for a states
*/
removeUnchangedContexts: function(manager) {
// Start from the beginning of the enter states. If the state was added
// to the list during the context matching phase, make sure the context
// has actually changed since the last time the state was entered.
while (this.enterStates.length > 0) {
if (this.enterStates[0] !== this.exitStates[0]) { break; }
if (this.enterStates.length === this.contexts.length) {
if (manager.getStateMeta(this.enterStates[0], 'context') !== this.contexts[0]) { break; }
this.contexts.shift();
}
this.resolveState = this.enterStates.shift();
this.exitStates.shift();
}
}
};
/**
StateManager is part of Ember's implementation of a finite state machine. A StateManager
instance manages a number of properties that are instances of `Ember.State`,
tracks the current active state, and triggers callbacks when states have changed.
## Defining States
The states of StateManager can be declared in one of two ways. First, you can define
a `states` property that contains all the states:
managerA = Ember.StateManager.create({
states: {
stateOne: Ember.State.create(),
stateTwo: Ember.State.create()
}
})
managerA.get('states')
// {
// stateOne: Ember.State.create(),
// stateTwo: Ember.State.create()
// }
You can also add instances of `Ember.State` (or an `Ember.State` subclass) directly as properties
of a StateManager. These states will be collected into the `states` property for you.
managerA = Ember.StateManager.create({
stateOne: Ember.State.create(),
stateTwo: Ember.State.create()
})
managerA.get('states')
// {
// stateOne: Ember.State.create(),
// stateTwo: Ember.State.create()
// }
## The Initial State
When created a StateManager instance will immediately enter into the state
defined as its `start` property or the state referenced by name in its
`initialState` property:
managerA = Ember.StateManager.create({
start: Ember.State.create({})
})
managerA.get('currentState.name') // 'start'
managerB = Ember.StateManager.create({
initialState: 'beginHere',
beginHere: Ember.State.create({})
})
managerB.get('currentState.name') // 'beginHere'
Because it is a property you may also provide a computed function if you wish to derive
an `initialState` programmatically:
managerC = Ember.StateManager.create({
initialState: function(){
if (someLogic) {
return 'active';
} else {
return 'passive';
}
}.property(),
active: Ember.State.create({}),
passive: Ember.State.create({})
})
## Moving Between States
A StateManager can have any number of Ember.State objects as properties
and can have a single one of these states as its current state.
Calling `transitionTo` transitions between states:
robotManager = Ember.StateManager.create({
initialState: 'poweredDown',
poweredDown: Ember.State.create({}),
poweredUp: Ember.State.create({})
})
robotManager.get('currentState.name') // 'poweredDown'
robotManager.transitionTo('poweredUp')
robotManager.get('currentState.name') // 'poweredUp'
Before transitioning into a new state the existing `currentState` will have its
`exit` method called with the StateManager instance as its first argument and
an object representing the transition as its second argument.
After transitioning into a new state the new `currentState` will have its
`enter` method called with the StateManager instance as its first argument and
an object representing the transition as its second argument.
robotManager = Ember.StateManager.create({
initialState: 'poweredDown',
poweredDown: Ember.State.create({
exit: function(stateManager){
console.log("exiting the poweredDown state")
}
}),
poweredUp: Ember.State.create({
enter: function(stateManager){
console.log("entering the poweredUp state. Destroy all humans.")
}
})
})
robotManager.get('currentState.name') // 'poweredDown'
robotManager.transitionTo('poweredUp')
// will log
// 'exiting the poweredDown state'
// 'entering the poweredUp state. Destroy all humans.'
Once a StateManager is already in a state, subsequent attempts to enter that state will
not trigger enter or exit method calls. Attempts to transition into a state that the
manager does not have will result in no changes in the StateManager's current state:
robotManager = Ember.StateManager.create({
initialState: 'poweredDown',
poweredDown: Ember.State.create({
exit: function(stateManager){
console.log("exiting the poweredDown state")
}
}),
poweredUp: Ember.State.create({
enter: function(stateManager){
console.log("entering the poweredUp state. Destroy all humans.")
}
})
})
robotManager.get('currentState.name') // 'poweredDown'
robotManager.transitionTo('poweredUp')
// will log
// 'exiting the poweredDown state'
// 'entering the poweredUp state. Destroy all humans.'
robotManager.transitionTo('poweredUp') // no logging, no state change
robotManager.transitionTo('someUnknownState') // silently fails
robotManager.get('currentState.name') // 'poweredUp'
Each state property may itself contain properties that are instances of Ember.State.
The StateManager can transition to specific sub-states in a series of transitionTo method calls or
via a single transitionTo with the full path to the specific state. The StateManager will also
keep track of the full path to its currentState
robotManager = Ember.StateManager.create({
initialState: 'poweredDown',
poweredDown: Ember.State.create({
charging: Ember.State.create(),
charged: Ember.State.create()
}),
poweredUp: Ember.State.create({
mobile: Ember.State.create(),
stationary: Ember.State.create()
})
})
robotManager.get('currentState.name') // 'poweredDown'
robotManager.transitionTo('poweredUp')
robotManager.get('currentState.name') // 'poweredUp'
robotManager.transitionTo('mobile')
robotManager.get('currentState.name') // 'mobile'
// transition via a state path
robotManager.transitionTo('poweredDown.charging')
robotManager.get('currentState.name') // 'charging'
robotManager.get('currentState.path') // 'poweredDown.charging'
Enter transition methods will be called for each state and nested child state in their
hierarchical order. Exit methods will be called for each state and its nested states in
reverse hierarchical order.
Exit transitions for a parent state are not called when entering into one of its child states,
only when transitioning to a new section of possible states in the hierarchy.
robotManager = Ember.StateManager.create({
initialState: 'poweredDown',
poweredDown: Ember.State.create({
enter: function(){},
exit: function(){
console.log("exited poweredDown state")
},
charging: Ember.State.create({
enter: function(){},
exit: function(){}
}),
charged: Ember.State.create({
enter: function(){
console.log("entered charged state")
},
exit: function(){
console.log("exited charged state")
}
})
}),
poweredUp: Ember.State.create({
enter: function(){
console.log("entered poweredUp state")
},
exit: function(){},
mobile: Ember.State.create({
enter: function(){
console.log("entered mobile state")
},
exit: function(){}
}),
stationary: Ember.State.create({
enter: function(){},
exit: function(){}
})
})
})
robotManager.get('currentState.path') // 'poweredDown'
robotManager.transitionTo('charged')
// logs 'entered charged state'
// but does *not* log 'exited poweredDown state'
robotManager.get('currentState.name') // 'charged
robotManager.transitionTo('poweredUp.mobile')
// logs
// 'exited charged state'
// 'exited poweredDown state'
// 'entered poweredUp state'
// 'entered mobile state'
During development you can set a StateManager's `enableLogging` property to `true` to
receive console messages of state transitions.
robotManager = Ember.StateManager.create({
enableLogging: true
})
## Managing currentState with Actions
To control which transitions between states are possible for a given state, StateManager
can receive and route action messages to its states via the `send` method. Calling to `send` with
an action name will begin searching for a method with the same name starting at the current state
and moving up through the parent states in a state hierarchy until an appropriate method is found
or the StateManager instance itself is reached.
If an appropriately named method is found it will be called with the state manager as the first
argument and an optional `context` object as the second argument.
managerA = Ember.StateManager.create({
initialState: 'stateOne.substateOne.subsubstateOne',
stateOne: Ember.State.create({
substateOne: Ember.State.create({
anAction: function(manager, context){
console.log("an action was called")
},
subsubstateOne: Ember.State.create({})
})
})
})
managerA.get('currentState.name') // 'subsubstateOne'
managerA.send('anAction')
// 'stateOne.substateOne.subsubstateOne' has no anAction method
// so the 'anAction' method of 'stateOne.substateOne' is called
// and logs "an action was called"
// with managerA as the first argument
// and no second argument
someObject = {}
managerA.send('anAction', someObject)
// the 'anAction' method of 'stateOne.substateOne' is called again
// with managerA as the first argument and
// someObject as the second argument.
If the StateManager attempts to send an action but does not find an appropriately named
method in the current state or while moving upwards through the state hierarchy
it will throw a new Ember.Error. Action detection only moves upwards through the state hierarchy
from the current state. It does not search in other portions of the hierarchy.
managerB = Ember.StateManager.create({
initialState: 'stateOne.substateOne.subsubstateOne',
stateOne: Ember.State.create({
substateOne: Ember.State.create({
subsubstateOne: Ember.State.create({})
})
}),
stateTwo: Ember.State.create({
anAction: function(manager, context){
// will not be called below because it is
// not a parent of the current state
}
})
})
managerB.get('currentState.name') // 'subsubstateOne'
managerB.send('anAction')
// Error: could not
// respond to event anAction in state stateOne.substateOne.subsubstateOne.
Inside of an action method the given state should delegate `transitionTo` calls on its
StateManager.
robotManager = Ember.StateManager.create({
initialState: 'poweredDown.charging',
poweredDown: Ember.State.create({
charging: Ember.State.create({
chargeComplete: function(manager, context){
manager.transitionTo('charged')
}
}),
charged: Ember.State.create({
boot: function(manager, context){
manager.transitionTo('poweredUp')
}
})
}),
poweredUp: Ember.State.create({
beginExtermination: function(manager, context){
manager.transitionTo('rampaging')
},
rampaging: Ember.State.create()
})
})
robotManager.get('currentState.name') // 'charging'
robotManager.send('boot') // throws error, no boot action
// in current hierarchy
robotManager.get('currentState.name') // remains 'charging'
robotManager.send('beginExtermination') // throws error, no beginExtermination
// action in current hierarchy
robotManager.get('currentState.name') // remains 'charging'
robotManager.send('chargeComplete')
robotManager.get('currentState.name') // 'charged'
robotManager.send('boot')
robotManager.get('currentState.name') // 'poweredUp'
robotManager.send('beginExtermination', allHumans)
robotManager.get('currentState.name') // 'rampaging'
Transition actions can also be created using the `transitionTo` method of the Ember.State class. The
following example StateManagers are equivalent:
aManager = Ember.StateManager.create({
stateOne: Ember.State.create({
changeToStateTwo: Ember.State.transitionTo('stateTwo')
}),
stateTwo: Ember.State.create({})
})
bManager = Ember.StateManager.create({
stateOne: Ember.State.create({
changeToStateTwo: function(manager, context){
manager.transitionTo('stateTwo', context)
}
}),
stateTwo: Ember.State.create({})
})
@class StateManager
@namespace Ember
@extends Ember.State
**/
Ember.StateManager = Ember.State.extend({
/**
@private
When creating a new statemanager, look for a default state to transition
into. This state can either be named `start`, or can be specified using the
`initialState` property.
@method init
*/
init: function() {
this._super();
set(this, 'stateMeta', Ember.Map.create());
var initialState = get(this, 'initialState');
if (!initialState && get(this, 'states.start')) {
initialState = 'start';
}
if (initialState) {
this.transitionTo(initialState);
Ember.assert('Failed to transition to initial state "' + initialState + '"', !!get(this, 'currentState'));
}
},
stateMetaFor: function(state) {
var meta = get(this, 'stateMeta'),
stateMeta = meta.get(state);
if (!stateMeta) {
stateMeta = {};
meta.set(state, stateMeta);
}
return stateMeta;
},
setStateMeta: function(state, key, value) {
return set(this.stateMetaFor(state), key, value);
},
getStateMeta: function(state, key) {
return get(this.stateMetaFor(state), key);
},
/**
The current state from among the manager's possible states. This property should
not be set directly. Use `transitionTo` to move between states by name.
@property currentState
@type Ember.State
*/
currentState: null,
/**
The path of the current state. Returns a string representation of the current
state.
@property currentPath
@type String
*/
currentPath: Ember.computed('currentState', function() {
return get(this, 'currentState.path');
}),
/**
The name of transitionEvent that this stateManager will dispatch
@property transitionEvent
@type String
@default 'setup'
*/
transitionEvent: 'setup',
/**
If set to true, `errorOnUnhandledEvents` will cause an exception to be
raised if you attempt to send an event to a state manager that is not
handled by the current state or any of its parent states.
@property errorOnUnhandledEvents
@type Boolean
@default true
*/
errorOnUnhandledEvent: true,
send: function(event) {
var contexts, sendRecursiveArguments;
Ember.assert('Cannot send event "' + event + '" while currentState is ' + get(this, 'currentState'), get(this, 'currentState'));
contexts = [].slice.call(arguments, 1);
sendRecursiveArguments = contexts;
sendRecursiveArguments.unshift(event, get(this, 'currentState'));
return this.sendRecursively.apply(this, sendRecursiveArguments);
},
sendRecursively: function(event, currentState) {
var log = this.enableLogging,
action = currentState[event],
contexts, sendRecursiveArguments, actionArguments;
contexts = [].slice.call(arguments, 2);
// Test to see if the action is a method that
// can be invoked. Don't blindly check just for
// existence, because it is possible the state
// manager has a child state of the given name,
// and we should still raise an exception in that
// case.
if (typeof action === 'function') {
if (log) { Ember.Logger.log(fmt("STATEMANAGER: Sending event '%@' to state %@.", [event, get(currentState, 'path')])); }
actionArguments = contexts;
actionArguments.unshift(this);
return action.apply(currentState, actionArguments);
} else {
var parentState = get(currentState, 'parentState');
if (parentState) {
sendRecursiveArguments = contexts;
sendRecursiveArguments.unshift(event, parentState);
return this.sendRecursively.apply(this, sendRecursiveArguments);
} else if (get(this, 'errorOnUnhandledEvent')) {
throw new Ember.Error(this.toString() + " could not respond to event " + event + " in state " + get(this, 'currentState.path') + ".");
}
}
},
/**
Finds a state by its state path.
Example:
manager = Ember.StateManager.create({
root: Ember.State.create({
dashboard: Ember.State.create()
})
});
manager.getStateByPath(manager, "root.dashboard")
// returns the dashboard state
@method getStateByPath
@param {Ember.State} root the state to start searching from
@param {String} path the state path to follow
@return {Ember.State} the state at the end of the path
*/
getStateByPath: function(root, path) {
var parts = path.split('.'),
state = root;
for (var i=0, len=parts.length; i`, an attempt to
// transition to `comments.show` will match ``.
//
// First, this code will look for root.posts.show.comments.show.
// Next, it will look for root.posts.comments.show. Finally,
// it will look for `root.comments.show`, and find the state.
//
// After this process, the following variables will exist:
//
// * resolveState: a common parent state between the current
// and target state. In the above example, `` is the
// `resolveState`.
// * enterStates: a list of all of the states represented
// by the path from the `resolveState`. For example, for
// the path `root.comments.show`, `enterStates` would have
// `[, ]`
// * exitStates: a list of all of the states from the
// `resolveState` to the `currentState`. In the above
// example, `exitStates` would have
// `[`, `]`.
while (resolveState && !enterStates) {
exitStates.unshift(resolveState);
resolveState = get(resolveState, 'parentState');
if (!resolveState) {
enterStates = this.getStatesInPath(this, path);
if (!enterStates) {
Ember.assert('Could not find state for path: "'+path+'"');
return;
}
}
enterStates = this.getStatesInPath(resolveState, path);
}
// If the path contains some states that are parents of both the
// current state and the target state, remove them.
//
// For example, in the following hierarchy:
//
// |- root
// | |- post
// | | |- index (* current)
// | | |- show
//
// If the `path` is `root.post.show`, the three variables will
// be:
//
// * resolveState: ``
// * enterStates: `[, , ]`
// * exitStates: `[, , ]`
//
// The goal of this code is to remove the common states, so we
// have:
//
// * resolveState: ``
// * enterStates: `[]`
// * exitStates: `[]`
//
// This avoid unnecessary calls to the enter and exit transitions.
while (enterStates.length > 0 && enterStates[0] === exitStates[0]) {
resolveState = enterStates.shift();
exitStates.shift();
}
// Cache the enterStates, exitStates, and resolveState for the
// current state and the `path`.
var transitions = currentState.pathsCache[path] = {
exitStates: exitStates,
enterStates: enterStates,
resolveState: resolveState
};
return transitions;
},
triggerSetupContext: function(transitions) {
var contexts = transitions.contexts,
offset = transitions.enterStates.length - contexts.length,
enterStates = transitions.enterStates,
transitionEvent = get(this, 'transitionEvent');
Ember.assert("More contexts provided than states", offset >= 0);
arrayForEach.call(enterStates, function(state, idx) {
state.trigger(transitionEvent, this, contexts[idx-offset]);
}, this);
},
getState: function(name) {
var state = get(this, name),
parentState = get(this, 'parentState');
if (state) {
return state;
} else if (parentState) {
return parentState.getState(name);
}
},
enterState: function(transition) {
var log = this.enableLogging;
var exitStates = transition.exitStates.slice(0).reverse();
arrayForEach.call(exitStates, function(state) {
state.trigger('exit', this);
}, this);
arrayForEach.call(transition.enterStates, function(state) {
if (log) { Ember.Logger.log("STATEMANAGER: Entering " + get(state, 'path')); }
state.trigger('enter', this);
}, this);
set(this, 'currentState', transition.finalState);
}
});
})();
(function() {
/**
Ember States
@module ember
@submodule ember-states
@requires ember-runtime
*/
})();
(function() {
var get = Ember.get;
Ember._ResolvedState = Ember.Object.extend({
manager: null,
state: null,
match: null,
object: Ember.computed(function(key, value) {
if (arguments.length === 2) {
this._object = value;
return value;
} else {
if (this._object) {
return this._object;
} else {
var state = get(this, 'state'),
match = get(this, 'match'),
manager = get(this, 'manager');
return state.deserialize(manager, match.hash);
}
}
}).property(),
hasPromise: Ember.computed(function() {
return Ember.canInvoke(get(this, 'object'), 'then');
}).property('object'),
promise: Ember.computed(function() {
var object = get(this, 'object');
if (Ember.canInvoke(object, 'then')) {
return object;
} else {
return {
then: function(success) { success(object); }
};
}
}).property('object'),
transition: function() {
var manager = get(this, 'manager'),
path = get(this, 'state.path'),
object = get(this, 'object');
manager.transitionTo(path, object);
}
});
})();
(function() {
/**
@module ember
@submodule ember-routing
*/
var get = Ember.get;
// The Ember Routable mixin assumes the existance of a simple
// routing shim that supports the following three behaviors:
//
// * .getURL() - this is called when the page loads
// * .setURL(newURL) - this is called from within the state
// manager when the state changes to a routable state
// * .onURLChange(callback) - this happens when the user presses
// the back or forward button
var paramForClass = function(classObject) {
var className = classObject.toString(),
parts = className.split("."),
last = parts[parts.length - 1];
return Ember.String.underscore(last) + "_id";
};
var merge = function(original, hash) {
for (var prop in hash) {
if (!hash.hasOwnProperty(prop)) { continue; }
if (original.hasOwnProperty(prop)) { continue; }
original[prop] = hash[prop];
}
};
/**
@class Routable
@namespace Ember
@extends Ember.Mixin
*/
Ember.Routable = Ember.Mixin.create({
init: function() {
var redirection;
this.on('setup', this, this.stashContext);
if (redirection = get(this, 'redirectsTo')) {
Ember.assert("You cannot use `redirectsTo` if you already have a `connectOutlets` method", this.connectOutlets === Ember.K);
this.connectOutlets = function(router) {
router.transitionTo(redirection);
};
}
// normalize empty route to '/'
var route = get(this, 'route');
if (route === '') {
route = '/';
}
this._super();
Ember.assert("You cannot use `redirectsTo` on a state that has child states", !redirection || (!!redirection && !!get(this, 'isLeaf')));
},
setup: function() {
return this.connectOutlets.apply(this, arguments);
},
/**
@private
Whenever a routable state is entered, the context it was entered with
is stashed so that we can regenerate the state's `absoluteURL` on
demand.
@method stashContext
@param manager {Ember.StateManager}
@param context
*/
stashContext: function(manager, context) {
this.router = manager;
var serialized = this.serialize(manager, context);
Ember.assert('serialize must return a hash', !serialized || typeof serialized === 'object');
manager.setStateMeta(this, 'context', context);
manager.setStateMeta(this, 'serialized', serialized);
if (get(this, 'isRoutable') && !get(manager, 'isRouting')) {
this.updateRoute(manager, get(manager, 'location'));
}
},
/**
@private
Whenever a routable state is entered, the router's location object
is notified to set the URL to the current absolute path.
In general, this will update the browser's URL.
@method updateRoute
@param manager {Ember.StateManager}
@param location {Ember.Location}
*/
updateRoute: function(manager, location) {
if (get(this, 'isLeafRoute')) {
var path = this.absoluteRoute(manager);
location.setURL(path);
}
},
/**
@private
Get the absolute route for the current state and a given
hash.
This method is private, as it expects a serialized hash,
not the original context object.
@method absoluteRoute
@param manager {Ember.StateManager}
@param hash {Hash}
*/
absoluteRoute: function(manager, hash) {
var parentState = get(this, 'parentState');
var path = '', generated;
// If the parent state is routable, use its current path
// as this route's prefix.
if (get(parentState, 'isRoutable')) {
path = parentState.absoluteRoute(manager, hash);
}
var matcher = get(this, 'routeMatcher'),
serialized = manager.getStateMeta(this, 'serialized');
// merge the existing serialized object in with the passed
// in hash.
hash = hash || {};
merge(hash, serialized);
generated = matcher && matcher.generate(hash);
if (generated) {
path = path + '/' + generated;
}
return path;
},
/**
@private
At the moment, a state is routable if it has a string `route`
property. This heuristic may change.
@property isRoutable
@type Boolean
*/
isRoutable: Ember.computed(function() {
return typeof get(this, 'route') === 'string';
}),
/**
@private
Determine if this is the last routeable state
@property isLeafRoute
@type Boolean
*/
isLeafRoute: Ember.computed(function() {
if (get(this, 'isLeaf')) { return true; }
return !get(this, 'childStates').findProperty('isRoutable');
}),
/**
@private
A _RouteMatcher object generated from the current route's `route`
string property.
@property routeMatcher
@type Ember._RouteMatcher
*/
routeMatcher: Ember.computed(function() {
var route = get(this, 'route');
if (route) {
return Ember._RouteMatcher.create({
route: route,
dynamicSegmentPattern: get(this, 'dynamicSegmentPattern'),
dynamicSegmentTerminators: get(this, 'dynamicSegmentTerminators')
});
}
}),
/**
@private
Check whether the route has dynamic segments and therefore takes
a context.
@property hasContext
@type Boolean
*/
hasContext: Ember.computed(function() {
var routeMatcher = get(this, 'routeMatcher');
if (routeMatcher) {
return routeMatcher.identifiers.length > 0;
}
}),
/**
@private
The model class associated with the current state. This property
uses the `modelType` property, in order to allow it to be
specified as a String.
@property modelClass
@type Ember.Object
*/
modelClass: Ember.computed(function() {
var modelType = get(this, 'modelType');
if (typeof modelType === 'string') {
return Ember.get(Ember.lookup, modelType);
} else {
return modelType;
}
}),
/**
@private
Get the model class for the state. The heuristic is:
* The state must have a single dynamic segment
* The dynamic segment must end in `_id`
* A dynamic segment like `blog_post_id` is converted into `BlogPost`
* The name is then looked up on the passed in namespace
The process of initializing an application with a router will
pass the application's namespace into the router, which will be
used here.
@method modelClassFor
@param namespace {Ember.Namespace}
*/
modelClassFor: function(namespace) {
var modelClass, routeMatcher, identifiers, match, className;
// if an explicit modelType was specified, use that
if (modelClass = get(this, 'modelClass')) { return modelClass; }
// if the router has no lookup namespace, we won't be able to guess
// the modelType
if (!namespace) { return; }
// make sure this state is actually a routable state
routeMatcher = get(this, 'routeMatcher');
if (!routeMatcher) { return; }
// only guess modelType for states with a single dynamic segment
// (no more, no fewer)
identifiers = routeMatcher.identifiers;
if (identifiers.length !== 2) { return; }
// extract the `_id` from the end of the dynamic segment; if the
// dynamic segment does not end in `_id`, we can't guess the
// modelType
match = identifiers[1].match(/^(.*)_id$/);
if (!match) { return; }
// convert the underscored type into a class form and look it up
// on the router's namespace
className = Ember.String.classify(match[1]);
return get(namespace, className);
},
/**
The default method that takes a `params` object and converts
it into an object.
By default, a params hash that looks like `{ post_id: 1 }`
will be looked up as `namespace.Post.find(1)`. This is
designed to work seamlessly with Ember Data, but will work
fine with any class that has a `find` method.
@method deserialize
@param manager {Ember.StateManager}
@param params {Hash}
*/
deserialize: function(manager, params) {
var modelClass, routeMatcher, param;
if (modelClass = this.modelClassFor(get(manager, 'namespace'))) {
Ember.assert("Expected "+modelClass.toString()+" to implement `find` for use in '"+this.get('path')+"' `deserialize`. Please implement the `find` method or overwrite `deserialize`.", modelClass.find);
return modelClass.find(params[paramForClass(modelClass)]);
}
return params;
},
/**
The default method that takes an object and converts it into
a params hash.
By default, if there is a single dynamic segment named
`blog_post_id` and the object is a `BlogPost` with an
`id` of `12`, the serialize method will produce:
{ blog_post_id: 12 }
@method serialize
@param manager {Ember.StateManager}
@param context
*/
serialize: function(manager, context) {
var modelClass, routeMatcher, namespace, param, id;
if (Ember.empty(context)) { return ''; }
if (modelClass = this.modelClassFor(get(manager, 'namespace'))) {
param = paramForClass(modelClass);
id = get(context, 'id');
context = {};
context[param] = id;
}
return context;
},
/**
@private
@method resolvePath
@param manager {Ember.StateManager}
@param path {String}
*/
resolvePath: function(manager, path) {
if (get(this, 'isLeafRoute')) { return Ember.A(); }
var childStates = get(this, 'childStates'), match;
childStates = Ember.A(childStates.filterProperty('isRoutable'));
childStates = childStates.sort(function(a, b) {
var aDynamicSegments = get(a, 'routeMatcher.identifiers.length'),
bDynamicSegments = get(b, 'routeMatcher.identifiers.length'),
aRoute = get(a, 'route'),
bRoute = get(b, 'route'),
aIndex = a.get('index'),
bIndex = b.get('index');
if( (aIndex || aIndex == 0) && (bIndex || bIndex == 0) ) {
return aIndex - bIndex
}
if (aRoute.indexOf(bRoute) === 0) {
return -1;
} else if (bRoute.indexOf(aRoute) === 0) {
return 1;
}
if (aDynamicSegments !== bDynamicSegments) {
return aDynamicSegments - bDynamicSegments;
}
return get(b, 'route.length') - get(a, 'route.length');
});
var state = childStates.find(function(state) {
var matcher = get(state, 'routeMatcher');
if (match = matcher.match(path)) { return true; }
});
Ember.assert("Could not find state for path " + path, !!state);
var resolvedState = Ember._ResolvedState.create({
manager: manager,
state: state,
match: match
});
var states = state.resolvePath(manager, match.remaining);
return Ember.A([resolvedState]).pushObjects(states);
},
/**
@private
Once `unroute` has finished unwinding, `routePath` will be called
with the remainder of the route.
For example, if you were in the /posts/1/comments state, and you
moved into the /posts/2/comments state, `routePath` will be called
on the state whose path is `/posts` with the path `/2/comments`.
@method routePath
@param manager {Ember.StateManager}
@param path {String}
*/
routePath: function(manager, path) {
if (get(this, 'isLeafRoute')) { return; }
var resolvedStates = this.resolvePath(manager, path),
hasPromises = resolvedStates.some(function(s) { return get(s, 'hasPromise'); });
function runTransition() {
resolvedStates.forEach(function(rs) { rs.transition(); });
}
if (hasPromises) {
manager.transitionTo('loading');
Ember.assert('Loading state should be the child of a route', Ember.Routable.detect(get(manager, 'currentState.parentState')));
Ember.assert('Loading state should not be a route', !Ember.Routable.detect(get(manager, 'currentState')));
manager.handleStatePromises(resolvedStates, runTransition);
} else {
runTransition();
}
},
/**
@private
When you move to a new route by pressing the back
or forward button, this method is called first.
Its job is to move the state manager into a parent
state of the state it will eventually move into.
@method unroutePath
@param router {Ember.Router}
@param path {String}
*/
unroutePath: function(router, path) {
var parentState = get(this, 'parentState');
// If we're at the root state, we're done
if (parentState === router) {
return;
}
path = path.replace(/^(?=[^\/])/, "/");
var absolutePath = this.absoluteRoute(router);
var route = get(this, 'route');
// If the current path is empty, move up one state,
// because the index ('/') state must be a leaf node.
if (route !== '/') {
// If the current path is a prefix of the path we're trying
// to go to, we're done.
var index = path.indexOf(absolutePath),
next = path.charAt(absolutePath.length);
if (index === 0 && (next === "/" || next === "")) {
return;
}
}
// Transition to the parent and call unroute again.
router.enterState({
exitStates: [this],
enterStates: [],
finalState: parentState
});
router.send('unroutePath', path);
},
parentTemplate: Ember.computed(function() {
var state = this, parentState, template;
while (state = get(state, 'parentState')) {
if (template = get(state, 'template')) {
return template;
}
}
return 'application';
}),
_template: Ember.computed(function(key, value) {
if (arguments.length > 1) { return value; }
if (value = get(this, 'template')) {
return value;
}
// If no template was explicitly supplied convert
// the class name into a template name. For example,
// App.PostRoute will return `post`.
var className = this.constructor.toString(), baseName;
if (/^[^\[].*Route$/.test(className)) {
baseName = className.match(/([^\.]+\.)*([^\.]+)/)[2];
baseName = baseName.replace(/Route$/, '');
return baseName.charAt(0).toLowerCase() + baseName.substr(1);
}
}),
render: function(options) {
options = options || {};
var template = options.template || get(this, '_template'),
parentTemplate = options.into || get(this, 'parentTemplate'),
controller = get(this.router, parentTemplate + "Controller");
var viewName = Ember.String.classify(template) + "View",
viewClass = get(get(this.router, 'namespace'), viewName);
viewClass = (viewClass || Ember.View).extend({
templateName: template
});
controller.set('view', viewClass.create());
},
/**
The `connectOutlets` event will be triggered once a
state has been entered. It will be called with the
route's context.
@event connectOutlets
@param router {Ember.Router}
@param [context*]
*/
connectOutlets: Ember.K,
/**
The `navigateAway` event will be triggered when the
URL changes due to the back/forward button
@event navigateAway
*/
navigateAway: Ember.K
});
})();
(function() {
/**
@module ember
@submodule ember-routing
*/
/**
@class Route
@namespace Ember
@extends Ember.State
@uses Ember.Routable
*/
Ember.Route = Ember.State.extend(Ember.Routable);
})();
(function() {
var escapeForRegex = function(text) {
return text.replace(/[\-\[\]{}()*+?.,\\\^\$|#\s]/g, "\\$&");
};
/**
@class _RouteMatcher
@namespace Ember
@private
@extends Ember.Object
*/
Ember._RouteMatcher = Ember.Object.extend({
state: null,
init: function() {
var route = this.route,
dynamicSegmentPattern = this.dynamicSegmentPattern || "([^/]+)",
terminators = this.dynamicSegmentTerminators || [],
identifiers = [],
count = 1,
escaped,
segmentRegexp;
// Strip off leading slash if present
if (route.charAt(0) === '/') {
route = this.route = route.substr(1);
}
escaped = escapeForRegex(route);
terminators.push('$|/');
str = ':([a-z_]+)(?=' + terminators.join('|') + ')'
segmentRegexp = new RegExp(str, 'gi');
var regex = escaped.replace(segmentRegexp, function(match, id) {
identifiers[count++] = id;
return dynamicSegmentPattern;
});
this.identifiers = identifiers;
this.regex = new RegExp("^/?" + regex);
},
match: function(path) {
var match = path.match(this.regex);
if (match) {
var identifiers = this.identifiers,
hash = {};
for (var i=1, l=identifiers.length; i 0 ? hash : null
};
}
},
generate: function(hash) {
var identifiers = this.identifiers, route = this.route, id;
for (var i=1, l=identifiers.length; i
" ],
map: [ 1, "" ],
_default: [ 0, "", "" ]
};
/**
* Given a parent node and some HTML, generate a set of nodes. Return the first
* node, which will allow us to traverse the rest using nextSibling.
*
* We need to do this because innerHTML in IE does not really parse the nodes.
**/
var firstNodeFor = function(parentNode, html) {
var arr = wrapMap[parentNode.tagName.toLowerCase()] || wrapMap._default;
var depth = arr[0], start = arr[1], end = arr[2];
if (needsShy) { html = ''+html; }
var element = document.createElement('div');
element.innerHTML = start + html + end;
for (var i=0; i<=depth; i++) {
element = element.firstChild;
}
// Look for to remove it.
if (needsShy) {
var shyElement = element;
// Sometimes we get nameless elements with the shy inside
while (shyElement.nodeType === 1 && !shyElement.nodeName) {
shyElement = shyElement.firstChild;
}
// At this point it's the actual unicode character.
if (shyElement.nodeType === 3 && shyElement.nodeValue.charAt(0) === "\u00AD") {
shyElement.nodeValue = shyElement.nodeValue.slice(1);
}
}
return element;
};
/**
* In some cases, Internet Explorer can create an anonymous node in
* the hierarchy with no tagName. You can create this scenario via:
*
* div = document.createElement("div");
* div.innerHTML = "
­
hi
";
* div.firstChild.firstChild.tagName //=> ""
*
* If our script markers are inside such a node, we need to find that
* node and use *it* as the marker.
**/
var realNode = function(start) {
while (start.parentNode.tagName === "") {
start = start.parentNode;
}
return start;
};
/**
* When automatically adding a tbody, Internet Explorer inserts the
* tbody immediately before the first
. Other browsers create it
* before the first node, no matter what.
*
* This means the the following code:
*
* div = document.createElement("div");
* div.innerHTML = "
hi
*
* Generates the following DOM in IE:
*
* + div
* + table
* - script id='first'
* + tbody
* + tr
* + td
* - "hi"
* - script id='last'
*
* Which means that the two script tags, even though they were
* inserted at the same point in the hierarchy in the original
* HTML, now have different parents.
*
* This code reparents the first script tag by making it the tbody's
* first child.
**/
var fixParentage = function(start, end) {
if (start.parentNode !== end.parentNode) {
end.parentNode.insertBefore(start, end.parentNode.firstChild);
}
};
htmlFunc = function(html, outerToo) {
// get the real starting node. see realNode for details.
var start = realNode(document.getElementById(this.start));
var end = document.getElementById(this.end);
var parentNode = end.parentNode;
var node, nextSibling, last;
// make sure that the start and end nodes share the same
// parent. If not, fix it.
fixParentage(start, end);
// remove all of the nodes after the starting placeholder and
// before the ending placeholder.
node = start.nextSibling;
while (node) {
nextSibling = node.nextSibling;
last = node === end;
// if this is the last node, and we want to remove it as well,
// set the `end` node to the next sibling. This is because
// for the rest of the function, we insert the new nodes
// before the end (note that insertBefore(node, null) is
// the same as appendChild(node)).
//
// if we do not want to remove it, just break.
if (last) {
if (outerToo) { end = node.nextSibling; } else { break; }
}
node.parentNode.removeChild(node);
// if this is the last node and we didn't break before
// (because we wanted to remove the outer nodes), break
// now.
if (last) { break; }
node = nextSibling;
}
// get the first node for the HTML string, even in cases like
// tables and lists where a simple innerHTML on a div would
// swallow some of the content.
node = firstNodeFor(start.parentNode, html);
// copy the nodes for the HTML between the starting and ending
// placeholder.
while (node) {
nextSibling = node.nextSibling;
parentNode.insertBefore(node, end);
node = nextSibling;
}
};
// remove the nodes in the DOM representing this metamorph.
//
// this includes the starting and ending placeholders.
removeFunc = function() {
var start = realNode(document.getElementById(this.start));
var end = document.getElementById(this.end);
this.html('');
start.parentNode.removeChild(start);
end.parentNode.removeChild(end);
};
appendToFunc = function(parentNode) {
var node = firstNodeFor(parentNode, this.outerHTML());
while (node) {
nextSibling = node.nextSibling;
parentNode.appendChild(node);
node = nextSibling;
}
};
afterFunc = function(html) {
// get the real starting node. see realNode for details.
var end = document.getElementById(this.end);
var insertBefore = end.nextSibling;
var parentNode = end.parentNode;
var nextSibling;
var node;
// get the first node for the HTML string, even in cases like
// tables and lists where a simple innerHTML on a div would
// swallow some of the content.
node = firstNodeFor(parentNode, html);
// copy the nodes for the HTML between the starting and ending
// placeholder.
while (node) {
nextSibling = node.nextSibling;
parentNode.insertBefore(node, insertBefore);
node = nextSibling;
}
};
prependFunc = function(html) {
var start = document.getElementById(this.start);
var parentNode = start.parentNode;
var nextSibling;
var node;
node = firstNodeFor(parentNode, html);
var insertBefore = start.nextSibling;
while (node) {
nextSibling = node.nextSibling;
parentNode.insertBefore(node, insertBefore);
node = nextSibling;
}
}
}
Metamorph.prototype.html = function(html) {
this.checkRemoved();
if (html === undefined) { return this.innerHTML; }
htmlFunc.call(this, html);
this.innerHTML = html;
};
Metamorph.prototype.replaceWith = function(html) {
this.checkRemoved();
htmlFunc.call(this, html, true);
};
Metamorph.prototype.remove = removeFunc;
Metamorph.prototype.outerHTML = outerHTMLFunc;
Metamorph.prototype.appendTo = appendToFunc;
Metamorph.prototype.after = afterFunc;
Metamorph.prototype.prepend = prependFunc;
Metamorph.prototype.startTag = startTagFunc;
Metamorph.prototype.endTag = endTagFunc;
Metamorph.prototype.isRemoved = function() {
var before = document.getElementById(this.start);
var after = document.getElementById(this.end);
return !before || !after;
};
Metamorph.prototype.checkRemoved = function() {
if (this.isRemoved()) {
throw new Error("Cannot perform operations on a Metamorph that is not in the DOM.");
}
};
window.Metamorph = Metamorph;
})(this);
})();
(function() {
/**
@module ember
@submodule ember-handlebars
*/
var objectCreate = Ember.create;
var Handlebars = Ember.imports.Handlebars;
Ember.assert("Ember Handlebars requires Handlebars 1.0.beta.5 or greater", Handlebars && Handlebars.VERSION.match(/^1\.0\.beta\.[56789]$|^1\.0\.rc\.[123456789]+/));
/**
Prepares the Handlebars templating library for use inside Ember's view
system.
The Ember.Handlebars object is the standard Handlebars library, extended to use
Ember's get() method instead of direct property access, which allows
computed properties to be used inside templates.
To create an Ember.Handlebars template, call Ember.Handlebars.compile(). This will
return a function that can be used by Ember.View for rendering.
@class Handlebars
@namespace Ember
*/
Ember.Handlebars = objectCreate(Handlebars);
/**
@class helpers
@namespace Ember.Handlebars
*/
Ember.Handlebars.helpers = objectCreate(Handlebars.helpers);
/**
Override the the opcode compiler and JavaScript compiler for Handlebars.
@class Compiler
@namespace Ember.Handlebars
@private
@constructor
*/
Ember.Handlebars.Compiler = function() {};
// Handlebars.Compiler doesn't exist in runtime-only
if (Handlebars.Compiler) {
Ember.Handlebars.Compiler.prototype = objectCreate(Handlebars.Compiler.prototype);
}
Ember.Handlebars.Compiler.prototype.compiler = Ember.Handlebars.Compiler;
/**
@class JavaScriptCompiler
@namespace Ember.Handlebars
@private
@constructor
*/
Ember.Handlebars.JavaScriptCompiler = function() {};
// Handlebars.JavaScriptCompiler doesn't exist in runtime-only
if (Handlebars.JavaScriptCompiler) {
Ember.Handlebars.JavaScriptCompiler.prototype = objectCreate(Handlebars.JavaScriptCompiler.prototype);
Ember.Handlebars.JavaScriptCompiler.prototype.compiler = Ember.Handlebars.JavaScriptCompiler;
}
Ember.Handlebars.JavaScriptCompiler.prototype.namespace = "Ember.Handlebars";
Ember.Handlebars.JavaScriptCompiler.prototype.initializeBuffer = function() {
return "''";
};
/**
@private
Override the default buffer for Ember Handlebars. By default, Handlebars creates
an empty String at the beginning of each invocation and appends to it. Ember's
Handlebars overrides this to append to a single shared buffer.
@method appendToBuffer
@param string {String}
*/
Ember.Handlebars.JavaScriptCompiler.prototype.appendToBuffer = function(string) {
return "data.buffer.push("+string+");";
};
/**
@private
Rewrite simple mustaches from `{{foo}}` to `{{bind "foo"}}`. This means that all simple
mustaches in Ember's Handlebars will also set up an observer to keep the DOM
up to date when the underlying property changes.
@method mustache
@for Ember.Handlebars.Compiler
@param mustache
*/
Ember.Handlebars.Compiler.prototype.mustache = function(mustache) {
if (mustache.params.length || mustache.hash) {
return Handlebars.Compiler.prototype.mustache.call(this, mustache);
} else {
var id = new Handlebars.AST.IdNode(['_triageMustache']);
// Update the mustache node to include a hash value indicating whether the original node
// was escaped. This will allow us to properly escape values when the underlying value
// changes and we need to re-render the value.
if(!mustache.escaped) {
mustache.hash = mustache.hash || new Handlebars.AST.HashNode([]);
mustache.hash.pairs.push(["unescaped", new Handlebars.AST.StringNode("true")]);
}
mustache = new Handlebars.AST.MustacheNode([id].concat([mustache.id]), mustache.hash, !mustache.escaped);
return Handlebars.Compiler.prototype.mustache.call(this, mustache);
}
};
/**
Used for precompilation of Ember Handlebars templates. This will not be used during normal
app execution.
@method precompile
@for Ember.Handlebars
@static
@param {String} string The template to precompile
*/
Ember.Handlebars.precompile = function(string) {
var ast = Handlebars.parse(string);
var options = {
knownHelpers: {
action: true,
unbound: true,
bindAttr: true,
template: true,
view: true,
_triageMustache: true
},
data: true,
stringParams: true
};
var environment = new Ember.Handlebars.Compiler().compile(ast, options);
return new Ember.Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true);
};
// We don't support this for Handlebars runtime-only
if (Handlebars.compile) {
/**
The entry point for Ember Handlebars. This replaces the default Handlebars.compile and turns on
template-local data and String parameters.
@method compile
@for Ember.Handlebars
@static
@param {String} string The template to compile
@return {Function}
*/
Ember.Handlebars.compile = function(string) {
var ast = Handlebars.parse(string);
var options = { data: true, stringParams: true };
var environment = new Ember.Handlebars.Compiler().compile(ast, options);
var templateSpec = new Ember.Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true);
return Handlebars.template(templateSpec);
};
}
/**
@private
If a path starts with a reserved keyword, returns the root
that should be used.
@method normalizePath
@for Ember
@param root {Object}
@param path {String}
@param data {Hash}
*/
var normalizePath = Ember.Handlebars.normalizePath = function(root, path, data) {
var keywords = (data && data.keywords) || {},
keyword, isKeyword;
// Get the first segment of the path. For example, if the
// path is "foo.bar.baz", returns "foo".
keyword = path.split('.', 1)[0];
// Test to see if the first path is a keyword that has been
// passed along in the view's data hash. If so, we will treat
// that object as the new root.
if (keywords.hasOwnProperty(keyword)) {
// Look up the value in the template's data hash.
root = keywords[keyword];
isKeyword = true;
// Handle cases where the entire path is the reserved
// word. In that case, return the object itself.
if (path === keyword) {
path = '';
} else {
// Strip the keyword from the path and look up
// the remainder from the newly found root.
path = path.substr(keyword.length+1);
}
}
return { root: root, path: path, isKeyword: isKeyword };
};
/**
Lookup both on root and on window. If the path starts with
a keyword, the corresponding object will be looked up in the
template's data hash and used to resolve the path.
@method getPath
@for Ember.Handlebars
@param {Object} root The object to look up the property on
@param {String} path The path to be lookedup
@param {Object} options The template's option hash
*/
Ember.Handlebars.getPath = function(root, path, options) {
var data = options && options.data,
normalizedPath = normalizePath(root, path, data),
value;
// In cases where the path begins with a keyword, change the
// root to the value represented by that keyword, and ensure
// the path is relative to it.
root = normalizedPath.root;
path = normalizedPath.path;
value = Ember.get(root, path);
// If the path starts with a capital letter, look it up on Ember.lookup,
// which defaults to the `window` object in browsers.
if (value === undefined && root !== Ember.lookup && Ember.isGlobalPath(path)) {
value = Ember.get(Ember.lookup, path);
}
return value;
};
/**
@private
Registers a helper in Handlebars that will be called if no property with the
given name can be found on the current context object, and no helper with
that name is registered.
This throws an exception with a more helpful error message so the user can
track down where the problem is happening.
@method helperMissing
@for Ember.Handlebars.helpers
@param {String} path
@param {Hash} options
*/
Ember.Handlebars.registerHelper('helperMissing', function(path, options) {
var error, view = "";
error = "%@ Handlebars error: Could not find property '%@' on object %@.";
if (options.data){
view = options.data.view;
}
throw new Ember.Error(Ember.String.fmt(error, [view, path, this]));
});
})();
(function() {
/**
@method htmlSafe
@for Ember.String
@static
*/
Ember.String.htmlSafe = function(str) {
return new Handlebars.SafeString(str);
};
var htmlSafe = Ember.String.htmlSafe;
if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) {
/**
See {{#crossLink "Ember.String/htmlSafe"}}{{/crossLink}}
@method htmlSafe
@for String
*/
String.prototype.htmlSafe = function() {
return htmlSafe(this);
};
}
})();
(function() {
/*jshint newcap:false*/
/**
@module ember
@submodule ember-handlebars
*/
var set = Ember.set, get = Ember.get;
// DOMManager should just abstract dom manipulation between jquery and metamorph
var DOMManager = {
remove: function(view) {
view.morph.remove();
},
prepend: function(view, html) {
view.morph.prepend(html);
},
after: function(view, html) {
view.morph.after(html);
},
html: function(view, html) {
view.morph.html(html);
},
// This is messed up.
replace: function(view) {
var morph = view.morph;
view.transitionTo('preRender');
view.clearRenderedChildren();
var buffer = view.renderToBuffer();
Ember.run.schedule('render', this, function() {
if (get(view, 'isDestroyed')) { return; }
view.invalidateRecursively('element');
view._notifyWillInsertElement();
morph.replaceWith(buffer.string());
view.transitionTo('inDOM');
view._notifyDidInsertElement();
});
},
empty: function(view) {
view.morph.html("");
}
};
// The `morph` and `outerHTML` properties are internal only
// and not observable.
/**
@class _Metamorph
@namespace Ember
@extends Ember.Mixin
@private
*/
Ember._Metamorph = Ember.Mixin.create({
isVirtual: true,
tagName: '',
instrumentName: 'render.metamorph',
init: function() {
this._super();
this.morph = Metamorph();
},
beforeRender: function(buffer) {
buffer.push(this.morph.startTag());
},
afterRender: function(buffer) {
buffer.push(this.morph.endTag());
},
createElement: function() {
var buffer = this.renderToBuffer();
this.outerHTML = buffer.string();
this.clearBuffer();
},
domManager: DOMManager
});
/**
@class _MetamorphView
@namespace Ember
@extends Ember.View
@uses Ember._Metamorph
@private
*/
Ember._MetamorphView = Ember.View.extend(Ember._Metamorph);
/**
@class _SimpleMetamorphView
@namespace Ember
@extends Ember.View
@uses Ember._Metamorph
@private
*/
Ember._SimpleMetamorphView = Ember.CoreView.extend(Ember._Metamorph);
})();
(function() {
/*globals Handlebars */
/**
@module ember
@submodule ember-handlebars
*/
var get = Ember.get, set = Ember.set, getPath = Ember.Handlebars.getPath;
Ember._SimpleHandlebarsView = Ember._SimpleMetamorphView.extend({
instrumentName: 'render.simpleHandlebars',
normalizedValue: Ember.computed(function() {
var path = get(this, 'path'),
pathRoot = get(this, 'pathRoot'),
result, templateData;
// Use the pathRoot as the result if no path is provided. This
// happens if the path is `this`, which gets normalized into
// a `pathRoot` of the current Handlebars context and a path
// of `''`.
if (path === '') {
result = pathRoot;
} else {
templateData = get(this, 'templateData');
result = getPath(pathRoot, path, { data: templateData });
}
return result;
}).property('path', 'pathRoot').volatile(),
render: function(buffer) {
// If not invoked via a triple-mustache ({{{foo}}}), escape
// the content of the template.
var escape = get(this, 'isEscaped');
var result = get(this, 'normalizedValue');
if (result === null || result === undefined) {
result = "";
} else if (!(result instanceof Handlebars.SafeString)) {
result = String(result);
}
if (escape) { result = Handlebars.Utils.escapeExpression(result); }
buffer.push(result);
return;
},
rerender: function() {
switch(this.state) {
case 'preRender':
case 'destroyed':
break;
case 'inBuffer':
throw new Error("Something you did tried to replace an {{expression}} before it was inserted into the DOM.");
case 'hasElement':
case 'inDOM':
this.domManager.replace(this);
break;
}
return this;
},
transitionTo: function(state) {
this.state = state;
}
});
/**
Ember._HandlebarsBoundView is a private view created by the Handlebars `{{bind}}`
helpers that is used to keep track of bound properties.
Every time a property is bound using a `{{mustache}}`, an anonymous subclass
of Ember._HandlebarsBoundView is created with the appropriate sub-template and
context set up. When the associated property changes, just the template for
this view will re-render.
@class _HandlebarsBoundView
@namespace Ember
@extends Ember._MetamorphView
@private
*/
Ember._HandlebarsBoundView = Ember._MetamorphView.extend({
instrumentName: 'render.boundHandlebars',
/**
The function used to determine if the `displayTemplate` or
`inverseTemplate` should be rendered. This should be a function that takes
a value and returns a Boolean.
@property shouldDisplayFunc
@type Function
@default null
*/
shouldDisplayFunc: null,
/**
Whether the template rendered by this view gets passed the context object
of its parent template, or gets passed the value of retrieving `path`
from the `pathRoot`.
For example, this is true when using the `{{#if}}` helper, because the
template inside the helper should look up properties relative to the same
object as outside the block. This would be false when used with `{{#with
foo}}` because the template should receive the object found by evaluating
`foo`.
@property preserveContext
@type Boolean
@default false
*/
preserveContext: false,
/**
If `preserveContext` is true, this is the object that will be used
to render the template.
@property previousContext
@type Object
*/
previousContext: null,
/**
The template to render when `shouldDisplayFunc` evaluates to true.
@property displayTemplate
@type Function
@default null
*/
displayTemplate: null,
/**
The template to render when `shouldDisplayFunc` evaluates to false.
@property inverseTemplate
@type Function
@default null
*/
inverseTemplate: null,
/**
The path to look up on `pathRoot` that is passed to
`shouldDisplayFunc` to determine which template to render.
In addition, if `preserveContext` is false, the object at this path will
be passed to the template when rendering.
@property path
@type String
@default null
*/
path: null,
/**
The object from which the `path` will be looked up. Sometimes this is the
same as the `previousContext`, but in cases where this view has been generated
for paths that start with a keyword such as `view` or `controller`, the
path root will be that resolved object.
@property pathRoot
@type Object
*/
pathRoot: null,
normalizedValue: Ember.computed(function() {
var path = get(this, 'path'),
pathRoot = get(this, 'pathRoot'),
valueNormalizer = get(this, 'valueNormalizerFunc'),
result, templateData;
// Use the pathRoot as the result if no path is provided. This
// happens if the path is `this`, which gets normalized into
// a `pathRoot` of the current Handlebars context and a path
// of `''`.
if (path === '') {
result = pathRoot;
} else {
templateData = get(this, 'templateData');
result = getPath(pathRoot, path, { data: templateData });
}
return valueNormalizer ? valueNormalizer(result) : result;
}).property('path', 'pathRoot', 'valueNormalizerFunc').volatile(),
rerenderIfNeeded: function() {
if (!get(this, 'isDestroyed') && get(this, 'normalizedValue') !== this._lastNormalizedValue) {
this.rerender();
}
},
/**
Determines which template to invoke, sets up the correct state based on
that logic, then invokes the default Ember.View `render` implementation.
This method will first look up the `path` key on `pathRoot`,
then pass that value to the `shouldDisplayFunc` function. If that returns
true, the `displayTemplate` function will be rendered to DOM. Otherwise,
`inverseTemplate`, if specified, will be rendered.
For example, if this Ember._HandlebarsBoundView represented the `{{#with foo}}`
helper, it would look up the `foo` property of its context, and
`shouldDisplayFunc` would always return true. The object found by looking
up `foo` would be passed to `displayTemplate`.
@method render
@param {Ember.RenderBuffer} buffer
*/
render: function(buffer) {
// If not invoked via a triple-mustache ({{{foo}}}), escape
// the content of the template.
var escape = get(this, 'isEscaped');
var shouldDisplay = get(this, 'shouldDisplayFunc'),
preserveContext = get(this, 'preserveContext'),
context = get(this, 'previousContext');
var inverseTemplate = get(this, 'inverseTemplate'),
displayTemplate = get(this, 'displayTemplate');
var result = get(this, 'normalizedValue');
this._lastNormalizedValue = result;
// First, test the conditional to see if we should
// render the template or not.
if (shouldDisplay(result)) {
set(this, 'template', displayTemplate);
// If we are preserving the context (for example, if this
// is an #if block, call the template with the same object.
if (preserveContext) {
set(this, '_context', context);
} else {
// Otherwise, determine if this is a block bind or not.
// If so, pass the specified object to the template
if (displayTemplate) {
set(this, '_context', result);
} else {
// This is not a bind block, just push the result of the
// expression to the render context and return.
if (result === null || result === undefined) {
result = "";
} else if (!(result instanceof Handlebars.SafeString)) {
result = String(result);
}
if (escape) { result = Handlebars.Utils.escapeExpression(result); }
buffer.push(result);
return;
}
}
} else if (inverseTemplate) {
set(this, 'template', inverseTemplate);
if (preserveContext) {
set(this, '_context', context);
} else {
set(this, '_context', result);
}
} else {
set(this, 'template', function() { return ''; });
}
return this._super(buffer);
}
});
})();
(function() {
/**
@module ember
@submodule ember-handlebars
*/
var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt;
var getPath = Ember.Handlebars.getPath, normalizePath = Ember.Handlebars.normalizePath;
var forEach = Ember.ArrayPolyfills.forEach;
var EmberHandlebars = Ember.Handlebars, helpers = EmberHandlebars.helpers;
// Binds a property into the DOM. This will create a hook in DOM that the
// KVO system will look for and update if the property changes.
function bind(property, options, preserveContext, shouldDisplay, valueNormalizer) {
var data = options.data,
fn = options.fn,
inverse = options.inverse,
view = data.view,
currentContext = this,
pathRoot, path, normalized;
normalized = normalizePath(currentContext, property, data);
pathRoot = normalized.root;
path = normalized.path;
// Set up observers for observable objects
if ('object' === typeof this) {
// Create the view that will wrap the output of this template/property
// and add it to the nearest view's childViews array.
// See the documentation of Ember._HandlebarsBoundView for more.
var bindView = view.createChildView(Ember._HandlebarsBoundView, {
preserveContext: preserveContext,
shouldDisplayFunc: shouldDisplay,
valueNormalizerFunc: valueNormalizer,
displayTemplate: fn,
inverseTemplate: inverse,
path: path,
pathRoot: pathRoot,
previousContext: currentContext,
isEscaped: !options.hash.unescaped,
templateData: options.data
});
view.appendChild(bindView);
var observer = function() {
Ember.run.scheduleOnce('render', bindView, 'rerenderIfNeeded');
};
// Observes the given property on the context and
// tells the Ember._HandlebarsBoundView to re-render. If property
// is an empty string, we are printing the current context
// object ({{this}}) so updating it is not our responsibility.
if (path !== '') {
Ember.addObserver(pathRoot, path, observer);
view.one('willClearRender', function() {
Ember.removeObserver(pathRoot, path, observer);
});
}
} else {
// The object is not observable, so just render it out and
// be done with it.
data.buffer.push(getPath(pathRoot, path, options));
}
}
function simpleBind(property, options) {
var data = options.data,
view = data.view,
currentContext = this,
pathRoot, path, normalized;
normalized = normalizePath(currentContext, property, data);
pathRoot = normalized.root;
path = normalized.path;
// Set up observers for observable objects
if ('object' === typeof this) {
var bindView = Ember._SimpleHandlebarsView.create().setProperties({
path: path,
pathRoot: pathRoot,
isEscaped: !options.hash.unescaped,
previousContext: currentContext,
templateData: options.data
});
view.createChildView(bindView);
view.appendChild(bindView);
var observer = function() {
Ember.run.scheduleOnce('render', bindView, 'rerender');
};
// Observes the given property on the context and
// tells the Ember._HandlebarsBoundView to re-render. If property
// is an empty string, we are printing the current context
// object ({{this}}) so updating it is not our responsibility.
if (path !== '') {
Ember.addObserver(pathRoot, path, observer);
view.one('willClearRender', function() {
Ember.removeObserver(pathRoot, path, observer);
});
}
} else {
// The object is not observable, so just render it out and
// be done with it.
data.buffer.push(getPath(pathRoot, path, options));
}
}
/**
@private
'_triageMustache' is used internally select between a binding and helper for
the given context. Until this point, it would be hard to determine if the
mustache is a property reference or a regular helper reference. This triage
helper resolves that.
This would not be typically invoked by directly.
@method _triageMustache
@for Ember.Handlebars.helpers
@param {String} property Property/helperID to triage
@param {Function} fn Context to provide for rendering
@return {String} HTML string
*/
EmberHandlebars.registerHelper('_triageMustache', function(property, fn) {
Ember.assert("You cannot pass more than one argument to the _triageMustache helper", arguments.length <= 2);
if (helpers[property]) {
return helpers[property].call(this, fn);
}
else {
return helpers.bind.apply(this, arguments);
}
});
/**
@private
`bind` can be used to display a value, then update that value if it
changes. For example, if you wanted to print the `title` property of
`content`:
``` handlebars
{{bind "content.title"}}
```
This will return the `title` property as a string, then create a new
observer at the specified path. If it changes, it will update the value in
DOM. Note that if you need to support IE7 and IE8 you must modify the
model objects properties using Ember.get() and Ember.set() for this to work as
it relies on Ember's KVO system. For all other browsers this will be handled
for you automatically.
@method bind
@for Ember.Handlebars.helpers
@param {String} property Property to bind
@param {Function} fn Context to provide for rendering
@return {String} HTML string
*/
EmberHandlebars.registerHelper('bind', function(property, options) {
Ember.assert("You cannot pass more than one argument to the bind helper", arguments.length <= 2);
var context = (options.contexts && options.contexts[0]) || this;
if (!options.fn) {
return simpleBind.call(context, property, options);
}
return bind.call(context, property, options, false, function(result) {
return !Ember.none(result);
});
});
/**
@private
Use the `boundIf` helper to create a conditional that re-evaluates
whenever the bound value changes.
``` handlebars
{{#boundIf "content.shouldDisplayTitle"}}
{{content.title}}
{{/boundIf}}
```
@method boundIf
@for Ember.Handlebars.helpers
@param {String} property Property to bind
@param {Function} fn Context to provide for rendering
@return {String} HTML string
*/
EmberHandlebars.registerHelper('boundIf', function(property, fn) {
var context = (fn.contexts && fn.contexts[0]) || this;
var func = function(result) {
if (Ember.typeOf(result) === 'array') {
return get(result, 'length') !== 0;
} else {
return !!result;
}
};
return bind.call(context, property, fn, true, func, func);
});
/**
@method with
@for Ember.Handlebars.helpers
@param {Function} context
@param {Hash} options
@return {String} HTML string
*/
EmberHandlebars.registerHelper('with', function(context, options) {
if (arguments.length === 4) {
var keywordName, path, rootPath, normalized;
Ember.assert("If you pass more than one argument to the with helper, it must be in the form #with foo as bar", arguments[1] === "as");
options = arguments[3];
keywordName = arguments[2];
path = arguments[0];
Ember.assert("You must pass a block to the with helper", options.fn && options.fn !== Handlebars.VM.noop);
if (Ember.isGlobalPath(path)) {
Ember.bind(options.data.keywords, keywordName, path);
} else {
normalized = normalizePath(this, path, options.data);
path = normalized.path;
rootPath = normalized.root;
// This is a workaround for the fact that you cannot bind separate objects
// together. When we implement that functionality, we should use it here.
var contextKey = Ember.$.expando + Ember.guidFor(rootPath);
options.data.keywords[contextKey] = rootPath;
// if the path is '' ("this"), just bind directly to the current context
var contextPath = path ? contextKey + '.' + path : contextKey;
Ember.bind(options.data.keywords, keywordName, contextPath);
}
return bind.call(this, path, options, true, function(result) {
return !Ember.none(result);
});
} else {
Ember.assert("You must pass exactly one argument to the with helper", arguments.length === 2);
Ember.assert("You must pass a block to the with helper", options.fn && options.fn !== Handlebars.VM.noop);
return helpers.bind.call(options.contexts[0], context, options);
}
});
/**
@method if
@for Ember.Handlebars.helpers
@param {Function} context
@param {Hash} options
@return {String} HTML string
*/
EmberHandlebars.registerHelper('if', function(context, options) {
Ember.assert("You must pass exactly one argument to the if helper", arguments.length === 2);
Ember.assert("You must pass a block to the if helper", options.fn && options.fn !== Handlebars.VM.noop);
return helpers.boundIf.call(options.contexts[0], context, options);
});
/**
@method unless
@for Ember.Handlebars.helpers
@param {Function} context
@param {Hash} options
@return {String} HTML string
*/
EmberHandlebars.registerHelper('unless', function(context, options) {
Ember.assert("You must pass exactly one argument to the unless helper", arguments.length === 2);
Ember.assert("You must pass a block to the unless helper", options.fn && options.fn !== Handlebars.VM.noop);
var fn = options.fn, inverse = options.inverse;
options.fn = inverse;
options.inverse = fn;
return helpers.boundIf.call(options.contexts[0], context, options);
});
/**
`bindAttr` allows you to create a binding between DOM element attributes and
Ember objects. For example:
``` handlebars
```
@method bindAttr
@for Ember.Handlebars.helpers
@param {Hash} options
@return {String} HTML string
*/
EmberHandlebars.registerHelper('bindAttr', function(options) {
var attrs = options.hash;
Ember.assert("You must specify at least one hash argument to bindAttr", !!Ember.keys(attrs).length);
var view = options.data.view;
var ret = [];
var ctx = this;
// Generate a unique id for this element. This will be added as a
// data attribute to the element so it can be looked up when
// the bound property changes.
var dataId = ++Ember.$.uuid;
// Handle classes differently, as we can bind multiple classes
var classBindings = attrs['class'];
if (classBindings !== null && classBindings !== undefined) {
var classResults = EmberHandlebars.bindClasses(this, classBindings, view, dataId, options);
ret.push('class="' + Handlebars.Utils.escapeExpression(classResults.join(' ')) + '"');
delete attrs['class'];
}
var attrKeys = Ember.keys(attrs);
// For each attribute passed, create an observer and emit the
// current value of the property as an attribute.
forEach.call(attrKeys, function(attr) {
var path = attrs[attr],
pathRoot, normalized;
Ember.assert(fmt("You must provide a String for a bound attribute, not %@", [path]), typeof path === 'string');
normalized = normalizePath(ctx, path, options.data);
pathRoot = normalized.root;
path = normalized.path;
var value = (path === 'this') ? pathRoot : getPath(pathRoot, path, options),
type = Ember.typeOf(value);
Ember.assert(fmt("Attributes must be numbers, strings or booleans, not %@", [value]), value === null || value === undefined || type === 'number' || type === 'string' || type === 'boolean');
var observer, invoker;
observer = function observer() {
var result = getPath(pathRoot, path, options);
Ember.assert(fmt("Attributes must be numbers, strings or booleans, not %@", [result]), result === null || result === undefined || typeof result === 'number' || typeof result === 'string' || typeof result === 'boolean');
var elem = view.$("[data-bindattr-" + dataId + "='" + dataId + "']");
// If we aren't able to find the element, it means the element
// to which we were bound has been removed from the view.
// In that case, we can assume the template has been re-rendered
// and we need to clean up the observer.
if (!elem || elem.length === 0) {
Ember.removeObserver(pathRoot, path, invoker);
return;
}
Ember.View.applyAttributeBindings(elem, attr, result);
};
invoker = function() {
Ember.run.scheduleOnce('render', observer);
};
// Add an observer to the view for when the property changes.
// When the observer fires, find the element using the
// unique data id and update the attribute to the new value.
if (path !== 'this') {
Ember.addObserver(pathRoot, path, invoker);
view.one('willClearRender', function() {
Ember.removeObserver(pathRoot, path, invoker);
});
}
// if this changes, also change the logic in ember-views/lib/views/view.js
if ((type === 'string' || (type === 'number' && !isNaN(value)))) {
ret.push(attr + '="' + Handlebars.Utils.escapeExpression(value) + '"');
} else if (value && type === 'boolean') {
// The developer controls the attr name, so it should always be safe
ret.push(attr + '="' + attr + '"');
}
}, this);
// Add the unique identifier
// NOTE: We use all lower-case since Firefox has problems with mixed case in SVG
ret.push('data-bindattr-' + dataId + '="' + dataId + '"');
return new EmberHandlebars.SafeString(ret.join(' '));
});
/**
@private
Helper that, given a space-separated string of property paths and a context,
returns an array of class names. Calling this method also has the side
effect of setting up observers at those property paths, such that if they
change, the correct class name will be reapplied to the DOM element.
For example, if you pass the string "fooBar", it will first look up the
"fooBar" value of the context. If that value is true, it will add the
"foo-bar" class to the current element (i.e., the dasherized form of
"fooBar"). If the value is a string, it will add that string as the class.
Otherwise, it will not add any new class name.
@method bindClasses
@for Ember.Handlebars
@param {Ember.Object} context The context from which to lookup properties
@param {String} classBindings A string, space-separated, of class bindings to use
@param {Ember.View} view The view in which observers should look for the element to update
@param {Srting} bindAttrId Optional bindAttr id used to lookup elements
@return {Array} An array of class names to add
*/
EmberHandlebars.bindClasses = function(context, classBindings, view, bindAttrId, options) {
var ret = [], newClass, value, elem;
// Helper method to retrieve the property from the context and
// determine which class string to return, based on whether it is
// a Boolean or not.
var classStringForPath = function(root, parsedPath, options) {
var val,
path = parsedPath.path;
if (path === 'this') {
val = root;
} else if (path === '') {
val = true;
} else {
val = getPath(root, path, options);
}
return Ember.View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName);
};
// For each property passed, loop through and setup
// an observer.
forEach.call(classBindings.split(' '), function(binding) {
// Variable in which the old class value is saved. The observer function
// closes over this variable, so it knows which string to remove when
// the property changes.
var oldClass;
var observer, invoker;
var parsedPath = Ember.View._parsePropertyPath(binding),
path = parsedPath.path,
pathRoot = context,
normalized;
if (path !== '' && path !== 'this') {
normalized = normalizePath(context, path, options.data);
pathRoot = normalized.root;
path = normalized.path;
}
// Set up an observer on the context. If the property changes, toggle the
// class name.
observer = function() {
// Get the current value of the property
newClass = classStringForPath(pathRoot, parsedPath, options);
elem = bindAttrId ? view.$("[data-bindattr-" + bindAttrId + "='" + bindAttrId + "']") : view.$();
// If we can't find the element anymore, a parent template has been
// re-rendered and we've been nuked. Remove the observer.
if (!elem || elem.length === 0) {
Ember.removeObserver(pathRoot, path, invoker);
} else {
// If we had previously added a class to the element, remove it.
if (oldClass) {
elem.removeClass(oldClass);
}
// If necessary, add a new class. Make sure we keep track of it so
// it can be removed in the future.
if (newClass) {
elem.addClass(newClass);
oldClass = newClass;
} else {
oldClass = null;
}
}
};
invoker = function() {
Ember.run.scheduleOnce('render', observer);
};
if (path !== '' && path !== 'this') {
Ember.addObserver(pathRoot, path, invoker);
view.one('willClearRender', function() {
Ember.removeObserver(pathRoot, path, invoker);
});
}
// We've already setup the observer; now we just need to figure out the
// correct behavior right now on the first pass through.
value = classStringForPath(pathRoot, parsedPath, options);
if (value) {
ret.push(value);
// Make sure we save the current value so that it can be removed if the
// observer fires.
oldClass = value;
}
});
return ret;
};
})();
(function() {
/*globals Handlebars */
// TODO: Don't require the entire module
/**
@module ember
@submodule ember-handlebars
*/
var get = Ember.get, set = Ember.set;
var PARENT_VIEW_PATH = /^parentView\./;
var EmberHandlebars = Ember.Handlebars;
EmberHandlebars.ViewHelper = Ember.Object.create({
propertiesFromHTMLOptions: function(options, thisContext) {
var hash = options.hash, data = options.data;
var extensions = {},
classes = hash['class'],
dup = false;
if (hash.id) {
extensions.elementId = hash.id;
dup = true;
}
if (classes) {
classes = classes.split(' ');
extensions.classNames = classes;
dup = true;
}
if (hash.classBinding) {
extensions.classNameBindings = hash.classBinding.split(' ');
dup = true;
}
if (hash.classNameBindings) {
if (extensions.classNameBindings === undefined) extensions.classNameBindings = [];
extensions.classNameBindings = extensions.classNameBindings.concat(hash.classNameBindings.split(' '));
dup = true;
}
if (hash.attributeBindings) {
Ember.assert("Setting 'attributeBindings' via Handlebars is not allowed. Please subclass Ember.View and set it there instead.");
extensions.attributeBindings = null;
dup = true;
}
if (dup) {
hash = Ember.$.extend({}, hash);
delete hash.id;
delete hash['class'];
delete hash.classBinding;
}
// Set the proper context for all bindings passed to the helper. This applies to regular attribute bindings
// as well as class name bindings. If the bindings are local, make them relative to the current context
// instead of the view.
var path;
// Evaluate the context of regular attribute bindings:
for (var prop in hash) {
if (!hash.hasOwnProperty(prop)) { continue; }
// Test if the property ends in "Binding"
if (Ember.IS_BINDING.test(prop) && typeof hash[prop] === 'string') {
path = this.contextualizeBindingPath(hash[prop], data);
if (path) { hash[prop] = path; }
}
}
// Evaluate the context of class name bindings:
if (extensions.classNameBindings) {
for (var b in extensions.classNameBindings) {
var full = extensions.classNameBindings[b];
if (typeof full === 'string') {
// Contextualize the path of classNameBinding so this:
//
// classNameBinding="isGreen:green"
//
// is converted to this:
//
// classNameBinding="bindingContext.isGreen:green"
var parsedPath = Ember.View._parsePropertyPath(full);
path = this.contextualizeBindingPath(parsedPath.path, data);
if (path) { extensions.classNameBindings[b] = path + parsedPath.classNames; }
}
}
}
// Make the current template context available to the view
// for the bindings set up above.
extensions.bindingContext = thisContext;
return Ember.$.extend(hash, extensions);
},
// Transform bindings from the current context to a context that can be evaluated within the view.
// Returns null if the path shouldn't be changed.
//
// TODO: consider the addition of a prefix that would allow this method to return `path`.
contextualizeBindingPath: function(path, data) {
var normalized = Ember.Handlebars.normalizePath(null, path, data);
if (normalized.isKeyword) {
return 'templateData.keywords.' + path;
} else if (Ember.isGlobalPath(path)) {
return null;
} else if (path === 'this') {
return 'bindingContext';
} else {
return 'bindingContext.' + path;
}
},
helper: function(thisContext, path, options) {
var inverse = options.inverse,
data = options.data,
view = data.view,
fn = options.fn,
hash = options.hash,
newView;
if ('string' === typeof path) {
newView = EmberHandlebars.getPath(thisContext, path, options);
Ember.assert("Unable to find view at path '" + path + "'", !!newView);
} else {
newView = path;
}
Ember.assert(Ember.String.fmt('You must pass a view class to the #view helper, not %@ (%@)', [path, newView]), Ember.View.detect(newView));
var viewOptions = this.propertiesFromHTMLOptions(options, thisContext);
var currentView = data.view;
viewOptions.templateData = options.data;
if (fn) {
Ember.assert("You cannot provide a template block if you also specified a templateName", !get(viewOptions, 'templateName') && !get(newView.proto(), 'templateName'));
viewOptions.template = fn;
}
// We only want to override the `_context` computed property if there is
// no specified controller. See View#_context for more information.
if (!newView.proto().controller && !newView.proto().controllerBinding && !viewOptions.controller && !viewOptions.controllerBinding) {
viewOptions._context = thisContext;
}
currentView.appendChild(newView, viewOptions);
}
});
/**
`{{view}}` inserts a new instance of `Ember.View` into a template passing its options
to the `Ember.View`'s `create` method and using the supplied block as the view's own template.
An empty `` and the following template:
``` handlebars
```
Will result in HTML structure:
``` html
A span:
Hello.
```
### parentView setting
The `parentView` property of the new `Ember.View` instance created through `{{view}}`
will be set to the `Ember.View` instance of the template where `{{view}}` was called.
``` javascript
aView = Ember.View.create({
template: Ember.Handlebars.compile("{{#view}} my parent: {{parentView.elementId}} {{/view}}")
});
aView.appendTo('body');
```
Will result in HTML structure:
``` html
my parent: ember1
```
### Setting CSS id and class attributes
The HTML `id` attribute can be set on the `{{view}}`'s resulting element with the `id` option.
This option will _not_ be passed to `Ember.View.create`.
``` handlebars
```
Results in the following HTML structure:
``` html
hello.
```
The HTML `class` attribute can be set on the `{{view}}`'s resulting element with
the `class` or `classNameBindings` options. The `class` option
will directly set the CSS `class` attribute and will not be passed to
`Ember.View.create`. `classNameBindings` will be passed to `create` and use
`Ember.View`'s class name binding functionality:
``` handlebars
```
Results in the following HTML structure:
``` html
hello.
```
### Supplying a different view class
`{{view}}` can take an optional first argument before its supplied options to specify a
path to a custom view class.
``` handlebars
```
The first argument can also be a relative path. Ember will search for the view class
starting at the `Ember.View` of the template where `{{view}}` was used as the root object:
``` javascript
MyApp = Ember.Application.create({});
MyApp.OuterView = Ember.View.extend({
innerViewClass: Ember.View.extend({
classNames: ['a-custom-view-class-as-property']
}),
template: Ember.Handlebars.compile('{{#view "innerViewClass"}} hi {{/view}}')
});
MyApp.OuterView.create().appendTo('body');
```
Will result in the following HTML:
``` html
hi
```
### Blockless use
If you supply a custom `Ember.View` subclass that specifies its own template
or provide a `templateName` option to `{{view}}` it can be used without supplying a block.
Attempts to use both a `templateName` option and supply a block will throw an error.
``` handlebars
```
### viewName property
You can supply a `viewName` option to `{{view}}`. The `Ember.View` instance will
be referenced as a property of its parent view by this name.
``` javascript
aView = Ember.View.create({
template: Ember.Handlebars.compile('{{#view viewName="aChildByName"}} hi {{/view}}')
});
aView.appendTo('body');
aView.get('aChildByName') // the instance of Ember.View created by {{view}} helper
```
@method view
@for Ember.Handlebars.helpers
@param {String} path
@param {Hash} options
@return {String} HTML string
*/
EmberHandlebars.registerHelper('view', function(path, options) {
Ember.assert("The view helper only takes a single argument", arguments.length <= 2);
// If no path is provided, treat path param as options.
if (path && path.data && path.data.isRenderData) {
options = path;
path = "Ember.View";
}
return EmberHandlebars.ViewHelper.helper(this, path, options);
});
})();
(function() {
/*globals Handlebars */
// TODO: Don't require all of this module
/**
@module ember
@submodule ember-handlebars
*/
var get = Ember.get, getPath = Ember.Handlebars.getPath, fmt = Ember.String.fmt;
/**
`{{collection}}` is a `Ember.Handlebars` helper for adding instances of
`Ember.CollectionView` to a template. See `Ember.CollectionView` for additional
information on how a `CollectionView` functions.
`{{collection}}`'s primary use is as a block helper with a `contentBinding` option
pointing towards an `Ember.Array`-compatible object. An `Ember.View` instance will
be created for each item in its `content` property. Each view will have its own
`content` property set to the appropriate item in the collection.
The provided block will be applied as the template for each item's view.
Given an empty `` the following template:
``` handlebars
```
And the following application code
``` javascript
App = Ember.Application.create()
App.items = [
Ember.Object.create({name: 'Dave'}),
Ember.Object.create({name: 'Mary'}),
Ember.Object.create({name: 'Sara'})
]
```
Will result in the HTML structure below
``` html
Hi Dave
Hi Mary
Hi Sara
```
### Blockless Use
If you provide an `itemViewClass` option that has its own `template` you can omit
the block.
The following template:
``` handlebars
```
And application code
``` javascript
App = Ember.Application.create();
App.items = [
Ember.Object.create({name: 'Dave'}),
Ember.Object.create({name: 'Mary'}),
Ember.Object.create({name: 'Sara'})
];
App.AnItemView = Ember.View.extend({
template: Ember.Handlebars.compile("Greetings {{view.content.name}}")
});
```
Will result in the HTML structure below
``` html
Greetings Dave
Greetings Mary
Greetings Sara
```
### Specifying a CollectionView subclass
By default the `{{collection}}` helper will create an instance of `Ember.CollectionView`.
You can supply a `Ember.CollectionView` subclass to the helper by passing it
as the first argument:
``` handlebars
```
### Forwarded `item.*`-named Options
As with the `{{view}}`, helper options passed to the `{{collection}}` will be set on
the resulting `Ember.CollectionView` as properties. Additionally, options prefixed with
`item` will be applied to the views rendered for each item (note the camelcasing):
``` handlebars
```
Will result in the following HTML structure:
``` html
Howdy Dave
Howdy Mary
Howdy Sara
```
@method collection
@for Ember.Handlebars.helpers
@param {String} path
@param {Hash} options
@return {String} HTML string
*/
Ember.Handlebars.registerHelper('collection', function(path, options) {
// If no path is provided, treat path param as options.
if (path && path.data && path.data.isRenderData) {
options = path;
path = undefined;
Ember.assert("You cannot pass more than one argument to the collection helper", arguments.length === 1);
} else {
Ember.assert("You cannot pass more than one argument to the collection helper", arguments.length === 2);
}
var fn = options.fn;
var data = options.data;
var inverse = options.inverse;
// If passed a path string, convert that into an object.
// Otherwise, just default to the standard class.
var collectionClass;
collectionClass = path ? getPath(this, path, options) : Ember.CollectionView;
Ember.assert(fmt("%@ #collection: Could not find collection class %@", [data.view, path]), !!collectionClass);
var hash = options.hash, itemHash = {}, match;
// Extract item view class if provided else default to the standard class
var itemViewClass, itemViewPath = hash.itemViewClass;
var collectionPrototype = collectionClass.proto();
delete hash.itemViewClass;
itemViewClass = itemViewPath ? getPath(collectionPrototype, itemViewPath, options) : collectionPrototype.itemViewClass;
Ember.assert(fmt("%@ #collection: Could not find itemViewClass %@", [data.view, itemViewPath]), !!itemViewClass);
// Go through options passed to the {{collection}} helper and extract options
// that configure item views instead of the collection itself.
for (var prop in hash) {
if (hash.hasOwnProperty(prop)) {
match = prop.match(/^item(.)(.*)$/);
if(match) {
// Convert itemShouldFoo -> shouldFoo
itemHash[match[1].toLowerCase() + match[2]] = hash[prop];
// Delete from hash as this will end up getting passed to the
// {{view}} helper method.
delete hash[prop];
}
}
}
var tagName = hash.tagName || collectionPrototype.tagName;
if (fn) {
itemHash.template = fn;
delete options.fn;
}
var emptyViewClass;
if (inverse && inverse !== Handlebars.VM.noop) {
emptyViewClass = get(collectionPrototype, 'emptyViewClass');
emptyViewClass = emptyViewClass.extend({
template: inverse,
tagName: itemHash.tagName
});
} else if (hash.emptyViewClass) {
emptyViewClass = getPath(this, hash.emptyViewClass, options);
}
hash.emptyView = emptyViewClass;
if (hash.eachHelper === 'each') {
itemHash._context = Ember.computed(function() {
return get(this, 'content');
}).property('content');
delete hash.eachHelper;
}
var viewOptions = Ember.Handlebars.ViewHelper.propertiesFromHTMLOptions({ data: data, hash: itemHash }, this);
hash.itemViewClass = itemViewClass.extend(viewOptions);
return Ember.Handlebars.helpers.view.call(this, collectionClass, options);
});
})();
(function() {
/*globals Handlebars */
/**
@module ember
@submodule ember-handlebars
*/
var getPath = Ember.Handlebars.getPath;
/**
`unbound` allows you to output a property without binding. *Important:* The
output will not be updated if the property changes. Use with caution.
``` handlebars
{{unbound somePropertyThatDoesntChange}}
```
@method unbound
@for Ember.Handlebars.helpers
@param {String} property
@return {String} HTML string
*/
Ember.Handlebars.registerHelper('unbound', function(property, fn) {
var context = (fn.contexts && fn.contexts[0]) || this;
return getPath(context, property, fn);
});
})();
(function() {
/*jshint debug:true*/
/**
@module ember
@submodule ember-handlebars
*/
var getPath = Ember.Handlebars.getPath, normalizePath = Ember.Handlebars.normalizePath;
/**
`log` allows you to output the value of a value in the current rendering
context.
``` handlebars
{{log myVariable}}
```
@method log
@for Ember.Handlebars.helpers
@param {String} property
*/
Ember.Handlebars.registerHelper('log', function(property, options) {
var context = (options.contexts && options.contexts[0]) || this,
normalized = normalizePath(context, property, options.data),
pathRoot = normalized.root,
path = normalized.path,
value = (path === 'this') ? pathRoot : getPath(pathRoot, path, options);
Ember.Logger.log(value);
});
/**
The `debugger` helper executes the `debugger` statement in the current
context.
``` handlebars
{{debugger}}
```
@method debugger
@for Ember.Handlebars.helpers
@param {String} property
*/
Ember.Handlebars.registerHelper('debugger', function() {
debugger;
});
})();
(function() {
/**
@module ember
@submodule ember-handlebars
*/
var get = Ember.get, set = Ember.set;
Ember.Handlebars.EachView = Ember.CollectionView.extend(Ember._Metamorph, {
itemViewClass: Ember._MetamorphView,
emptyViewClass: Ember._MetamorphView,
createChildView: function(view, attrs) {
view = this._super(view, attrs);
// At the moment, if a container view subclass wants
// to insert keywords, it is responsible for cloning
// the keywords hash. This will be fixed momentarily.
var keyword = get(this, 'keyword');
if (keyword) {
var data = get(view, 'templateData');
data = Ember.copy(data);
data.keywords = view.cloneKeywords();
set(view, 'templateData', data);
var content = get(view, 'content');
// In this case, we do not bind, because the `content` of
// a #each item cannot change.
data.keywords[keyword] = content;
}
return view;
}
});
/**
The `{{#each}}` helper loops over elements in a collection, rendering its block once for each item:
``` javascript
Developers = [{name: 'Yehuda'},{name: 'Tom'}, {name: 'Paul'}];
```
``` handlebars
{{#each Developers}}
{{name}}
{{/each}}
```
`{{each}}` supports an alternative syntax with element naming:
``` handlebars
{{#each person in Developers}}
{{person.name}}
{{/each}}
```
When looping over objects that do not have properties, `{{this}}` can be used to render the object:
``` javascript
DeveloperNames = ['Yehuda', 'Tom', 'Paul']
```
``` handlebars
{{#each DeveloperNames}}
{{this}}
{{/each}}
```
### Blockless Use
If you provide an `itemViewClass` option that has its own `template` you can omit
the block in a similar way to how it can be done with the collection helper.
The following template:
``` handlebars
```
And application code
``` javascript
App = Ember.Application.create({
MyView: Ember.View.extend({
items: [
Ember.Object.create({name: 'Dave'}),
Ember.Object.create({name: 'Mary'}),
Ember.Object.create({name: 'Sara'})
]
})
});
App.AnItemView = Ember.View.extend({
template: Ember.Handlebars.compile("Greetings {{name}}")
});
App.initialize();
```
Will result in the HTML structure below
``` html
Greetings Dave
Greetings Mary
Greetings Sara
```
@method each
@for Ember.Handlebars.helpers
@param [name] {String} name for item (used with `in`)
@param path {String} path
*/
Ember.Handlebars.registerHelper('each', function(path, options) {
if (arguments.length === 4) {
Ember.assert("If you pass more than one argument to the each helper, it must be in the form #each foo in bar", arguments[1] === "in");
var keywordName = arguments[0];
options = arguments[3];
path = arguments[2];
if (path === '') { path = "this"; }
options.hash.keyword = keywordName;
} else {
options.hash.eachHelper = 'each';
}
options.hash.contentBinding = path;
// Set up emptyView as a metamorph with no tag
//options.hash.emptyViewClass = Ember._MetamorphView;
return Ember.Handlebars.helpers.collection.call(this, 'Ember.Handlebars.EachView', options);
});
})();
(function() {
/**
@module ember
@submodule ember-handlebars
*/
/**
`template` allows you to render a template from inside another template.
This allows you to re-use the same template in multiple places. For example:
``` handlebars
```
This helper looks for templates in the global Ember.TEMPLATES hash. If you
add <script> tags to your page with the `data-template-name` attribute set,
they will be compiled and placed in this hash automatically.
You can also manually register templates by adding them to the hash:
``` javascript
Ember.TEMPLATES["my_cool_template"] = Ember.Handlebars.compile('{{user}}');
```
@method template
@for Ember.Handlebars.helpers
@param {String} templateName the template to render
*/
Ember.Handlebars.registerHelper('template', function(name, options) {
var template = Ember.TEMPLATES[name];
Ember.assert("Unable to find template with name '"+name+"'.", !!template);
Ember.TEMPLATES[name](this, { data: options.data });
});
})();
(function() {
/**
@module ember
@submodule ember-handlebars
*/
var EmberHandlebars = Ember.Handlebars,
getPath = EmberHandlebars.getPath,
get = Ember.get,
a_slice = Array.prototype.slice;
var ActionHelper = EmberHandlebars.ActionHelper = {
registeredActions: {}
};
ActionHelper.registerAction = function(actionName, options) {
var actionId = (++Ember.$.uuid).toString();
ActionHelper.registeredActions[actionId] = {
eventName: options.eventName,
handler: function(event) {
var modifier = event.shiftKey || event.metaKey || event.altKey || event.ctrlKey,
secondaryClick = event.which > 1, // IE9 may return undefined
nonStandard = modifier || secondaryClick;
if (options.link && nonStandard) {
// Allow the browser to handle special link clicks normally
return;
}
event.preventDefault();
event.view = options.view;
if (options.hasOwnProperty('context')) {
event.context = options.context;
}
if (options.hasOwnProperty('contexts')) {
event.contexts = options.contexts;
}
var target = options.target;
// Check for StateManager (or compatible object)
if (target.isState && typeof target.send === 'function') {
return target.send(actionName, event);
} else {
Ember.assert(Ember.String.fmt('Target %@ does not have action %@', [target, actionName]), target[actionName]);
return target[actionName].call(target, event);
}
}
};
options.view.on('willClearRender', function() {
delete ActionHelper.registeredActions[actionId];
});
return actionId;
};
/**
The `{{action}}` helper registers an HTML element within a template for
DOM event handling and forwards that interaction to the Application's router,
the template's `Ember.View` instance, or supplied `target` option (see 'Specifying a Target').
User interaction with that element will invoke the supplied action name on
the appropriate target.
Given the following Handlebars template on the page
``` handlebars
```
And application code
``` javascript
AView = Ember.View.extend({
templateName; 'a-template',
anActionName: function(event){}
});
aView = AView.create();
aView.appendTo('body');
```
Will results in the following rendered HTML
``` html
click me
```
Clicking "click me" will trigger the `anActionName` method of the `aView`
object with a `jQuery.Event` object as its argument. The `jQuery.Event`
object will be extended to include a `view` property that is set to the
original view interacted with (in this case the `aView` object).
### Event Propagation
Events triggered through the action helper will automatically have
`.preventDefault()` called on them. You do not need to do so in your event
handlers. To stop propagation of the event, simply return `false` from your
handler.
If you need the default handler to trigger you should either register your
own event handler, or use event methods on your view class. See Ember.View
'Responding to Browser Events' for more information.
### Specifying DOM event type
By default the `{{action}}` helper registers for DOM `click` events. You can
supply an `on` option to the helper to specify a different DOM event name:
``` handlebars
```
See Ember.View 'Responding to Browser Events' for a list of
acceptable DOM event names.
Because `{{action}}` depends on Ember's event dispatch system it will only
function if an `Ember.EventDispatcher` instance is available. An
`Ember.EventDispatcher` instance will be created when a new
`Ember.Application` is created. Having an instance of `Ember.Application`
will satisfy this requirement.
### Specifying a Target
There are several possible target objects for `{{action}}` helpers:
In a typical `Ember.Router`-backed Application where views are managed
through use of the `{{outlet}}` helper, actions will be forwarded to the
current state of the Applications's Router. See Ember.Router 'Responding
to User-initiated Events' for more information.
If you manually set the `target` property on the controller of a template's
`Ember.View` instance, the specifed `controller.target` will become the target
for any actions. Likely custom values for a controller's `target` are the
controller itself or a StateManager other than the Application's Router.
If the templates's view lacks a controller property the view itself is the target.
Finally, a `target` option can be provided to the helper to change which object
will receive the method call. This option must be a string representing a
path to an object:
``` handlebars
```
Clicking "click me" in the rendered HTML of the above template will trigger
the `anActionName` method of the object at `MyApplication.someObject`.
The first argument to this method will be a `jQuery.Event` extended to
include a `view` property that is set to the original view interacted with.
A path relative to the template's `Ember.View` instance can also be used as
a target:
``` handlebars
```
Clicking "click me" in the rendered HTML of the above template will trigger
the `anActionName` method of the view's parent view.
The `{{action}}` helper is `Ember.StateManager` aware. If the target of the
action is an `Ember.StateManager` instance `{{action}}` will use the `send`
functionality of StateManagers. The documentation for `Ember.StateManager`
has additional information about this use.
If an action's target does not implement a method that matches the supplied
action name an error will be thrown.
``` handlebars
```
With the following application code
``` javascript
AView = Ember.View.extend({
templateName; 'a-template',
// note: no method 'aMethodNameThatIsMissing'
anActionName: function(event){}
});
aView = AView.create();
aView.appendTo('body');
```
Will throw `Uncaught TypeError: Cannot call method 'call' of undefined` when
"click me" is clicked.
### Specifying a context
By default the `{{action}}` helper passes the current Handlebars context
along in the `jQuery.Event` object. You may specify an alternate object to
pass as the context by providing a property path:
``` handlebars
```
@method action
@for Ember.Handlebars.helpers
@param {String} actionName
@param {Object...} contexts
@param {Hash} options
*/
EmberHandlebars.registerHelper('action', function(actionName) {
var options = arguments[arguments.length - 1],
contexts = a_slice.call(arguments, 1, -1);
var hash = options.hash,
view = options.data.view,
target, controller, link;
// create a hash to pass along to registerAction
var action = {
eventName: hash.on || "click"
};
action.view = view = get(view, 'concreteView');
if (hash.target) {
target = getPath(this, hash.target, options);
} else if (controller = options.data.keywords.controller) {
target = get(controller, 'target');
}
action.target = target = target || view;
if (contexts.length) {
action.contexts = contexts = Ember.EnumerableUtils.map(contexts, function(context) {
return getPath(this, context, options);
}, this);
action.context = contexts[0];
}
var output = [], url;
if (hash.href && target.urlForEvent) {
url = target.urlForEvent.apply(target, [actionName].concat(contexts));
output.push('href="' + url + '"');
action.link = true;
}
var actionId = ActionHelper.registerAction(actionName, action);
output.push('data-ember-action="' + actionId + '"');
return new EmberHandlebars.SafeString(output.join(" "));
});
})();
(function() {
/**
@module ember
@submodule ember-handlebars
*/
var get = Ember.get, set = Ember.set;
/**
When used in a Handlebars template that is assigned to an `Ember.View` instance's
`layout` property Ember will render the layout template first, inserting the view's
own rendered output at the `{{ yield }}` location.
An empty `` and the following application code:
``` javascript
AView = Ember.View.extend({
classNames: ['a-view-with-layout'],
layout: Ember.Handlebars.compile('
{{ yield }}
'),
template: Ember.Handlebars.compile('I am wrapped')
});
aView = AView.create();
aView.appendTo('body');
```
Will result in the following HTML output:
``` html
I am wrapped
```
The yield helper cannot be used outside of a template assigned to an `Ember.View`'s `layout` property
and will throw an error if attempted.
``` javascript
BView = Ember.View.extend({
classNames: ['a-view-with-layout'],
template: Ember.Handlebars.compile('{{yield}}')
});
bView = BView.create();
bView.appendTo('body');
// throws
// Uncaught Error: assertion failed: You called yield in a template that was not a layout
```
@method yield
@for Ember.Handlebars.helpers
@param {Hash} options
@return {String} HTML string
*/
Ember.Handlebars.registerHelper('yield', function(options) {
var view = options.data.view, template;
while (view && !get(view, 'layout')) {
view = get(view, 'parentView');
}
Ember.assert("You called yield in a template that was not a layout", !!view);
template = get(view, 'template');
if (template) { template(this, options); }
});
})();
(function() {
/**
@module ember
@submodule ember-handlebars
*/
Ember.Handlebars.OutletView = Ember.ContainerView.extend(Ember._Metamorph);
/**
The `outlet` helper allows you to specify that the current
view's controller will fill in the view for a given area.
``` handlebars
{{outlet}}
```
By default, when the the current controller's `view` property changes, the
outlet will replace its current view with the new view. You can set the
`view` property directly, but it's normally best to use `connectOutlet`.
``` javascript
# Instantiate App.PostsView and assign to `view`, so as to render into outlet.
controller.connectOutlet('posts');
```
You can also specify a particular name other than `view`:
``` handlebars
{{outlet masterView}}
{{outlet detailView}}
```
Then, you can control several outlets from a single controller.
``` javascript
# Instantiate App.PostsView and assign to controller.masterView.
controller.connectOutlet('masterView', 'posts');
# Also, instantiate App.PostInfoView and assign to controller.detailView.
controller.connectOutlet('detailView', 'postInfo');
```
@method outlet
@for Ember.Handlebars.helpers
@param {String} property the property on the controller
that holds the view for this outlet
*/
Ember.Handlebars.registerHelper('outlet', function(property, options) {
if (property && property.data && property.data.isRenderData) {
options = property;
property = 'view';
}
options.hash.currentViewBinding = "view.context." + property;
return Ember.Handlebars.helpers.view.call(this, Ember.Handlebars.OutletView, options);
});
})();
(function() {
})();
(function() {
})();
(function() {
/**
@module ember
@submodule ember-handlebars
*/
var set = Ember.set, get = Ember.get;
/**
The `Ember.Checkbox` view class renders a checkbox [input](https://developer.mozilla.org/en/HTML/Element/Input)
element. It allows for binding an Ember property (`checked`) to the status of the checkbox.
Example:
``` handlebars
{{view Ember.Checkbox checkedBinding="receiveEmail"}}
```
You can add a `label` tag yourself in the template where the Ember.Checkbox is being used.
``` html
```
The `checked` attribute of an Ember.Checkbox object should always be set
through the Ember object or by interacting with its rendered element representation
via the mouse, keyboard, or touch. Updating the value of the checkbox via jQuery will
result in the checked value of the object and its element losing synchronization.
## Layout and LayoutName properties
Because HTML `input` elements are self closing `layout` and `layoutName` properties will
not be applied. See `Ember.View`'s layout section for more information.
@class Checkbox
@namespace Ember
@extends Ember.View
*/
Ember.Checkbox = Ember.View.extend({
classNames: ['ember-checkbox'],
tagName: 'input',
attributeBindings: ['type', 'checked', 'disabled', 'tabindex'],
type: "checkbox",
checked: false,
disabled: false,
init: function() {
this._super();
this.on("change", this, this._updateElementValue);
},
_updateElementValue: function() {
set(this, 'checked', this.$().prop('checked'));
}
});
})();
(function() {
/**
@module ember
@submodule ember-handlebars
*/
var get = Ember.get, set = Ember.set;
/**
Shared mixin used by Ember.TextField and Ember.TextArea.
@class TextSupport
@namespace Ember
@extends Ember.Mixin
@private
*/
Ember.TextSupport = Ember.Mixin.create({
value: "",
attributeBindings: ['placeholder', 'disabled', 'maxlength', 'tabindex'],
placeholder: null,
disabled: false,
maxlength: null,
insertNewline: Ember.K,
cancel: Ember.K,
init: function() {
this._super();
this.on("focusOut", this, this._elementValueDidChange);
this.on("change", this, this._elementValueDidChange);
this.on("keyUp", this, this.interpretKeyEvents);
},
interpretKeyEvents: function(event) {
var map = Ember.TextSupport.KEY_EVENTS;
var method = map[event.keyCode];
this._elementValueDidChange();
if (method) { return this[method](event); }
},
_elementValueDidChange: function() {
set(this, 'value', this.$().val());
}
});
Ember.TextSupport.KEY_EVENTS = {
13: 'insertNewline',
27: 'cancel'
};
})();
(function() {
/**
@module ember
@submodule ember-handlebars
*/
var get = Ember.get, set = Ember.set;
/**
The `Ember.TextField` view class renders a text
[input](https://developer.mozilla.org/en/HTML/Element/Input) element. It
allows for binding Ember properties to the text field contents (`value`),
live-updating as the user inputs text.
Example:
``` handlebars
{{view Ember.TextField valueBinding="firstName"}}
```
## Layout and LayoutName properties
Because HTML `input` elements are self closing `layout` and `layoutName` properties will
not be applied. See `Ember.View`'s layout section for more information.
## HTML Attributes
By default `Ember.TextField` provides support for `type`, `value`, `size`, `placeholder`,
`disabled`, `maxlength` and `tabindex` attributes on a textarea. If you need to support
more attributes have a look at the `attributeBindings` property in `Ember.View`'s
HTML Attributes section.
To globally add support for additional attributes you can reopen `Ember.TextField` or
`Ember.TextSupport`.
``` javascript
Ember.TextSupport.reopen({
attributeBindings: ["required"]
})
```
@class TextField
@namespace Ember
@extends Ember.View
@uses Ember.TextSupport
*/
Ember.TextField = Ember.View.extend(Ember.TextSupport,
/** @scope Ember.TextField.prototype */ {
classNames: ['ember-text-field'],
tagName: "input",
attributeBindings: ['type', 'value', 'size'],
/**
The value attribute of the input element. As the user inputs text, this
property is updated live.
@property value
@type String
@default ""
*/
value: "",
/**
The type attribute of the input element.
@property type
@type String
@default "text"
*/
type: "text",
/**
The size of the text field in characters.
@property size
@type String
@default null
*/
size: null
});
})();
(function() {
/**
@module ember
@submodule ember-handlebars
*/
var get = Ember.get, set = Ember.set;
/**
@class Button
@namespace Ember
@extends Ember.View
@uses Ember.TargetActionSupport
@deprecated
*/
Ember.Button = Ember.View.extend(Ember.TargetActionSupport, {
classNames: ['ember-button'],
classNameBindings: ['isActive'],
tagName: 'button',
propagateEvents: false,
attributeBindings: ['type', 'disabled', 'href', 'tabindex'],
/**
@private
Overrides TargetActionSupport's targetObject computed
property to use Handlebars-specific path resolution.
@property targetObject
*/
targetObject: Ember.computed(function() {
var target = get(this, 'target'),
root = get(this, 'context'),
data = get(this, 'templateData');
if (typeof target !== 'string') { return target; }
return Ember.Handlebars.getPath(root, target, { data: data });
}).property('target'),
// Defaults to 'button' if tagName is 'input' or 'button'
type: Ember.computed(function(key, value) {
var tagName = this.get('tagName');
if (value !== undefined) { this._type = value; }
if (this._type !== undefined) { return this._type; }
if (tagName === 'input' || tagName === 'button') { return 'button'; }
}).property('tagName'),
disabled: false,
// Allow 'a' tags to act like buttons
href: Ember.computed(function() {
return this.get('tagName') === 'a' ? '#' : null;
}).property('tagName'),
mouseDown: function() {
if (!get(this, 'disabled')) {
set(this, 'isActive', true);
this._mouseDown = true;
this._mouseEntered = true;
}
return get(this, 'propagateEvents');
},
mouseLeave: function() {
if (this._mouseDown) {
set(this, 'isActive', false);
this._mouseEntered = false;
}
},
mouseEnter: function() {
if (this._mouseDown) {
set(this, 'isActive', true);
this._mouseEntered = true;
}
},
mouseUp: function(event) {
if (get(this, 'isActive')) {
// Actually invoke the button's target and action.
// This method comes from the Ember.TargetActionSupport mixin.
this.triggerAction();
set(this, 'isActive', false);
}
this._mouseDown = false;
this._mouseEntered = false;
return get(this, 'propagateEvents');
},
keyDown: function(event) {
// Handle space or enter
if (event.keyCode === 13 || event.keyCode === 32) {
this.mouseDown();
}
},
keyUp: function(event) {
// Handle space or enter
if (event.keyCode === 13 || event.keyCode === 32) {
this.mouseUp();
}
},
// TODO: Handle proper touch behavior. Including should make inactive when
// finger moves more than 20x outside of the edge of the button (vs mouse
// which goes inactive as soon as mouse goes out of edges.)
touchStart: function(touch) {
return this.mouseDown(touch);
},
touchEnd: function(touch) {
return this.mouseUp(touch);
},
init: function() {
Ember.deprecate("Ember.Button is deprecated and will be removed from future releases. Consider using the `{{action}}` helper.");
this._super();
}
});
})();
(function() {
/**
@module ember
@submodule ember-handlebars
*/
var get = Ember.get, set = Ember.set;
/**
The `Ember.TextArea` view class renders a
[textarea](https://developer.mozilla.org/en/HTML/Element/textarea) element.
It allows for binding Ember properties to the text area contents (`value`),
live-updating as the user inputs text.
## Layout and LayoutName properties
Because HTML `textarea` elements do not contain inner HTML the `layout` and `layoutName`
properties will not be applied. See `Ember.View`'s layout section for more information.
## HTML Attributes
By default `Ember.TextArea` provides support for `rows`, `cols`, `placeholder`, `disabled`,
`maxlength` and `tabindex` attributes on a textarea. If you need to support more
attributes have a look at the `attributeBindings` property in `Ember.View`'s HTML Attributes section.
To globally add support for additional attributes you can reopen `Ember.TextArea` or `Ember.TextSupport`.
``` javascript
Ember.TextSupport.reopen({
attributeBindings: ["required"]
})
```
@class TextArea
@namespace Ember
@extends Ember.View
@uses Ember.TextSupport
*/
Ember.TextArea = Ember.View.extend(Ember.TextSupport, {
classNames: ['ember-text-area'],
tagName: "textarea",
attributeBindings: ['rows', 'cols'],
rows: null,
cols: null,
_updateElementValue: Ember.observer(function() {
// We do this check so cursor position doesn't get affected in IE
var value = get(this, 'value'),
$el = this.$();
if ($el && value !== $el.val()) {
$el.val(value);
}
}, 'value'),
init: function() {
this._super();
this.on("didInsertElement", this, this._updateElementValue);
}
});
})();
(function() {
/**
@module ember
@submodule ember-handlebars
*/
/**
@class TabContainerView
@namespace Ember
@deprecated
@extends Ember.View
*/
Ember.TabContainerView = Ember.View.extend({
init: function() {
Ember.deprecate("Ember.TabContainerView is deprecated and will be removed from future releases.");
this._super();
}
});
})();
(function() {
/**
@module ember
@submodule ember-handlebars
*/
var get = Ember.get;
/**
@class TabPaneView
@namespace Ember
@extends Ember.View
@deprecated
*/
Ember.TabPaneView = Ember.View.extend({
tabsContainer: Ember.computed(function() {
return this.nearestOfType(Ember.TabContainerView);
}).property().volatile(),
isVisible: Ember.computed(function() {
return get(this, 'viewName') === get(this, 'tabsContainer.currentView');
}).property('tabsContainer.currentView').volatile(),
init: function() {
Ember.deprecate("Ember.TabPaneView is deprecated and will be removed from future releases.");
this._super();
}
});
})();
(function() {
/**
@module ember
@submodule ember-handlebars
*/
var get = Ember.get, setPath = Ember.setPath;
/**
@class TabView
@namespace Ember
@extends Ember.View
@deprecated
*/
Ember.TabView = Ember.View.extend({
tabsContainer: Ember.computed(function() {
return this.nearestInstanceOf(Ember.TabContainerView);
}).property().volatile(),
mouseUp: function() {
setPath(this, 'tabsContainer.currentView', get(this, 'value'));
},
init: function() {
Ember.deprecate("Ember.TabView is deprecated and will be removed from future releases.");
this._super();
}
});
})();
(function() {
})();
(function() {
/*jshint eqeqeq:false */
/**
@module ember
@submodule ember-handlebars
*/
var set = Ember.set,
get = Ember.get,
indexOf = Ember.EnumerableUtils.indexOf,
indexesOf = Ember.EnumerableUtils.indexesOf,
replace = Ember.EnumerableUtils.replace,
isArray = Ember.isArray;
/**
The Ember.Select view class renders a
[select](https://developer.mozilla.org/en/HTML/Element/select) HTML element,
allowing the user to choose from a list of options.
The text and `value` property of each `