diff --git a/perf/todomvc-benchmark/resources/tests.js b/perf/todomvc-benchmark/resources/tests.js index 672f9bf986..cf3f235008 100644 --- a/perf/todomvc-benchmark/resources/tests.js +++ b/perf/todomvc-benchmark/resources/tests.js @@ -96,47 +96,50 @@ Suites.push({ ] }); + Suites.push({ - name: 'Ember', + name: 'EmberJS-TodoMVC', url: 'todomvc/architecture-examples/emberjs/index.html', - version: '1.3.1 + Handlebars 1.3.0', prepare: function (runner, contentWindow, contentDocument) { - contentWindow.Todos.Store = contentWindow.DS.Store.extend({ - revision: 12, - adapter: 'Todos.LSAdapter', - commit: function () { } - }); - return runner.waitForElement('#new-todo').then(function (element) { element.focus(); return { views: contentWindow.Ember.View.views, emberRun: contentWindow.Ember.run, - } + }; }); }, tests: [ new BenchmarkTestStep('Adding' + numberOfItemsToAdd + 'Items', function (params) { - for (var i = 0; i < numberOfItemsToAdd; i++) { - params.emberRun(function () { params.views["new-todo"].set('value', 'Something to do' + i); }); - params.emberRun(function () { params.views["new-todo"].insertNewline(document.createEvent('Event')); }); - } + params.emberRun(function () { + for (var i = 0; i < numberOfItemsToAdd; i++) { + params.views["new-todo"].set('value', 'Something to do' + i); + params.emberRun.sync(); // force binding propogation + params.views["new-todo"].triggerAction("createTodo"); + } + }); }), new BenchmarkTestStep('CompletingAllItems', function (params, contentWindow, contentDocument) { var checkboxes = contentDocument.querySelectorAll('.ember-checkbox'); - for (var i = 0; i < checkboxes.length; i++) { - var view = params.views[checkboxes[i].id]; - params.emberRun(function () { view.set('checked', true); }); - } + params.emberRun(function () { + for (var i = 0; i < checkboxes.length; i++) { + var view = params.views[checkboxes[i].id]; + view.set('checked', true); + } + }); }), new BenchmarkTestStep('DeletingItems', function (params, contentWindow, contentDocument) { var deleteButtons = contentDocument.querySelectorAll('.destroy'); - for (var i = 0; i < deleteButtons.length; i++) - params.emberRun(function () { deleteButtons[i].click(); }); + params.emberRun(function () { + for (var i = 0; i < deleteButtons.length; i++) + deleteButtons[i].click(); + }); }), ] }); + + Suites.push({ name: 'Angular', url: 'todomvc/architecture-examples/angularjs-perf/index.html', diff --git a/perf/todomvc-benchmark/todomvc/architecture-examples/emberjs/bower_components/ember-data/ember-data.min.js b/perf/todomvc-benchmark/todomvc/architecture-examples/emberjs/bower_components/ember-data/ember-data.min.js new file mode 100644 index 0000000000..310ff4c1ce --- /dev/null +++ b/perf/todomvc-benchmark/todomvc/architecture-examples/emberjs/bower_components/ember-data/ember-data.min.js @@ -0,0 +1,10 @@ +/*! + * @overview Ember Data + * @copyright Copyright 2011-2014 Tilde Inc. and contributors. + * Portions Copyright 2011 LivingSocial Inc. + * @license Licensed under MIT license (see license.js) + * @version 1.0.0-beta.7+canary.2ee1b58c + */ +!function(a){var b,c,d,e;!function(){var a={},f={};b=function(b,c,d){a[b]={deps:c,callback:d}},e=d=c=function(b){function d(a){if("."!==a.charAt(0))return a;for(var c=a.split("/"),d=b.split("/").slice(0,-1),e=0,f=c.length;f>e;e++){var g=c[e];if(".."===g)d.pop();else{if("."===g)continue;d.push(g)}}return d.join("/")}if(e._eak_seen=a,f[b])return f[b];if(f[b]={},!a[b])throw new Error("Could not find module "+b);for(var g,h=a[b],i=h.deps,j=h.callback,k=[],l=0,m=i.length;m>l;l++)k.push("exports"===i[l]?g={}:c(d(i[l])));var n=j.apply(this,k);return f[b]=g||n}}(),b("activemodel-adapter/lib/initializers",["../../ember-data/lib/system/container_proxy","./system/active_model_serializer","./system/active_model_adapter"],function(a,b,c){"use strict";var d=a["default"],e=b["default"],f=c["default"];Ember.onLoad("Ember.Application",function(a){a.initializer({name:"activeModelAdapter",initialize:function(a,b){var c=new d(a);c.registerDeprecations([{deprecated:"serializer:_ams",valid:"serializer:-active-model"},{deprecated:"adapter:_ams",valid:"adapter:-active-model"}]),b.register("serializer:-active-model",e),b.register("adapter:-active-model",f)}})})}),b("activemodel-adapter/lib/main",["./system","./initializers","exports"],function(a,b,c){"use strict";var d=a.ActiveModelAdapter,e=a.ActiveModelSerializer,f=a.EmbeddedRecordsMixin;c.ActiveModelAdapter=d,c.ActiveModelSerializer=e,c.EmbeddedRecordsMixin=f}),b("activemodel-adapter/lib/system",["./system/embedded_records_mixin","./system/active_model_adapter","./system/active_model_serializer","exports"],function(a,b,c,d){"use strict";var e=a["default"],f=b["default"],g=c["default"];d.EmbeddedRecordsMixin=e,d.ActiveModelAdapter=f,d.ActiveModelSerializer=g}),b("activemodel-adapter/lib/system/active_model_adapter",["../../../ember-data/lib/adapters","../../../ember-data/lib/system/adapter","../../../ember-inflector/lib/main","./active_model_serializer","./embedded_records_mixin","exports"],function(a,b,c,d,e,f){"use strict";var g=a.RESTAdapter,h=b.InvalidError,i=c.pluralize,j=(d["default"],e["default"],Ember.EnumerableUtils.forEach),k=Ember.String.decamelize,l=Ember.String.underscore,m=g.extend({defaultSerializer:"-active-model",pathForType:function(a){var b=k(a),c=l(b);return i(c)},ajaxError:function(a){var b=this._super(a);if(a&&422===a.status){var c=Ember.$.parseJSON(a.responseText),d={};if(void 0!==c.errors){var e=c.errors;j(Ember.keys(e),function(a){d[Ember.String.camelize(a)]=e[a]})}return new h(d)}return b}});f["default"]=m}),b("activemodel-adapter/lib/system/active_model_serializer",["../../../ember-inflector/lib/main","../../../ember-data/lib/serializers/rest_serializer","exports"],function(a,b,c){"use strict";var d=a.singularize,e=b["default"],f=Ember.get,g=Ember.EnumerableUtils.forEach,h=Ember.String.camelize,i=Ember.String.capitalize,j=Ember.String.decamelize,k=Ember.String.underscore,l=e.extend({keyForAttribute:function(a){return j(a)},keyForRelationship:function(a,b){return a=j(a),"belongsTo"===b?a+"_id":"hasMany"===b?d(a)+"_ids":a},serializeHasMany:Ember.K,serializeIntoHash:function(a,b,c,d){var e=k(j(b.typeKey));a[e]=this.serialize(c,d)},serializePolymorphicType:function(a,b,c){var d=c.key,e=f(a,d);d=this.keyForAttribute(d),b[d+"_type"]=i(h(e.constructor.typeKey))},typeForRoot:function(a){var b=h(a);return d(b)},normalize:function(a,b,c){return this.normalizeLinks(b),this._super(a,b,c)},normalizeLinks:function(a){if(a.links){var b=a.links;for(var c in b){var d=h(c);d!==c&&(b[d]=b[c],delete b[c])}}},normalizeRelationships:function(a,b){var c,d;this.keyForRelationship&&a.eachRelationship(function(a,e){if(e.options.polymorphic){if(c=this.keyForAttribute(a),d=b[c],d&&d.type)d.type=this.typeForRoot(d.type);else if(d&&"hasMany"===e.kind){var f=this;g(d,function(a){a.type=f.typeForRoot(a.type)})}}else c=this.keyForRelationship(a,e.kind),d=b[c];b[a]=d,a!==c&&delete b[c]},this)}});c["default"]=l}),b("activemodel-adapter/lib/system/embedded_records_mixin",["../../../ember-inflector/lib/main","exports"],function(a,b){"use strict";function c(a,b,f,g,h){var i=d(b,"attrs");i&&f.eachRelationship(function(b,f){var j,k,l,m,n=i[b],o=a.serializerFor(f.type.typeKey),p=d(o,"primaryKey");if("hasMany"===f.kind&&n&&("always"===n.embedded||"load"===n.embedded)){if(k="_"+Ember.String.pluralize(f.type.typeKey),j=this.keyForRelationship(b,f.kind),l=this.keyForAttribute(b),m=[],!g[l])return;h[k]=h[k]||[],e(g[l],function(b){var d=a.modelFor(f.type.typeKey);c(a,o,d,b,h),m.push(b[p]),h[k].push(b)}),g[j]=m,delete g[l]}},b)}var d=Ember.get,e=Ember.EnumerableUtils.forEach,f=a.pluralize,g=Ember.Mixin.create({serializeHasMany:function(a,b,c){var e=c.key,f=d(this,"attrs"),g=f&&f[e]&&"always"===f[e].embedded;g&&(b[this.keyForAttribute(e)]=d(a,e).map(function(a){var b=a.serialize(),c=d(this,"primaryKey");return b[c]=d(a,c),b},this))},extractSingle:function(a,b,d,e,f){var g=this.keyForAttribute(b.typeKey),h=d[g];return c(a,this,b,h,d),this._super(a,b,d,e,f)},extractArray:function(a,b,d){var g=this.keyForAttribute(b.typeKey),h=d[f(g)];return e(h,function(e){c(a,this,b,e,d)},this),this._super(a,b,d)}});b["default"]=g}),b("ember-data/lib/adapters",["./adapters/fixture_adapter","./adapters/rest_adapter","exports"],function(a,b,c){"use strict";var d=a["default"],e=b["default"];c.RESTAdapter=e,c.FixtureAdapter=d}),b("ember-data/lib/adapters/fixture_adapter",["../system/adapter","exports"],function(a,b){"use strict";var c=Ember.get,d=Ember.String.fmt,e=Ember.EnumerableUtils.indexOf,f=0,g=a["default"],h=g.extend({serializer:null,simulateRemoteResponse:!0,latency:50,fixturesForType:function(a){if(a.FIXTURES){var b=Ember.A(a.FIXTURES);return b.map(function(a){var b=typeof a.id;if("number"!==b&&"string"!==b)throw new Error(d("the id property must be defined as a number or string for fixture %@",[a]));return a.id=a.id+"",a})}return null},queryFixtures:function(){},updateFixtures:function(a,b){a.FIXTURES||(a.FIXTURES=[]);var c=a.FIXTURES;this.deleteLoadedFixture(a,b),c.push(b)},mockJSON:function(a,b,c){return a.serializerFor(b).serialize(c,{includeId:!0})},generateIdForRecord:function(){return"fixture-"+f++},find:function(a,b,c){var d,e=this.fixturesForType(b);return e&&(d=Ember.A(e).findProperty("id",c)),d?this.simulateRemoteCall(function(){return d},this):void 0},findMany:function(a,b,c){var d=this.fixturesForType(b);return d&&(d=d.filter(function(a){return-1!==e(c,a.id)})),d?this.simulateRemoteCall(function(){return d},this):void 0},findAll:function(a,b){var c=this.fixturesForType(b);return this.simulateRemoteCall(function(){return c},this)},findQuery:function(a,b,c){var d=this.fixturesForType(b);return d=this.queryFixtures(d,c,b),d?this.simulateRemoteCall(function(){return d},this):void 0},createRecord:function(a,b,c){var d=this.mockJSON(a,b,c);return this.updateFixtures(b,d),this.simulateRemoteCall(function(){return d},this)},updateRecord:function(a,b,c){var d=this.mockJSON(a,b,c);return this.updateFixtures(b,d),this.simulateRemoteCall(function(){return d},this)},deleteRecord:function(a,b,c){var d=this.mockJSON(a,b,c);return this.deleteLoadedFixture(b,d),this.simulateRemoteCall(function(){return null})},deleteLoadedFixture:function(a,b){var c=this.findExistingFixture(a,b);if(c){var d=e(a.FIXTURES,c);return a.FIXTURES.splice(d,1),!0}},findExistingFixture:function(a,b){var d=this.fixturesForType(a),e=c(b,"id");return this.findFixtureById(d,e)},findFixtureById:function(a,b){return Ember.A(a).find(function(a){return""+c(a,"id")==""+b?!0:!1})},simulateRemoteCall:function(a,b){var d=this;return new Ember.RSVP.Promise(function(e){c(d,"simulateRemoteResponse")?Ember.run.later(function(){e(a.call(b))},c(d,"latency")):Ember.run.schedule("actions",null,function(){e(a.call(b))})},"DS: FixtureAdapter#simulateRemoteCall")}});b["default"]=h}),b("ember-data/lib/adapters/rest_adapter",["../system/adapter","exports"],function(a,b){"use strict";var c=a["default"],d=Ember.get,e=(Ember.set,Ember.ArrayPolyfills.forEach),f=c.extend({defaultSerializer:"-rest",find:function(a,b,c){return this.ajax(this.buildURL(b.typeKey,c),"GET")},findAll:function(a,b,c){var d;return c&&(d={since:c}),this.ajax(this.buildURL(b.typeKey),"GET",{data:d})},findQuery:function(a,b,c){return this.ajax(this.buildURL(b.typeKey),"GET",{data:c})},findMany:function(a,b,c){return this.ajax(this.buildURL(b.typeKey),"GET",{data:{ids:c}})},findHasMany:function(a,b,c){var e=d(this,"host"),f=d(b,"id"),g=b.constructor.typeKey;return e&&"/"===c.charAt(0)&&"/"!==c.charAt(1)&&(c=e+c),this.ajax(this.urlPrefix(c,this.buildURL(g,f)),"GET")},findBelongsTo:function(a,b,c){var e=d(b,"id"),f=b.constructor.typeKey;return this.ajax(this.urlPrefix(c,this.buildURL(f,e)),"GET")},createRecord:function(a,b,c){var d={},e=a.serializerFor(b.typeKey);return e.serializeIntoHash(d,b,c,{includeId:!0}),this.ajax(this.buildURL(b.typeKey),"POST",{data:d})},updateRecord:function(a,b,c){var e={},f=a.serializerFor(b.typeKey);f.serializeIntoHash(e,b,c);var g=d(c,"id");return this.ajax(this.buildURL(b.typeKey,g),"PUT",{data:e})},deleteRecord:function(a,b,c){var e=d(c,"id");return this.ajax(this.buildURL(b.typeKey,e),"DELETE")},buildURL:function(a,b){var c=[],e=d(this,"host"),f=this.urlPrefix();return a&&c.push(this.pathForType(a)),b&&c.push(b),f&&c.unshift(f),c=c.join("/"),!e&&c&&(c="/"+c),c},urlPrefix:function(a,b){var c=d(this,"host"),e=d(this,"namespace"),f=[];return a?"/"===a.charAt(0)?c&&(a=a.slice(1),f.push(c)):/^http(s)?:\/\//.test(a)||f.push(b):(c&&f.push(c),e&&f.push(e)),a&&f.push(a),f.join("/")},pathForType:function(a){var b=Ember.String.camelize(a);return Ember.String.pluralize(b)},ajaxError:function(a){return a&&(a.then=null),a},ajax:function(a,b,c){var d=this;return new Ember.RSVP.Promise(function(e,f){c=d.ajaxOptions(a,b,c),c.success=function(a){Ember.run(null,e,a)},c.error=function(a){Ember.run(null,f,d.ajaxError(a))},Ember.$.ajax(c)},"DS: RestAdapter#ajax "+b+" to "+a)},ajaxOptions:function(a,b,c){if(c=c||{},c.url=a,c.type=b,c.dataType="json",c.context=this,c.data&&"GET"!==b&&(c.contentType="application/json; charset=utf-8",c.data=JSON.stringify(c.data)),void 0!==this.headers){var d=this.headers;c.beforeSend=function(a){e.call(Ember.keys(d),function(b){a.setRequestHeader(b,d[b])})}}return c}});b["default"]=f}),b("ember-data/lib/core",["exports"],function(a){"use strict";var b;"undefined"==typeof b&&(b=Ember.Namespace.create({VERSION:"1.0.0-beta.7+canary.2ee1b58c"}),"undefined"!=typeof window&&(window.DS=b),Ember.libraries&&Ember.libraries.registerCoreLibrary("Ember Data",b.VERSION)),a["default"]=b}),b("ember-data/lib/ext/date",[],function(){"use strict";Ember.Date=Ember.Date||{};var a=Date.parse,b=[1,4,5,6,7,10,11];Ember.Date.parse=function(c){var d,e,f=0;if(e=/^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(c)){for(var g,h=0;g=b[h];++h)e[g]=+e[g]||0;e[2]=(+e[2]||1)-1,e[3]=+e[3]||1,"Z"!==e[8]&&void 0!==e[9]&&(f=60*e[10]+e[11],"+"===e[9]&&(f=0-f)),d=Date.UTC(e[1],e[2],e[3],e[4],e[5]+f,e[6],e[7])}else d=a?a(c):0/0;return d},(Ember.EXTEND_PROTOTYPES===!0||Ember.EXTEND_PROTOTYPES.Date)&&(Date.parse=Ember.Date.parse)}),b("ember-data/lib/initializers",["./system/store","./serializers","./adapters","./system/debug/debug_adapter","./system/container_proxy","./transforms"],function(a,b,c,d,e,f){"use strict";{var g=a["default"],h=b.JSONSerializer,i=b.RESTSerializer,j=c.RESTAdapter,k=d["default"],l=e["default"],m=f.BooleanTransform,n=f.DateTransform,o=f.StringTransform,p=f.NumberTransform;Ember.set}Ember.onLoad("Ember.Application",function(a){a.initializer({name:"store",initialize:function(a,b){b.register("store:main",b.Store||g);var c=new l(a);c.registerDeprecations([{deprecated:"serializer:_default",valid:"serializer:-default"},{deprecated:"serializer:_rest",valid:"serializer:-rest"},{deprecated:"adapter:_rest",valid:"adapter:-rest"}]),b.register("serializer:-default",h),b.register("serializer:-rest",i),b.register("adapter:-rest",j),a.lookup("store:main")}}),a.initializer({name:"transforms",before:"store",initialize:function(a,b){b.register("transform:boolean",m),b.register("transform:date",n),b.register("transform:number",p),b.register("transform:string",o)}}),a.initializer({name:"data-adapter",before:"store",initialize:function(a,b){b.register("data-adapter:main",k)}}),a.initializer({name:"injectStore",before:"store",initialize:function(a,b){b.inject("controller","store","store:main"),b.inject("route","store","store:main"),b.inject("serializer","store","store:main"),b.inject("data-adapter","store","store:main")}})})}),b("ember-data/lib/main",["./core","./ext/date","./system/store","./system/model","./system/changes","./system/adapter","./system/debug","./system/record_arrays","./system/record_array_manager","./adapters","./serializers/json_serializer","./serializers/rest_serializer","../../ember-inflector/lib/main","../../activemodel-adapter/lib/main","./transforms","./system/relationships","./initializers","./system/container_proxy","exports"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s){"use strict";Ember.RSVP.Promise.cast=Ember.RSVP.Promise.cast||Ember.RSVP.resolve;var t=a["default"],u=c.Store,v=c.PromiseArray,w=c.PromiseObject,x=d.Model,y=d.Errors,z=d.RootState,A=d.attr,B=e.AttributeChange,C=e.RelationshipChange,D=e.RelationshipChangeAdd,E=(e.RelationshipChangeRemove,e.OneToManyChange),F=(e.ManyToNoneChange,e.OneToOneChange),G=e.ManyToManyChange,H=f.InvalidError,I=f.Adapter,J=g["default"],K=h.RecordArray,L=h.FilteredRecordArray,M=h.AdapterPopulatedRecordArray,N=h.ManyArray,O=i["default"],P=j.RESTAdapter,Q=j.FixtureAdapter,R=k["default"],S=l["default"],T=n.ActiveModelAdapter,U=n.ActiveModelSerializer,V=n.EmbeddedRecordsMixin,W=o.Transform,X=o.DateTransform,Y=o.NumberTransform,Z=o.StringTransform,$=o.BooleanTransform,_=p.hasMany,ab=p.belongsTo,bb=r["default"];t.Store=u,t.PromiseArray=v,t.PromiseObject=w,t.Model=x,t.RootState=z,t.attr=A,t.Errors=y,t.AttributeChange=B,t.RelationshipChange=C,t.RelationshipChangeAdd=D,t.OneToManyChange=E,t.ManyToNoneChange=E,t.OneToOneChange=F,t.ManyToManyChange=G,t.Adapter=I,t.InvalidError=H,t.DebugAdapter=J,t.RecordArray=K,t.FilteredRecordArray=L,t.AdapterPopulatedRecordArray=M,t.ManyArray=N,t.RecordArrayManager=O,t.RESTAdapter=P,t.FixtureAdapter=Q,t.RESTSerializer=S,t.JSONSerializer=R,t.Transform=W,t.DateTransform=X,t.StringTransform=Z,t.NumberTransform=Y,t.BooleanTransform=$,t.ActiveModelAdapter=T,t.ActiveModelSerializer=U,t.EmbeddedRecordsMixin=V,t.belongsTo=ab,t.hasMany=_,t.ContainerProxy=bb,s["default"]=t}),b("ember-data/lib/serializers",["./serializers/json_serializer","./serializers/rest_serializer","exports"],function(a,b,c){"use strict";var d=a["default"],e=b["default"];c.JSONSerializer=d,c.RESTSerializer=e}),b("ember-data/lib/serializers/json_serializer",["exports"],function(a){"use strict";var b=Ember.get,c=(Ember.set,Ember.isNone),d=Ember.Object.extend({primaryKey:"id",applyTransforms:function(a,b){return a.eachTransformedAttribute(function(a,c){var d=this.transformFor(c);b[a]=d.deserialize(b[a])},this),b},normalize:function(a,b){return b?(this.applyTransforms(a,b),b):b},serialize:function(a,c){var d={};if(c&&c.includeId){var e=b(a,"id");e&&(d[b(this,"primaryKey")]=e)}return a.eachAttribute(function(b,c){this.serializeAttribute(a,d,b,c)},this),a.eachRelationship(function(b,c){"belongsTo"===c.kind?this.serializeBelongsTo(a,d,c):"hasMany"===c.kind&&this.serializeHasMany(a,d,c)},this),d},serializeAttribute:function(a,c,d,e){var f=b(this,"attrs"),g=b(a,d),h=e.type;if(h){var i=this.transformFor(h);g=i.serialize(g)}d=f&&f[d]||(this.keyForAttribute?this.keyForAttribute(d):d),c[d]=g},serializeBelongsTo:function(a,d,e){var f=e.key,g=b(a,f);f=this.keyForRelationship?this.keyForRelationship(f,"belongsTo"):f,d[f]=c(g)?g:b(g,"id"),e.options.polymorphic&&this.serializePolymorphicType(a,d,e)},serializeHasMany:function(a,c,d){var e=d.key,f=DS.RelationshipChange.determineRelationshipType(a.constructor,d);("manyToNone"===f||"manyToMany"===f)&&(c[e]=b(a,e).mapBy("id"))},serializePolymorphicType:Ember.K,extract:function(a,b,c,d,e){this.extractMeta(a,b,c);var f="extract"+e.charAt(0).toUpperCase()+e.substr(1);return this[f](a,b,c,d,e)},extractFindAll:function(a,b,c){return this.extractArray(a,b,c)},extractFindQuery:function(a,b,c){return this.extractArray(a,b,c)},extractFindMany:function(a,b,c){return this.extractArray(a,b,c)},extractFindHasMany:function(a,b,c){return this.extractArray(a,b,c)},extractCreateRecord:function(a,b,c){return this.extractSave(a,b,c)},extractUpdateRecord:function(a,b,c){return this.extractSave(a,b,c)},extractDeleteRecord:function(a,b,c){return this.extractSave(a,b,c)},extractFind:function(a,b,c){return this.extractSingle(a,b,c)},extractFindBelongsTo:function(a,b,c){return this.extractSingle(a,b,c)},extractSave:function(a,b,c){return this.extractSingle(a,b,c)},extractSingle:function(a,b,c){return this.normalize(b,c)},extractArray:function(a,b,c){return this.normalize(b,c)},extractMeta:function(a,b,c){c&&c.meta&&(a.metaForType(b,c.meta),delete c.meta)},transformFor:function(a){var b=this.container.lookup("transform:"+a);return b}});a["default"]=d}),b("ember-data/lib/serializers/rest_serializer",["./json_serializer","exports"],function(a,b){"use strict";function c(a){return null==a?null:a+""}var d=a["default"],e=Ember.get,f=(Ember.set,Ember.ArrayPolyfills.forEach),g=Ember.ArrayPolyfills.map,h=d.extend({normalize:function(a,b,c){return this.normalizeId(b),this.normalizeAttributes(a,b),this.normalizeRelationships(a,b),this.normalizeUsingDeclaredMapping(a,b),this.normalizeHash&&this.normalizeHash[c]&&this.normalizeHash[c](b),this._super(a,b,c)},normalizePayload:function(a,b){return b},normalizeId:function(a){var b=e(this,"primaryKey");"id"!==b&&(a.id=a[b],delete a[b])},normalizeUsingDeclaredMapping:function(a,b){var c,d,f=e(this,"attrs");if(f)for(d in f)c=f[d],c&&c.key&&(c=c.key),"string"==typeof c&&(b[d]=b[c],delete b[c])},normalizeAttributes:function(a,b){var c;this.keyForAttribute&&a.eachAttribute(function(a){c=this.keyForAttribute(a),a!==c&&(b[a]=b[c],delete b[c])},this)},normalizeRelationships:function(a,b){var c;this.keyForRelationship&&a.eachRelationship(function(a,d){c=this.keyForRelationship(a,d.kind),a!==c&&(b[a]=b[c],delete b[c])},this)},extractSingle:function(a,b,d,e){d=this.normalizePayload(b,d);var g,h=b.typeKey;for(var i in d){var j=this.typeForRoot(i),k=a.modelFor(j),l=k.typeKey===h;l&&"array"!==Ember.typeOf(d[i])?g=this.normalize(b,d[i],i):f.call(d[i],function(b){var d=this.typeForRoot(i),f=a.modelFor(d),h=a.serializerFor(f);b=h.normalize(f,b,i);var j=l&&!e&&!g,k=l&&c(b.id)===e;j||k?g=b:a.push(d,b)},this)}return g},extractArray:function(a,b,c){c=this.normalizePayload(b,c);var d,e=b.typeKey;for(var f in c){var h=f,i=!1;"_"===f.charAt(0)&&(i=!0,h=f.substr(1));var j=this.typeForRoot(h),k=a.modelFor(j),l=a.serializerFor(k),m=!i&&k.typeKey===e,n=g.call(c[f],function(a){return l.normalize(k,a,f)},this);m?d=n:a.pushMany(j,n)}return d},pushPayload:function(a,b){b=this.normalizePayload(null,b);for(var c in b){var d=this.typeForRoot(c),e=a.modelFor(d),f=g.call(Ember.makeArray(b[c]),function(a){return this.normalize(e,a,c)},this);a.pushMany(d,f)}},typeForRoot:function(a){return Ember.String.singularize(a)},serialize:function(){return this._super.apply(this,arguments)},serializeIntoHash:function(a,b,c,d){var e=Ember.String.camelize(b.typeKey);a[e]=this.serialize(c,d)},serializePolymorphicType:function(a,b,c){var d=c.key,f=e(a,d);d=this.keyForAttribute?this.keyForAttribute(d):d,b[d+"Type"]=Ember.String.camelize(f.constructor.typeKey)}});b["default"]=h}),b("ember-data/lib/system/adapter",["exports"],function(a){"use strict";var b=Ember.get,c=(Ember.set,Ember.ArrayPolyfills.map),d=["description","fileName","lineNumber","message","name","number","stack"],e=function(a){var b=Error.prototype.constructor.call(this,"The backend rejected the commit because it was invalid: "+Ember.inspect(a));this.errors=a;for(var c=0,e=d.length;e>c;c++)this[d[c]]=b[d[c]]};e.prototype=Ember.create(Error.prototype);var f=Ember.Object.extend({find:Ember.required(Function),findAll:null,findQuery:null,generateIdForRecord:null,serialize:function(a,c){return b(a,"store").serializerFor(a.constructor.typeKey).serialize(a,c)},createRecord:Ember.required(Function),updateRecord:Ember.required(Function),deleteRecord:Ember.required(Function),findMany:function(a,b,d){var e=c.call(d,function(c){return this.find(a,b,c)},this);return Ember.RSVP.all(e)}});a.InvalidError=e,a.Adapter=f,a["default"]=f}),b("ember-data/lib/system/changes",["./changes/attribute_change","./changes/relationship_change","exports"],function(a,b,c){"use strict";var d=a["default"],e=b.RelationshipChange,f=b.RelationshipChangeAdd,g=b.RelationshipChangeRemove,h=b.OneToManyChange,i=b.ManyToNoneChange,j=b.OneToOneChange,k=b.ManyToManyChange;c.AttributeChange=d,c.RelationshipChange=e,c.RelationshipChangeAdd=f,c.RelationshipChangeRemove=g,c.OneToManyChange=h,c.ManyToNoneChange=i,c.OneToOneChange=j,c.ManyToManyChange=k}),b("ember-data/lib/system/changes/attribute_change",["exports"],function(a){"use strict";function b(a){this.record=a.record,this.store=a.store,this.name=a.name,this.value=a.value,this.oldValue=a.oldValue}b.createChange=function(a){return new b(a)},b.prototype={sync:function(){this.value!==this.oldValue&&(this.record.send("becomeDirty"),this.record.updateRecordArraysLater()),this.destroy()},destroy:function(){delete this.record._changesToSync[this.name]}},a["default"]=b}),b("ember-data/lib/system/changes/relationship_change",["../model","exports"],function(a,b){"use strict";function c(a){return"object"==typeof a&&(!a.then||"function"!=typeof a.then)}var d=a.Model,e=Ember.get,f=Ember.set,g=Ember.EnumerableUtils.forEach,h=function(a){this.parentRecord=a.parentRecord,this.childRecord=a.childRecord,this.firstRecord=a.firstRecord,this.firstRecordKind=a.firstRecordKind,this.firstRecordName=a.firstRecordName,this.secondRecord=a.secondRecord,this.secondRecordKind=a.secondRecordKind,this.secondRecordName=a.secondRecordName,this.changeType=a.changeType,this.store=a.store,this.committed={}},i=function(a){h.call(this,a)},j=function(a){h.call(this,a)};h.create=function(a){return new h(a)},i.create=function(a){return new i(a)},j.create=function(a){return new j(a)};var k={},l={},m={},n={},o={};h._createChange=function(a){return"add"===a.changeType?i.create(a):"remove"===a.changeType?j.create(a):void 0},h.determineRelationshipType=function(a,b){var c,d,e=b.key,f=b.kind,g=a.inverseFor(e);return g&&(c=g.name,d=g.kind),g?"belongsTo"===d?"belongsTo"===f?"oneToOne":"manyToOne":"belongsTo"===f?"oneToMany":"manyToMany":"belongsTo"===f?"oneToNone":"manyToNone"},h.createChange=function(a,b,c,d){var e,f=a.constructor;return e=h.determineRelationshipType(f,d),"oneToMany"===e?k.createChange(a,b,c,d):"manyToOne"===e?k.createChange(b,a,c,d):"oneToNone"===e?l.createChange(a,b,c,d):"manyToNone"===e?m.createChange(a,b,c,d):"oneToOne"===e?n.createChange(a,b,c,d):"manyToMany"===e?o.createChange(a,b,c,d):void 0},l.createChange=function(a,b,c,d){var e=d.key,f=h._createChange({parentRecord:b,childRecord:a,firstRecord:a,store:c,changeType:d.changeType,firstRecordName:e,firstRecordKind:"belongsTo"});return c.addRelationshipChangeFor(a,e,b,null,f),f},m.createChange=function(a,b,c,d){var e=d.key,f=h._createChange({parentRecord:a,childRecord:b,secondRecord:a,store:c,changeType:d.changeType,secondRecordName:d.key,secondRecordKind:"hasMany"});return c.addRelationshipChangeFor(a,e,b,null,f),f},o.createChange=function(a,b,c,d){var e=d.key,f=h._createChange({parentRecord:b,childRecord:a,firstRecord:a,secondRecord:b,firstRecordKind:"hasMany",secondRecordKind:"hasMany",store:c,changeType:d.changeType,firstRecordName:e});return c.addRelationshipChangeFor(a,e,b,null,f),f},n.createChange=function(a,b,c,d){var e;d.parentType?e=d.parentType.inverseFor(d.key).name:d.key&&(e=d.key);var f=h._createChange({parentRecord:b,childRecord:a,firstRecord:a,secondRecord:b,firstRecordKind:"belongsTo",secondRecordKind:"belongsTo",store:c,changeType:d.changeType,firstRecordName:e});return c.addRelationshipChangeFor(a,e,b,null,f),f},n.maintainInvariant=function(a,b,c,d){if("add"===a.changeType&&b.recordIsMaterialized(c)){var f=e(c,d);if(f){var g=n.createChange(c,f,b,{parentType:a.parentType,hasManyName:a.hasManyName,changeType:"remove",key:a.key});b.addRelationshipChangeFor(c,d,a.parentRecord,null,g),g.sync()}}},k.createChange=function(a,b,c,d){var e;d.parentType?(e=d.parentType.inverseFor(d.key).name,k.maintainInvariant(d,c,a,e)):d.key&&(e=d.key);var f=h._createChange({parentRecord:b,childRecord:a,firstRecord:a,secondRecord:b,firstRecordKind:"belongsTo",secondRecordKind:"hasMany",store:c,changeType:d.changeType,firstRecordName:e});return c.addRelationshipChangeFor(a,e,b,f.getSecondRecordName(),f),f},k.maintainInvariant=function(a,b,c,d){if("add"===a.changeType&&c){var f=e(c,d);if(f){var g=k.createChange(c,f,b,{parentType:a.parentType,hasManyName:a.hasManyName,changeType:"remove",key:a.key});b.addRelationshipChangeFor(c,d,a.parentRecord,g.getSecondRecordName(),g),g.sync()}}},h.prototype={getSecondRecordName:function(){var a,b=this.secondRecordName;if(!b){if(a=this.secondRecord,!a)return;var c=this.firstRecord.constructor,d=c.inverseFor(this.firstRecordName);this.secondRecordName=d.name}return this.secondRecordName},getFirstRecordName:function(){var a=this.firstRecordName;return a},destroy:function(){var a=this.childRecord,b=this.getFirstRecordName(),c=this.getSecondRecordName(),d=this.store;d.removeRelationshipChangeFor(a,b,this.parentRecord,c,this.changeType)},getSecondRecord:function(){return this.secondRecord},getFirstRecord:function(){return this.firstRecord},coalesce:function(){var a=this.store.relationshipChangePairsFor(this.firstRecord);g(a,function(a){var b=a.add,c=a.remove;b&&c&&(b.destroy(),c.destroy())})}},i.prototype=Ember.create(h.create({})),j.prototype=Ember.create(h.create({})),i.prototype.changeType="add",i.prototype.sync=function(){var a=this.getSecondRecordName(),b=this.getFirstRecordName(),g=this.getFirstRecord(),h=this.getSecondRecord();h instanceof d&&g instanceof d&&("belongsTo"===this.secondRecordKind?h.suspendRelationshipObservers(function(){f(h,a,g)}):"hasMany"===this.secondRecordKind&&h.suspendRelationshipObservers(function(){var b=e(h,a);c(b)&&b.addObject(g)})),g instanceof d&&h instanceof d&&e(g,b)!==h&&("belongsTo"===this.firstRecordKind?g.suspendRelationshipObservers(function(){f(g,b,h)}):"hasMany"===this.firstRecordKind&&g.suspendRelationshipObservers(function(){var a=e(g,b);c(a)&&a.addObject(h)})),this.coalesce()},j.prototype.changeType="remove",j.prototype.sync=function(){var a=this.getSecondRecordName(),b=this.getFirstRecordName(),g=this.getFirstRecord(),h=this.getSecondRecord();h instanceof d&&g instanceof d&&("belongsTo"===this.secondRecordKind?h.suspendRelationshipObservers(function(){f(h,a,null)}):"hasMany"===this.secondRecordKind&&h.suspendRelationshipObservers(function(){var b=e(h,a);c(b)&&b.removeObject(g)})),g instanceof d&&e(g,b)&&("belongsTo"===this.firstRecordKind?g.suspendRelationshipObservers(function(){f(g,b,null)}):"hasMany"===this.firstRecordKind&&g.suspendRelationshipObservers(function(){var a=e(g,b);c(a)&&a.removeObject(h)})),this.coalesce()},b.RelationshipChange=h,b.RelationshipChangeAdd=i,b.RelationshipChangeRemove=j,b.OneToManyChange=k,b.ManyToNoneChange=m,b.OneToOneChange=n,b.ManyToManyChange=o}),b("ember-data/lib/system/container_proxy",["exports"],function(a){"use strict";var b=function(a){this.container=a};b.prototype.aliasedFactory=function(a,b){var c=this;return{create:function(){return b&&b(),c.container.lookup(a)}}},b.prototype.registerAlias=function(a,b,c){var d=this.aliasedFactory(b,c);return this.container.register(a,d)},b.prototype.registerDeprecation=function(a,b){var c=function(){};return this.registerAlias(a,b,c)},b.prototype.registerDeprecations=function(a){for(var b=a.length;b>0;b--){var c=a[b-1],d=c.deprecated,e=c.valid;this.registerDeprecation(d,e)}},a["default"]=b}),b("ember-data/lib/system/debug",["./debug/debug_info","./debug/debug_adapter","exports"],function(a,b,c){"use strict";var d=b["default"];c["default"]=d}),b("ember-data/lib/system/debug/debug_adapter",["../model","exports"],function(a,b){"use strict";var c=a.Model,d=Ember.get,e=Ember.String.capitalize,f=Ember.String.underscore,g=Ember.DataAdapter.extend({getFilters:function(){return[{name:"isNew",desc:"New"},{name:"isModified",desc:"Modified"},{name:"isClean",desc:"Clean"}]},detect:function(a){return a!==c&&c.detect(a)},columnsForType:function(a){var b=[{name:"id",desc:"Id"}],c=0,g=this;return d(a,"attributes").forEach(function(a){if(c++>g.attributeLimit)return!1;var d=e(f(a).replace("_"," "));b.push({name:a,desc:d})}),b},getRecords:function(a){return this.get("store").all(a)},getRecordColumnValues:function(a){var b=this,c=0,e={id:d(a,"id")};return a.eachAttribute(function(f){if(c++>b.attributeLimit)return!1;var g=d(a,f);e[f]=g}),e},getRecordKeywords:function(a){var b=[],c=Ember.A(["id"]);return a.eachAttribute(function(a){c.push(a)}),c.forEach(function(c){b.push(d(a,c))}),b},getRecordFilterValues:function(a){return{isNew:a.get("isNew"),isModified:a.get("isDirty")&&!a.get("isNew"),isClean:!a.get("isDirty")}},getRecordColor:function(a){var b="black";return a.get("isNew")?b="green":a.get("isDirty")&&(b="blue"),b},observeRecord:function(a,b){var c=Ember.A(),d=this,e=Ember.A(["id","isNew","isDirty"]);a.eachAttribute(function(a){e.push(a)}),e.forEach(function(e){var f=function(){b(d.wrapRecord(a))};Ember.addObserver(a,e,f),c.push(function(){Ember.removeObserver(a,e,f)})});var f=function(){c.forEach(function(a){a()})};return f}});b["default"]=g}),b("ember-data/lib/system/debug/debug_info",["../model","exports"],function(a,b){"use strict";var c=a.Model;c.reopen({_debugInfo:function(){var a=["id"],b={belongsTo:[],hasMany:[]},c=[];this.eachAttribute(function(b){a.push(b)},this),this.eachRelationship(function(a,d){b[d.kind].push(a),c.push(a)});var d=[{name:"Attributes",properties:a,expand:!0},{name:"Belongs To",properties:b.belongsTo,expand:!0},{name:"Has Many",properties:b.hasMany,expand:!0},{name:"Flags",properties:["isLoaded","isDirty","isSaving","isDeleted","isError","isNew","isValid"]}];return{propertyInfo:{includeOtherProperties:!0,groups:d,expensiveProperties:c}}}}),b["default"]=c}),b("ember-data/lib/system/model",["./model/model","./model/attributes","./model/states","./model/errors","exports"],function(a,b,c,d,e){"use strict";var f=a["default"],g=b["default"],h=c["default"],i=d["default"];e.Model=f,e.RootState=h,e.attr=g,e.Errors=i}),b("ember-data/lib/system/model/attributes",["./model","exports"],function(a,b){"use strict";function c(a,b){return"function"==typeof b.defaultValue?b.defaultValue.apply(null,arguments):b.defaultValue}function d(a,b){return a._attributes.hasOwnProperty(b)||a._inFlightAttributes.hasOwnProperty(b)||a._data.hasOwnProperty(b)}function e(a,b){return a._attributes.hasOwnProperty(b)?a._attributes[b]:a._inFlightAttributes.hasOwnProperty(b)?a._inFlightAttributes[b]:a._data[b]}function f(a,b){b=b||{};var f={type:a,isAttribute:!0,options:b};return Ember.computed("data",function(a,f){if(arguments.length>1){var g=e(this,a);return f!==g&&(this._attributes[a]=f,this.send("didSetProperty",{name:a,oldValue:g,originalValue:this._data[a],value:f})),f}return d(this,a)?e(this,a):c(this,b,a)}).meta(f)}var g=a["default"],h=Ember.get;g.reopenClass({attributes:Ember.computed(function(){var a=Ember.Map.create();return this.eachComputedProperty(function(b,c){c.isAttribute&&(c.name=b,a.set(b,c))}),a}),transformedAttributes:Ember.computed(function(){var a=Ember.Map.create();return this.eachAttribute(function(b,c){c.type&&a.set(b,c.type)}),a}),eachAttribute:function(a,b){h(this,"attributes").forEach(function(c,d){a.call(b,c,d)},b)},eachTransformedAttribute:function(a,b){h(this,"transformedAttributes").forEach(function(c,d){a.call(b,c,d)})}}),g.reopen({eachAttribute:function(a,b){this.constructor.eachAttribute(a,b)}}),b["default"]=f +}),b("ember-data/lib/system/model/errors",["exports"],function(a){"use strict";var b=Ember.get,c=Ember.isEmpty,d=Ember.Object.extend(Ember.Enumerable,Ember.Evented,{registerHandlers:function(a,b,c){this.on("becameInvalid",a,b),this.on("becameValid",a,c)},errorsByAttributeName:Ember.reduceComputed("content",{initialValue:function(){return Ember.MapWithDefault.create({defaultValue:function(){return Ember.A()}})},addedItem:function(a,b){return a.get(b.attribute).pushObject(b),a},removedItem:function(a,b){return a.get(b.attribute).removeObject(b),a}}),errorsFor:function(a){return b(this,"errorsByAttributeName").get(a)},messages:Ember.computed.mapBy("content","message"),content:Ember.computed(function(){return Ember.A()}),unknownProperty:function(a){var b=this.errorsFor(a);return c(b)?null:b},nextObject:function(a){return b(this,"content").objectAt(a)},length:Ember.computed.oneWay("content.length").readOnly(),isEmpty:Ember.computed.not("length").readOnly(),add:function(a,c){var d=b(this,"isEmpty");c=this._findOrCreateMessages(a,c),b(this,"content").addObjects(c),this.notifyPropertyChange(a),this.enumerableContentDidChange(),d&&!b(this,"isEmpty")&&this.trigger("becameInvalid")},_findOrCreateMessages:function(a,b){var c=this.errorsFor(a);return Ember.makeArray(b).map(function(b){return c.findBy("message",b)||{attribute:a,message:b}})},remove:function(a){if(!b(this,"isEmpty")){var c=b(this,"content").rejectBy("attribute",a);b(this,"content").setObjects(c),this.notifyPropertyChange(a),this.enumerableContentDidChange(),b(this,"isEmpty")&&this.trigger("becameValid")}},clear:function(){b(this,"isEmpty")||(b(this,"content").clear(),this.enumerableContentDidChange(),this.trigger("becameValid"))},has:function(a){return!c(this.errorsFor(a))}});a["default"]=d}),b("ember-data/lib/system/model/model",["./states","./errors","exports"],function(a,b,c){"use strict";var d=a["default"],e=b["default"],f=Ember.get,g=Ember.set,h=Ember.merge,i=Ember.RSVP.Promise,j=Ember.computed("currentState",function(a){return f(f(this,"currentState"),a)}).readOnly(),k=Ember.Object.extend(Ember.Evented,{isEmpty:j,isLoading:j,isLoaded:j,isDirty:j,isSaving:j,isDeleted:j,isNew:j,isValid:j,dirtyType:j,isError:!1,isReloading:!1,clientId:null,id:null,currentState:d.empty,errors:Ember.computed(function(){var a=e.create();return a.registerHandlers(this,function(){this.send("becameInvalid")},function(){this.send("becameValid")}),a}).readOnly(),serialize:function(a){var b=f(this,"store");return b.serialize(this,a)},toJSON:function(a){var b=DS.JSONSerializer.create({container:this.container});return b.serialize(this,a)},didLoad:Ember.K,didUpdate:Ember.K,didCreate:Ember.K,didDelete:Ember.K,becameInvalid:Ember.K,becameError:Ember.K,data:Ember.computed(function(){return this._data=this._data||{},this._data}).readOnly(),_data:null,init:function(){this._super(),this._setup()},_setup:function(){this._changesToSync={},this._deferredTriggers=[],this._data={},this._attributes={},this._inFlightAttributes={},this._relationships={}},send:function(a,b){var c=f(this,"currentState");return c[a]||this._unhandledEvent(c,a,b),c[a](this,b)},transitionTo:function(a){var b=a.split(".",1),c=f(this,"currentState"),d=c;do d.exit&&d.exit(this),d=d.parentState;while(!d.hasOwnProperty(b));var e,h,i=a.split("."),j=[],k=[];for(e=0,h=i.length;h>e;e++)d=d[i[e]],d.enter&&k.push(d),d.setup&&j.push(d);for(e=0,h=k.length;h>e;e++)k[e].enter(this);for(g(this,"currentState",d),e=0,h=j.length;h>e;e++)j[e].setup(this);this.updateRecordArraysLater()},_unhandledEvent:function(a,b,c){var d="Attempted to handle event `"+b+"` ";throw d+="on "+String(this)+" while in state ",d+=a.stateName+". ",void 0!==c&&(d+="Called with "+Ember.inspect(c)+"."),new Ember.Error(d)},withTransaction:function(a){var b=f(this,"transaction");b&&a(b)},loadingData:function(a){this.send("loadingData",a)},loadedData:function(){this.send("loadedData")},notFound:function(){this.send("notFound")},pushedData:function(){this.send("pushedData")},deleteRecord:function(){this.send("deleteRecord")},destroyRecord:function(){return this.deleteRecord(),this.save()},unloadRecord:function(){this.send("unloadRecord")},clearRelationships:function(){this.eachRelationship(function(a,b){if("belongsTo"===b.kind)g(this,a,null);else if("hasMany"===b.kind){var c=this._relationships[b.name];c&&c.clear()}},this)},updateRecordArrays:function(){this._updatingRecordArraysLater=!1,f(this,"store").dataWasUpdated(this.constructor,this)},changedAttributes:function(){var a,b=f(this,"_data"),c=f(this,"_attributes"),d={};for(a in c)d[a]=[b[a],c[a]];return d},adapterWillCommit:function(){this.send("willCommit")},adapterDidCommit:function(a){g(this,"isError",!1),a?this._data=a:Ember.mixin(this._data,this._inFlightAttributes),this._inFlightAttributes={},this.send("didCommit"),this.updateRecordArraysLater(),a&&this.suspendRelationshipObservers(function(){this.notifyPropertyChange("data")})},adapterDidDirty:function(){this.send("becomeDirty"),this.updateRecordArraysLater()},dataDidChange:Ember.observer(function(){this.reloadHasManys()},"data"),reloadHasManys:function(){var a=f(this.constructor,"relationshipsByName");this.updateRecordArraysLater(),a.forEach(function(a,b){this._data.links&&this._data.links[a]||"hasMany"===b.kind&&this.hasManyDidChange(b.key)},this)},hasManyDidChange:function(a){var b=this._relationships[a];if(b){var c=this._data[a]||[];g(b,"content",Ember.A(c)),g(b,"isLoaded",!0),b.trigger("didLoad")}},updateRecordArraysLater:function(){this._updatingRecordArraysLater||(this._updatingRecordArraysLater=!0,Ember.run.schedule("actions",this,this.updateRecordArrays))},setupData:function(a,b){b?Ember.merge(this._data,a):this._data=a;var c=this._relationships;this.eachRelationship(function(b,d){a.links&&a.links[b]||d.options.async&&(c[b]=null)}),a&&this.pushedData(),this.suspendRelationshipObservers(function(){this.notifyPropertyChange("data")})},materializeId:function(a){g(this,"id",a)},materializeAttributes:function(a){h(this._data,a)},materializeAttribute:function(a,b){this._data[a]=b},updateHasMany:function(a,b){this._data[a]=b,this.hasManyDidChange(a)},updateBelongsTo:function(a,b){this._data[a]=b},rollback:function(){this._attributes={},f(this,"isError")&&(this._inFlightAttributes={},g(this,"isError",!1)),f(this,"isValid")||(this._inFlightAttributes={}),this.send("rolledBack"),this.suspendRelationshipObservers(function(){this.notifyPropertyChange("data")})},toStringExtension:function(){return f(this,"id")},suspendRelationshipObservers:function(a,b){var c=f(this.constructor,"relationshipNames").belongsTo,d=this;try{this._suspendedRelationships=!0,Ember._suspendObservers(d,c,null,"belongsToDidChange",function(){Ember._suspendBeforeObservers(d,c,null,"belongsToWillChange",function(){a.call(b||d)})})}finally{this._suspendedRelationships=!1}},save:function(){var a="DS: Model#save "+this,b=Ember.RSVP.defer(a);return this.get("store").scheduleSave(this,b),this._inFlightAttributes=this._attributes,this._attributes={},DS.PromiseObject.create({promise:b.promise})},reload:function(){g(this,"isReloading",!0);var a=this,b="DS: Model#reload of "+this,c=new i(function(b){a.send("reloadRecord",b)},b).then(function(){return a.set("isReloading",!1),a.set("isError",!1),a},function(b){throw a.set("isError",!0),b},"DS: Model#reload complete, update flags");return DS.PromiseObject.create({promise:c})},adapterDidUpdateAttribute:function(a,b){void 0!==b?(this._data[a]=b,this.notifyPropertyChange(a)):this._data[a]=this._inFlightAttributes[a],this.updateRecordArraysLater()},adapterDidInvalidate:function(a){function b(b){a[b]&&c.add(b,a[b])}var c=f(this,"errors");this.eachAttribute(b),this.eachRelationship(b)},adapterDidError:function(){this.send("becameError"),g(this,"isError",!0)},trigger:function(a){Ember.tryInvoke(this,a,[].slice.call(arguments,1)),this._super.apply(this,arguments)},triggerLater:function(){1===this._deferredTriggers.push(arguments)&&Ember.run.schedule("actions",this,"_triggerDeferredTriggers")},_triggerDeferredTriggers:function(){for(var a=0,b=this._deferredTriggers.length;b>a;a++)this.trigger.apply(this,this._deferredTriggers[a]);this._deferredTriggers.length=0}});k.reopenClass({_create:k.create,create:function(){throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.")}}),c["default"]=k}),b("ember-data/lib/system/model/states",["exports"],function(a){"use strict";function b(a,b){b.value===b.originalValue?(delete a._attributes[b.name],a.send("propertyWasReset",b.name)):b.value!==b.oldValue&&a.send("becomeDirty"),a.updateRecordArraysLater()}function c(a){var b,d={};for(var e in a)b=a[e],d[e]=b&&"object"==typeof b?c(b):b;return d}function d(a,b){for(var c in b)a[c]=b[c];return a}function e(a){var b=c(i);return d(b,a)}function f(a,b,c){a=d(b?Ember.create(b):{},a),a.parentState=b,a.stateName=c;for(var e in a)a.hasOwnProperty(e)&&"parentState"!==e&&"stateName"!==e&&"object"==typeof a[e]&&(a[e]=f(a[e],a,c+"."+e));return a}var g=Ember.get,h=Ember.set,i={initialState:"uncommitted",isDirty:!0,uncommitted:{didSetProperty:b,propertyWasReset:function(a){var b=!1;for(var c in a._attributes){b=!0;break}b||a.send("rolledBack")},pushedData:Ember.K,becomeDirty:Ember.K,willCommit:function(a){a.transitionTo("inFlight")},reloadRecord:function(a,b){b(g(a,"store").reloadRecord(a))},rolledBack:function(a){a.transitionTo("loaded.saved")},becameInvalid:function(a){a.transitionTo("invalid")},rollback:function(a){a.rollback()}},inFlight:{isSaving:!0,didSetProperty:b,becomeDirty:Ember.K,pushedData:Ember.K,willCommit:Ember.K,didCommit:function(a){var b=g(this,"dirtyType");a.transitionTo("saved"),a.send("invokeLifecycleCallbacks",b)},becameInvalid:function(a){a.transitionTo("invalid"),a.send("invokeLifecycleCallbacks")},becameError:function(a){a.transitionTo("uncommitted"),a.triggerLater("becameError",a)}},invalid:{isValid:!1,deleteRecord:function(a){a.transitionTo("deleted.uncommitted"),a.clearRelationships()},didSetProperty:function(a,c){g(a,"errors").remove(c.name),b(a,c)},becomeDirty:Ember.K,rolledBack:function(a){g(a,"errors").clear()},becameValid:function(a){a.transitionTo("uncommitted")},invokeLifecycleCallbacks:function(a){a.triggerLater("becameInvalid",a)}}},j=e({dirtyType:"created",isNew:!0});j.uncommitted.rolledBack=function(a){a.transitionTo("deleted.saved")};var k=e({dirtyType:"updated"});j.uncommitted.deleteRecord=function(a){a.clearRelationships(),a.transitionTo("deleted.saved")},j.uncommitted.rollback=function(a){i.uncommitted.rollback.apply(this,arguments),a.transitionTo("deleted.saved")},j.uncommitted.propertyWasReset=Ember.K,k.uncommitted.deleteRecord=function(a){a.transitionTo("deleted.uncommitted"),a.clearRelationships()};var l={isEmpty:!1,isLoading:!1,isLoaded:!1,isDirty:!1,isSaving:!1,isDeleted:!1,isNew:!1,isValid:!0,rolledBack:Ember.K,propertyWasReset:Ember.K,empty:{isEmpty:!0,loadingData:function(a,b){a._loadingPromise=b,a.transitionTo("loading")},loadedData:function(a){a.transitionTo("loaded.created.uncommitted"),a.suspendRelationshipObservers(function(){a.notifyPropertyChange("data")})},pushedData:function(a){a.transitionTo("loaded.saved"),a.triggerLater("didLoad")}},loading:{isLoading:!0,exit:function(a){a._loadingPromise=null},pushedData:function(a){a.transitionTo("loaded.saved"),a.triggerLater("didLoad"),h(a,"isError",!1)},becameError:function(a){a.triggerLater("becameError",a)},notFound:function(a){a.transitionTo("empty")}},loaded:{initialState:"saved",isLoaded:!0,saved:{setup:function(a){var b=a._attributes,c=!1;for(var d in b)if(b.hasOwnProperty(d)){c=!0;break}c&&a.adapterDidDirty()},didSetProperty:b,pushedData:Ember.K,becomeDirty:function(a){a.transitionTo("updated.uncommitted")},willCommit:function(a){a.transitionTo("updated.inFlight")},reloadRecord:function(a,b){b(g(a,"store").reloadRecord(a))},deleteRecord:function(a){a.transitionTo("deleted.uncommitted"),a.clearRelationships()},unloadRecord:function(a){a.clearRelationships(),a.transitionTo("deleted.saved")},didCommit:function(a){a.send("invokeLifecycleCallbacks",g(a,"lastDirtyType"))},notFound:Ember.K},created:j,updated:k},deleted:{initialState:"uncommitted",dirtyType:"deleted",isDeleted:!0,isLoaded:!0,isDirty:!0,setup:function(a){a.updateRecordArrays()},uncommitted:{willCommit:function(a){a.transitionTo("inFlight")},rollback:function(a){a.rollback()},becomeDirty:Ember.K,deleteRecord:Ember.K,rolledBack:function(a){a.transitionTo("loaded.saved")}},inFlight:{isSaving:!0,willCommit:Ember.K,didCommit:function(a){a.transitionTo("saved"),a.send("invokeLifecycleCallbacks")},becameError:function(a){a.transitionTo("uncommitted"),a.triggerLater("becameError",a)}},saved:{isDirty:!1,setup:function(a){var b=g(a,"store");b.dematerializeRecord(a)},invokeLifecycleCallbacks:function(a){a.triggerLater("didDelete",a),a.triggerLater("didCommit",a)}}},invokeLifecycleCallbacks:function(a,b){"created"===b?a.triggerLater("didCreate",a):a.triggerLater("didUpdate",a),a.triggerLater("didCommit",a)}};l=f(l,null,"root"),a["default"]=l}),b("ember-data/lib/system/record_array_manager",["./record_arrays","exports"],function(a,b){"use strict";var c=a.ManyArray,d=Ember.get,e=(Ember.set,Ember.EnumerableUtils.forEach),f=Ember.Object.extend({init:function(){this.filteredRecordArrays=Ember.MapWithDefault.create({defaultValue:function(){return[]}}),this.changedRecords=[]},recordDidChange:function(a){1===this.changedRecords.push(a)&&Ember.run.schedule("actions",this,this.updateRecordArrays)},recordArraysForRecord:function(a){return a._recordArrays=a._recordArrays||Ember.OrderedSet.create(),a._recordArrays},updateRecordArrays:function(){e(this.changedRecords,function(a){d(a,"isDeleted")?this._recordWasDeleted(a):this._recordWasChanged(a)},this),this.changedRecords.length=0},_recordWasDeleted:function(a){var b=a._recordArrays;b&&e(b,function(b){b.removeRecord(a)})},_recordWasChanged:function(a){var b,c=a.constructor,f=this.filteredRecordArrays.get(c);e(f,function(e){b=d(e,"filterFunction"),this.updateRecordArray(e,b,c,a)},this);var g=a._loadingRecordArrays;if(g){for(var h=0,i=g.length;i>h;h++)g[h].loadedRecord();a._loadingRecordArrays=[]}},updateRecordArray:function(a,b,c,d){var e;e=b?b(d):!0;var f=this.recordArraysForRecord(d);e?(f.add(a),a.addRecord(d)):e||(f.remove(a),a.removeRecord(d))},updateFilter:function(a,b,c){for(var e,f=this.store.typeMapFor(b),g=f.records,h=0,i=g.length;i>h;h++)e=g[h],d(e,"isDeleted")||d(e,"isEmpty")||this.updateRecordArray(a,c,b,e)},createManyArray:function(a,b){var d=c.create({type:a,content:b,store:this.store});return e(b,function(a){var b=this.recordArraysForRecord(a);b.add(d)},this),d},createRecordArray:function(a){var b=DS.RecordArray.create({type:a,content:Ember.A(),store:this.store,isLoaded:!0});return this.registerFilteredRecordArray(b,a),b},createFilteredRecordArray:function(a,b){var c=DS.FilteredRecordArray.create({type:a,content:Ember.A(),store:this.store,manager:this,filterFunction:b});return this.registerFilteredRecordArray(c,a,b),c},createAdapterPopulatedRecordArray:function(a,b){return DS.AdapterPopulatedRecordArray.create({type:a,query:b,content:Ember.A(),store:this.store})},registerFilteredRecordArray:function(a,b,c){var d=this.filteredRecordArrays.get(b);d.push(a),this.updateFilter(a,b,c)},registerWaitingRecordArray:function(a,b){var c=a._loadingRecordArrays||[];c.push(b),a._loadingRecordArrays=c}});b["default"]=f}),b("ember-data/lib/system/record_arrays",["./record_arrays/record_array","./record_arrays/filtered_record_array","./record_arrays/adapter_populated_record_array","./record_arrays/many_array","exports"],function(a,b,c,d,e){"use strict";var f=a["default"],g=b["default"],h=c["default"],i=d["default"];e.RecordArray=f,e.FilteredRecordArray=g,e.AdapterPopulatedRecordArray=h,e.ManyArray=i}),b("ember-data/lib/system/record_arrays/adapter_populated_record_array",["./record_array","exports"],function(a,b){"use strict";var c=a["default"],d=Ember.get,e=(Ember.set,c.extend({query:null,replace:function(){var a=d(this,"type").toString();throw new Error("The result of a server query (on "+a+") is immutable.")},load:function(a){var b=d(this,"store"),c=d(this,"type"),e=b.pushMany(c,a),f=b.metadataFor(c);this.setProperties({content:Ember.A(e),isLoaded:!0,meta:f}),Ember.run.once(this,"trigger","didLoad")}}));b["default"]=e}),b("ember-data/lib/system/record_arrays/filtered_record_array",["./record_array","exports"],function(a,b){"use strict";var c=a["default"],d=Ember.get,e=c.extend({filterFunction:null,isLoaded:!0,replace:function(){var a=d(this,"type").toString();throw new Error("The result of a client-side filter (on "+a+") is immutable.")},updateFilter:Ember.observer(function(){var a=d(this,"manager");a.updateFilter(this,d(this,"type"),d(this,"filterFunction"))},"filterFunction")});b["default"]=e}),b("ember-data/lib/system/record_arrays/many_array",["./record_array","../changes","exports"],function(a,b,c){"use strict";function d(a){a.sync()}var e=a["default"],f=b.RelationshipChange,g=Ember.get,h=Ember.set,i=Ember.EnumerableUtils.map,j=e.extend({init:function(){this._super.apply(this,arguments),this._changesToSync=Ember.OrderedSet.create()},name:null,owner:null,isPolymorphic:!1,isLoaded:!1,promise:null,loadingRecordsCount:function(a){this.loadingRecordsCount=a},loadedRecord:function(){this.loadingRecordsCount--,0===this.loadingRecordsCount&&(h(this,"isLoaded",!0),this.trigger("didLoad"))},fetch:function(){var a=g(this,"content"),b=g(this,"store"),c=g(this,"owner"),d=Ember.RSVP.defer("DS: ManyArray#fetch "+g(this,"type")),e=a.filterProperty("isEmpty",!0);b.fetchMany(e,c,d)},replaceContent:function(a,b,c){c=i(c,function(a){return a},this),this._super(a,b,c)},arrangedContentDidChange:function(){Ember.run.once(this,"fetch")},arrayContentWillChange:function(a,b){var c=g(this,"owner"),d=g(this,"name");if(!c._suspendedRelationships)for(var e=a;a+b>e;e++){var h=g(this,"content").objectAt(e),i=f.createChange(c,h,g(this,"store"),{parentType:c.constructor,changeType:"remove",kind:"hasMany",key:d});this._changesToSync.add(i)}return this._super.apply(this,arguments)},arrayContentDidChange:function(a,b,c){this._super.apply(this,arguments);var e=g(this,"owner"),h=g(this,"name"),i=g(this,"store");if(!e._suspendedRelationships){for(var j=a;a+c>j;j++){var k=g(this,"content").objectAt(j),l=f.createChange(e,k,i,{parentType:e.constructor,changeType:"add",kind:"hasMany",key:h});l.hasManyName=h,this._changesToSync.add(l)}this._changesToSync.forEach(d),this._changesToSync.clear()}},createRecord:function(a){var b,c=g(this,"owner"),d=g(c,"store"),e=g(this,"type");return b=d.createRecord.call(d,e,a),this.pushObject(b),b}});c["default"]=j}),b("ember-data/lib/system/record_arrays/record_array",["../store","exports"],function(a,b){"use strict";var c=a.PromiseArray,d=Ember.get,e=(Ember.set,Ember.ArrayProxy.extend(Ember.Evented,{type:null,content:null,isLoaded:!1,isUpdating:!1,store:null,objectAtContent:function(a){var b=d(this,"content");return b.objectAt(a)},update:function(){if(!d(this,"isUpdating")){var a=d(this,"store"),b=d(this,"type");return a.fetchAll(b,this)}},addRecord:function(a){d(this,"content").addObject(a)},removeRecord:function(a){d(this,"content").removeObject(a)},save:function(){var a="DS: RecordArray#save "+d(this,"type"),b=Ember.RSVP.all(this.invoke("save"),a).then(function(a){return Ember.A(a)},null,"DS: RecordArray#save apply Ember.NativeArray");return c.create({promise:b})}}));b["default"]=e}),b("ember-data/lib/system/relationships",["./relationships/belongs_to","./relationships/has_many","../system/relationships/ext","exports"],function(a,b,c,d){"use strict";var e=a["default"],f=b["default"];d.belongsTo=e,d.hasMany=f}),b("ember-data/lib/system/relationships/belongs_to",["../model","exports"],function(a,b){"use strict";function c(a,b,c){return Ember.computed("data",function(a,b){var d=e(this,"data"),h=e(this,"store"),i="DS: Async belongsTo "+this+" : "+a;if(2===arguments.length)return void 0===b?null:DS.PromiseObject.create({promise:g.cast(b,i)});var j=d.links&&d.links[a],k=d[a];if(f(k)){if(j){var l=Ember.RSVP.defer("DS: Async belongsTo (link) "+this+" : "+a);return h.findBelongsTo(this,j,c,l),DS.PromiseObject.create({promise:l.promise})}return null}var m=h.fetchRecord(k)||g.cast(k,i);return DS.PromiseObject.create({promise:m})}).meta(c)}function d(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var d={type:a,isRelationship:!0,options:b,kind:"belongsTo"};return b.async?c(a,b,d):Ember.computed("data",function(b,c){var d,g,h=e(this,"data"),i=e(this,"store");return g="string"==typeof a?i.modelFor(a):a,2===arguments.length?void 0===c?null:c:(d=h[b],f(d)?null:(i.fetchRecord(d),d))}).meta(d)}var e=Ember.get,f=(Ember.set,Ember.isNone),g=Ember.RSVP.Promise,h=a.Model;h.reopen({belongsToWillChange:Ember.beforeObserver(function(a,b){if(e(a,"isLoaded")){var c=e(a,b);if(c){var d=e(a,"store"),f=DS.RelationshipChange.createChange(a,c,d,{key:b,kind:"belongsTo",changeType:"remove"});f.sync(),this._changesToSync[b]=f}}}),belongsToDidChange:Ember.immediateObserver(function(a,b){if(e(a,"isLoaded")){var c=e(a,b);if(c){var d=e(a,"store"),f=DS.RelationshipChange.createChange(a,c,d,{key:b,kind:"belongsTo",changeType:"add"});f.sync()}}delete this._changesToSync[b]})}),b["default"]=d}),b("ember-data/lib/system/relationships/ext",["../../../../ember-inflector/lib/system","../model"],function(a,b){"use strict";{var c=a.singularize,d=b.Model,e=Ember.get;Ember.set}d.reopen({didDefineProperty:function(a,b,c){if(c instanceof Ember.Descriptor){var d=c.meta();d.isRelationship&&"belongsTo"===d.kind&&(Ember.addObserver(a,b,null,"belongsToDidChange"),Ember.addBeforeObserver(a,b,null,"belongsToWillChange")),d.parentType=a.constructor}}}),d.reopenClass({typeForRelationship:function(a){var b=e(this,"relationshipsByName").get(a);return b&&b.type},inverseFor:function(a){function b(a,c,d){d=d||[];var f=e(c,"relationships");if(f){var g=f.get(a);return g&&d.push.apply(d,f.get(a)),a.superclass&&b(a.superclass,c,d),d}}var c=this.typeForRelationship(a);if(!c)return null;var d=this.metaForProperty(a).options;if(null===d.inverse)return null;var f,g;if(d.inverse)f=d.inverse,g=Ember.get(c,"relationshipsByName").get(f).kind;else{var h=b(this,c);if(0===h.length)return null;f=h[0].name,g=h[0].kind}return{type:c,name:f,kind:g}},relationships:Ember.computed(function(){var a=new Ember.MapWithDefault({defaultValue:function(){return[]}});return this.eachComputedProperty(function(b,c){if(c.isRelationship){"string"==typeof c.type&&(c.type=this.store.modelFor(c.type));var d=a.get(c.type);d.push({name:b,kind:c.kind})}}),a}),relationshipNames:Ember.computed(function(){var a={hasMany:[],belongsTo:[]};return this.eachComputedProperty(function(b,c){c.isRelationship&&a[c.kind].push(b)}),a}),relatedTypes:Ember.computed(function(){var a,b=Ember.A();return this.eachComputedProperty(function(c,d){d.isRelationship&&(a=d.type,"string"==typeof a&&(a=e(this,a,!1)||this.store.modelFor(a)),b.contains(a)||b.push(a))}),b}),relationshipsByName:Ember.computed(function(){var a,b=Ember.Map.create();return this.eachComputedProperty(function(d,e){e.isRelationship&&(e.key=d,a=e.type,a||"hasMany"!==e.kind?a||(a=d):a=c(d),"string"==typeof a&&(e.type=this.store.modelFor(a)),b.set(d,e))}),b}),fields:Ember.computed(function(){var a=Ember.Map.create();return this.eachComputedProperty(function(b,c){c.isRelationship?a.set(b,c.kind):c.isAttribute&&a.set(b,"attribute")}),a}),eachRelationship:function(a,b){e(this,"relationshipsByName").forEach(function(c,d){a.call(b,c,d)})},eachRelatedType:function(a,b){e(this,"relatedTypes").forEach(function(c){a.call(b,c)})}}),d.reopen({eachRelationship:function(a,b){this.constructor.eachRelationship(a,b)}})}),b("ember-data/lib/system/relationships/has_many",["exports"],function(a){"use strict";function b(a,b,d){return Ember.computed("data",function(a){var e=this._relationships[a],f="DS: Async hasMany "+this+" : "+a;if(!e){var h=Ember.RSVP.defer(f);e=c(this,a,b,function(b,c){var e,f=c.links&&c.links[a];return e=f?b.findHasMany(this,f,d,h):b.findMany(this,c[a],d.type,h),g(e,"promise",h.promise),e})}var i=e.get("promise").then(function(){return e},null,"DS: Async hasMany records received");return DS.PromiseArray.create({promise:i})}).meta(d).readOnly()}function c(a,b,c,d){var e=a._relationships;if(e[b])return e[b];var g=f(a,"data"),i=f(a,"store"),j=e[b]=d.call(a,i,g);return h(j,{owner:a,name:b,isPolymorphic:c.polymorphic})}function d(a,d){d=d||{};var e={type:a,isRelationship:!0,options:d,kind:"hasMany"};return d.async?b(a,d,e):Ember.computed("data",function(a){return c(this,a,d,function(b,c){c[a];return b.findMany(this,c[a],e.type)})}).meta(e).readOnly()}function e(a,b){return"object"==typeof a&&(b=a,a=void 0),d(a,b)}var f=Ember.get,g=Ember.set,h=Ember.setProperties;a["default"]=e}),b("ember-data/lib/system/store",["exports"],function(a){"use strict";function b(a){return null==a?null:a+""}function c(a,b,c,e){return b.eachRelationship(function(b,h){if(c.links&&c.links[b])return void(e&&h.options.async&&(e._relationships[b]=null));var i=h.kind,j=c[b];null!=j&&("belongsTo"===i?d(a,c,b,h,j):"hasMany"===i&&(f(a,c,b,h,j),g(e,b,j)))}),c}function d(a,b,c,d,f){if(!(z(f)||f instanceof DS.Model)){var g;"number"==typeof f||"string"==typeof f?(g=e(d,c,b),b[c]=a.recordForId(g,f)):"object"==typeof f&&(b[c]=a.recordForId(f.type,f.id))}}function e(a,b,c){return a.options.polymorphic?c[b+"Type"]:a.type}function f(a,b,c,e,f){for(var g=0,h=f.length;h>g;g++)d(a,f,g,e,f[g])}function g(a,b,c){a&&c.pushObjects(a.get(b).filterBy("isNew"))}function h(a,b){return u.create({promise:D.cast(a,b)})}function i(a,b){return v.create({promise:D.cast(a,b)})}function j(a,b,c){return a.lookup("serializer:"+b)||a.lookup("serializer:application")||a.lookup("serializer:"+c)||a.lookup("serializer:-default")}function k(a){return a.lookup("serializer:application")||a.lookup("serializer:-default")}function l(a,b){var c=a.serializer,d=a.defaultSerializer,e=a.container;return e&&void 0===c&&(c=j(e,b.typeKey,d)),(null===c||void 0===c)&&(c={extract:function(a,b,c){return c}}),c}function m(a,b,c,d){var e=a.find(b,c,d),f=l(a,c),g="DS: Handle Adapter#find of "+c+" with id: "+d;return D.cast(e,g).then(function(a){var e=f.extract(b,c,a,d,"find");return b.push(c,e)},function(a){var e=b.getById(c,d);throw e.notFound(),a},"DS: Extract payload of '"+c+"'")}function n(a,b,c,d,e){var f=a.findMany(b,c,d,e),g=l(a,c),h="DS: Handle Adapter#findMany of "+c;return D.cast(f,h).then(function(a){var d=g.extract(b,c,a,null,"findMany");b.pushMany(c,d)},null,"DS: Extract payload of "+c)}function o(a,b,c,d,e){var f=a.findHasMany(b,c,d,e),g=l(a,e.type),h="DS: Handle Adapter#findHasMany of "+c+" : "+e.type;return D.cast(f,h).then(function(a){var d=g.extract(b,e.type,a,null,"findHasMany"),f=b.pushMany(e.type,d);c.updateHasMany(e.key,f)},null,"DS: Extract payload of "+c+" : hasMany "+e.type)}function p(a,b,c,d,e){var f=a.findBelongsTo(b,c,d,e),g=l(a,e.type),h="DS: Handle Adapter#findBelongsTo of "+c+" : "+e.type;return D.cast(f,h).then(function(a){var c=g.extract(b,e.type,a,null,"findBelongsTo"),d=b.push(e.type,c);return d.updateBelongsTo(e.key,d),d},null,"DS: Extract payload of "+c+" : "+e.type)}function q(a,b,c,d){var e=a.findAll(b,c,d),f=l(a,c),g="DS: Handle Adapter#findAll of "+c;return D.cast(e,g).then(function(a){var d=f.extract(b,c,a,null,"findAll");return b.pushMany(c,d),b.didUpdateAll(c),b.all(c)},null,"DS: Extract payload of findAll "+c)}function r(a,b,c,d,e){var f=a.findQuery(b,c,d,e),g=l(a,c),h="DS: Handle Adapter#findQuery of "+c;return D.cast(f,h).then(function(a){var d=g.extract(b,c,a,null,"findQuery");return e.load(d),e},null,"DS: Extract payload of findQuery "+c)}function s(a,b,c,d){var e=d.constructor,f=a[c](b,e,d),g=l(a,e),h="DS: Extract and notify about "+c+" completion of "+d;return f.then(function(a){var f;return f=a?g.extract(b,e,a,w(d,"id"),c):a,b.didSaveRecord(d,f),d},function(a){throw a instanceof DS.InvalidError?b.recordWasInvalid(d,a.errors):b.recordWasError(d,a),a},h)}var t,u,v,w=Ember.get,x=Ember.set,y=Ember.run.once,z=Ember.isNone,A=Ember.EnumerableUtils.forEach,B=Ember.EnumerableUtils.indexOf,C=Ember.EnumerableUtils.map,D=Ember.RSVP.Promise,E=Ember.copy;t=Ember.Object.extend({init:function(){this.typeMaps={},this.recordArrayManager=DS.RecordArrayManager.create({store:this}),this._relationshipChanges={},this._pendingSave=[]},adapter:"-rest",serialize:function(a,b){return this.serializerFor(a.constructor.typeKey).serialize(a,b)},defaultAdapter:Ember.computed("adapter",function(){var a=w(this,"adapter");return"string"==typeof a&&(a=this.container.lookup("adapter:"+a)||this.container.lookup("adapter:application")||this.container.lookup("adapter:-rest")),DS.Adapter.detect(a)&&(a=a.create({container:this.container})),a}),createRecord:function(a,c){a=this.modelFor(a),c=E(c)||{},z(c.id)&&(c.id=this._generateId(a)),c.id=b(c.id);var d=this.buildRecord(a,c.id);return d.loadedData(),d.setProperties(c),d},_generateId:function(a){var b=this.adapterFor(a);return b&&b.generateIdForRecord?b.generateIdForRecord(this):null},deleteRecord:function(a){a.deleteRecord()},unloadRecord:function(a){a.unloadRecord()},find:function(a,c){return 1===arguments.length?this.findAll(a):"object"===Ember.typeOf(c)?this.findQuery(a,c):this.findById(a,b(c))},findById:function(a,b){a=this.modelFor(a);var c=this.recordForId(a,b),d=this.fetchRecord(c);return h(d||c,"DS: Store#findById "+a+" with id: "+b)},findByIds:function(a,b){var c=this;return i(Ember.RSVP.all(C(b,function(b){return c.findById(a,b)})).then(Ember.A,null,"DS: Store#findByIds of "+a+" complete"))},fetchRecord:function(a){if(z(a))return null;if(a._loadingPromise)return a._loadingPromise;if(!w(a,"isEmpty"))return null;var b=a.constructor,c=w(a,"id"),d=this.adapterFor(b),e=m(d,this,b,c);return a.loadingData(e),e},getById:function(a,b){return this.hasRecordForId(a,b)?this.recordForId(a,b):null},reloadRecord:function(a){var b=a.constructor,c=this.adapterFor(b),d=w(a,"id");return m(c,this,b,d)},fetchMany:function(a,b,c){if(a.length){var d=Ember.MapWithDefault.create({defaultValue:function(){return Ember.A()}});A(a,function(a){d.get(a.constructor).push(a)});var e=[];A(d,function(a,c){var d=c.mapProperty("id"),f=this.adapterFor(a);e.push(n(f,this,a,d,b))},this),c.resolve(Ember.RSVP.all(e))}},hasRecordForId:function(a,c){return c=b(c),a=this.modelFor(a),!!this.typeMapFor(a).idToRecord[c]},recordForId:function(a,c){a=this.modelFor(a),c=b(c);var d=this.typeMapFor(a).idToRecord[c];return d||(d=this.buildRecord(a,c)),d},findMany:function(a,b,c,d){c=this.modelFor(c),b=Ember.A(b);var e=b.filterProperty("isEmpty",!0),f=this.recordArrayManager.createManyArray(c,b);return A(e,function(a){a.loadingData()}),f.loadingRecordsCount=e.length,e.length?(A(e,function(a){this.recordArrayManager.registerWaitingRecordArray(a,f)},this),this.fetchMany(e,a,d)):(d&&d.resolve(),f.set("isLoaded",!0),y(f,"trigger","didLoad")),f},findHasMany:function(a,b,c,d){var e=this.adapterFor(a.constructor),f=this.recordArrayManager.createManyArray(c.type,Ember.A([]));return d.resolve(o(e,this,a,b,c)),f},findBelongsTo:function(a,b,c,d){var e=this.adapterFor(a.constructor);d.resolve(p(e,this,a,b,c))},findQuery:function(a,b){a=this.modelFor(a);var c=this.recordArrayManager.createAdapterPopulatedRecordArray(a,b),d=this.adapterFor(a);return i(r(d,this,a,b,c))},findAll:function(a){return a=this.modelFor(a),this.fetchAll(a,this.all(a))},fetchAll:function(a,b){var c=this.adapterFor(a),d=this.typeMapFor(a).metadata.since;return x(b,"isUpdating",!0),i(q(c,this,a,d))},didUpdateAll:function(a){var b=this.typeMapFor(a).findAllCache;x(b,"isUpdating",!1)},all:function(a){a=this.modelFor(a);var b=this.typeMapFor(a),c=b.findAllCache;if(c)return c;var d=this.recordArrayManager.createRecordArray(a);return b.findAllCache=d,d},unloadAll:function(a){a=this.modelFor(a);for(var b,c=this.typeMapFor(a),d=c.records.splice(0);b=d.pop();)b.unloadRecord();c.findAllCache=null},filter:function(a,b,c){var d;3===arguments.length?d=this.findQuery(a,b):2===arguments.length&&(c=b),a=this.modelFor(a); +var e=this.recordArrayManager.createFilteredRecordArray(a,c);return d=d||D.cast(e),i(d.then(function(){return e},null,"DS: Store#filter of "+a))},recordIsLoaded:function(a,b){return this.hasRecordForId(a,b)?!w(this.recordForId(a,b),"isEmpty"):!1},metadataFor:function(a){return a=this.modelFor(a),this.typeMapFor(a).metadata},dataWasUpdated:function(a,b){this.recordArrayManager.recordDidChange(b)},scheduleSave:function(a,b){a.adapterWillCommit(),this._pendingSave.push([a,b]),y(this,"flushPendingSave")},flushPendingSave:function(){var a=this._pendingSave.slice();this._pendingSave=[],A(a,function(a){var b,c=a[0],d=a[1],e=this.adapterFor(c.constructor);b=w(c,"isNew")?"createRecord":w(c,"isDeleted")?"deleteRecord":"updateRecord",d.resolve(s(e,this,b,c))},this)},didSaveRecord:function(a,b){b&&(b=c(this,a.constructor,b,a),this.updateId(a,b)),a.adapterDidCommit(b)},recordWasInvalid:function(a,b){a.adapterDidInvalidate(b)},recordWasError:function(a){a.adapterDidError()},updateId:function(a,c){var d=(w(a,"id"),b(c.id));this.typeMapFor(a.constructor).idToRecord[d]=a,x(a,"id",d)},typeMapFor:function(a){var b,c=w(this,"typeMaps"),d=Ember.guidFor(a);return(b=c[d])?b:(b={idToRecord:{},records:[],metadata:{}},c[d]=b,b)},_load:function(a,c,d){var e=b(c.id),f=this.recordForId(a,e);return f.setupData(c,d),this.recordArrayManager.recordDidChange(f),f},modelFor:function(a){var b;if("string"==typeof a){var c=this.container.normalize("model:"+a);if(b=this.container.lookupFactory(c),!b)throw new Ember.Error("No model was found for '"+a+"'");b.typeKey=c.split(":",2)[1]}else b=a;return b.store=this,b},push:function(a,b,d){return a=this.modelFor(a),b=c(this,a,b),this._load(a,b,d),this.recordForId(a,b.id)},pushPayload:function(a,b){var c;b?c=this.serializerFor(a):(b=a,c=k(this.container)),c.pushPayload(this,b)},update:function(a,b){return this.push(a,b,!0)},pushMany:function(a,b){return C(b,function(b){return this.push(a,b)},this)},metaForType:function(a,b){a=this.modelFor(a),Ember.merge(this.typeMapFor(a).metadata,b)},buildRecord:function(a,b,c){var d=this.typeMapFor(a),e=d.idToRecord,f=a._create({id:b,store:this,container:this.container});return c&&f.setupData(c),b&&(e[b]=f),d.records.push(f),f},dematerializeRecord:function(a){var b=a.constructor,c=this.typeMapFor(b),d=w(a,"id");a.updateRecordArrays(),d&&delete c.idToRecord[d];var e=B(c.records,a);c.records.splice(e,1)},addRelationshipChangeFor:function(a,b,c,d,e){var f=a.clientId,g=c?c:c,h=b+d,i=this._relationshipChanges;f in i||(i[f]={}),g in i[f]||(i[f][g]={}),h in i[f][g]||(i[f][g][h]={}),i[f][g][h][e.changeType]=e},removeRelationshipChangeFor:function(a,b,c,d,e){var f=a.clientId,g=c?c.clientId:c,h=this._relationshipChanges,i=b+d;f in h&&g in h[f]&&i in h[f][g]&&delete h[f][g][i][e]},relationshipChangePairsFor:function(a){var b=[];if(!a)return b;var c=this._relationshipChanges[a.clientId];for(var d in c)if(c.hasOwnProperty(d))for(var e in c[d])c[d].hasOwnProperty(e)&&b.push(c[d][e]);return b},adapterFor:function(a){var b,c=this.container;return c&&(b=c.lookup("adapter:"+a.typeKey)||c.lookup("adapter:application")),b||w(this,"defaultAdapter")},serializerFor:function(a){a=this.modelFor(a);var b=this.adapterFor(a);return j(this.container,a.typeKey,b&&b.defaultSerializer)}}),v=Ember.ArrayProxy.extend(Ember.PromiseProxyMixin),u=Ember.ObjectProxy.extend(Ember.PromiseProxyMixin),a.Store=t,a.PromiseArray=v,a.PromiseObject=u,a["default"]=t}),b("ember-data/lib/transforms",["./transforms/base","./transforms/number","./transforms/date","./transforms/string","./transforms/boolean","exports"],function(a,b,c,d,e,f){"use strict";var g=a["default"],h=b["default"],i=c["default"],j=d["default"],k=e["default"];f.Transform=g,f.NumberTransform=h,f.DateTransform=i,f.StringTransform=j,f.BooleanTransform=k}),b("ember-data/lib/transforms/base",["exports"],function(a){"use strict";var b=Ember.Object.extend({serialize:Ember.required(),deserialize:Ember.required()});a["default"]=b}),b("ember-data/lib/transforms/boolean",["./base","exports"],function(a,b){"use strict";var c=a["default"],d=c.extend({deserialize:function(a){var b=typeof a;return"boolean"===b?a:"string"===b?null!==a.match(/^true$|^t$|^1$/i):"number"===b?1===a:!1},serialize:function(a){return Boolean(a)}});b["default"]=d}),b("ember-data/lib/transforms/date",["./base","exports"],function(a,b){"use strict";var c=a["default"],d=c.extend({deserialize:function(a){var b=typeof a;return"string"===b?new Date(Ember.Date.parse(a)):"number"===b?new Date(a):null===a||void 0===a?a:null},serialize:function(a){if(a instanceof Date){var b=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],d=function(a){return 10>a?"0"+a:""+a},e=a.getUTCFullYear(),f=a.getUTCMonth(),g=a.getUTCDate(),h=a.getUTCDay(),i=a.getUTCHours(),j=a.getUTCMinutes(),k=a.getUTCSeconds(),l=b[h],m=d(g),n=c[f];return l+", "+m+" "+n+" "+e+" "+d(i)+":"+d(j)+":"+d(k)+" GMT"}return null}});b["default"]=d}),b("ember-data/lib/transforms/number",["./base","exports"],function(a,b){"use strict";var c=a["default"],d=Ember.isEmpty,e=c.extend({deserialize:function(a){return d(a)?null:Number(a)},serialize:function(a){return d(a)?null:Number(a)}});b["default"]=e}),b("ember-data/lib/transforms/string",["./base","exports"],function(a,b){"use strict";var c=a["default"],d=Ember.isNone,e=c.extend({deserialize:function(a){return d(a)?null:String(a)},serialize:function(a){return d(a)?null:String(a)}});b["default"]=e}),b("ember-inflector/lib/ext/string",["../system/string"],function(a){"use strict";var b=a.pluralize,c=a.singularize;(Ember.EXTEND_PROTOTYPES===!0||Ember.EXTEND_PROTOTYPES.String)&&(String.prototype.pluralize=function(){return b(this)},String.prototype.singularize=function(){return c(this)})}),b("ember-inflector/lib/main",["./system","./ext/string","exports"],function(a,b,c){"use strict";var d=a.Inflector,e=a.inflections,f=a.pluralize,g=a.singularize;d.defaultRules=e,Ember.Inflector=d,Ember.String.pluralize=f,Ember.String.singularize=g,c["default"]=d,c.pluralize=f,c.singularize=g}),b("ember-inflector/lib/system",["./system/inflector","./system/string","./system/inflections","exports"],function(a,b,c,d){"use strict";var e=a["default"],f=b.pluralize,g=b.singularize,h=c["default"];e.inflector=new e(h),d.Inflector=e,d.singularize=g,d.pluralize=f,d.defaultRules=h}),b("ember-inflector/lib/system/inflections",["exports"],function(a){"use strict";var b={plurals:[[/$/,"s"],[/s$/i,"s"],[/^(ax|test)is$/i,"$1es"],[/(octop|vir)us$/i,"$1i"],[/(octop|vir)i$/i,"$1i"],[/(alias|status)$/i,"$1es"],[/(bu)s$/i,"$1ses"],[/(buffal|tomat)o$/i,"$1oes"],[/([ti])um$/i,"$1a"],[/([ti])a$/i,"$1a"],[/sis$/i,"ses"],[/(?:([^f])fe|([lr])f)$/i,"$1$2ves"],[/(hive)$/i,"$1s"],[/([^aeiouy]|qu)y$/i,"$1ies"],[/(x|ch|ss|sh)$/i,"$1es"],[/(matr|vert|ind)(?:ix|ex)$/i,"$1ices"],[/^(m|l)ouse$/i,"$1ice"],[/^(m|l)ice$/i,"$1ice"],[/^(ox)$/i,"$1en"],[/^(oxen)$/i,"$1"],[/(quiz)$/i,"$1zes"]],singular:[[/s$/i,""],[/(ss)$/i,"$1"],[/(n)ews$/i,"$1ews"],[/([ti])a$/i,"$1um"],[/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i,"$1sis"],[/(^analy)(sis|ses)$/i,"$1sis"],[/([^f])ves$/i,"$1fe"],[/(hive)s$/i,"$1"],[/(tive)s$/i,"$1"],[/([lr])ves$/i,"$1f"],[/([^aeiouy]|qu)ies$/i,"$1y"],[/(s)eries$/i,"$1eries"],[/(m)ovies$/i,"$1ovie"],[/(x|ch|ss|sh)es$/i,"$1"],[/^(m|l)ice$/i,"$1ouse"],[/(bus)(es)?$/i,"$1"],[/(o)es$/i,"$1"],[/(shoe)s$/i,"$1"],[/(cris|test)(is|es)$/i,"$1is"],[/^(a)x[ie]s$/i,"$1xis"],[/(octop|vir)(us|i)$/i,"$1us"],[/(alias|status)(es)?$/i,"$1"],[/^(ox)en/i,"$1"],[/(vert|ind)ices$/i,"$1ex"],[/(matr)ices$/i,"$1ix"],[/(quiz)zes$/i,"$1"],[/(database)s$/i,"$1"]],irregularPairs:[["person","people"],["man","men"],["child","children"],["sex","sexes"],["move","moves"],["cow","kine"],["zombie","zombies"]],uncountable:["equipment","information","rice","money","species","series","fish","sheep","jeans","police"]};a["default"]=b}),b("ember-inflector/lib/system/inflector",["exports"],function(a){"use strict";function b(a,b){for(var c=0,d=b.length;d>c;c++)a.uncountable[b[c].toLowerCase()]=!0}function c(a,b){for(var c,d=0,e=b.length;e>d;d++)c=b[d],a.irregular[c[0].toLowerCase()]=c[1],a.irregularInverse[c[1].toLowerCase()]=c[0]}function d(a){a=a||{},a.uncountable=a.uncountable||{},a.irregularPairs=a.irregularPairs||{};var d=this.rules={plurals:a.plurals||[],singular:a.singular||[],irregular:{},irregularInverse:{},uncountable:{}};b(d,a.uncountable),c(d,a.irregularPairs)}var e=/^\s*$/;d.prototype={plural:function(a,b){this.rules.plurals.push([a,b.toLowerCase()])},singular:function(a,b){this.rules.singular.push([a,b.toLowerCase()])},uncountable:function(a){b(this.rules,[a.toLowerCase()])},irregular:function(a,b){c(this.rules,[[a,b]])},pluralize:function(a){return this.inflect(a,this.rules.plurals,this.rules.irregular)},singularize:function(a){return this.inflect(a,this.rules.singular,this.rules.irregularInverse)},inflect:function(a,b,c){var d,f,g,h,i,j,k,l;if(i=e.test(a))return a;if(h=a.toLowerCase(),j=this.rules.uncountable[h])return a;if(k=c&&c[h])return k;for(var m=b.length,n=0;m>n&&(d=b[m-1],l=d[0],!l.test(a));m--);return d=d||[],l=d[0],f=d[1],g=a.replace(l,f)}},a["default"]=d}),b("ember-inflector/lib/system/string",["./inflector","exports"],function(a,b){"use strict";var c=a["default"],d=function(a){return c.inflector.pluralize(a)},e=function(a){return c.inflector.singularize(a)};b.pluralize=d,b.singularize=e}),a.DS=c("ember-data/lib/main")["default"]}(window); \ No newline at end of file diff --git a/perf/todomvc-benchmark/todomvc/architecture-examples/emberjs/bower_components/ember-data/ember-data.prod.js b/perf/todomvc-benchmark/todomvc/architecture-examples/emberjs/bower_components/ember-data/ember-data.prod.js deleted file mode 100644 index e5fc6f68da..0000000000 --- a/perf/todomvc-benchmark/todomvc/architecture-examples/emberjs/bower_components/ember-data/ember-data.prod.js +++ /dev/null @@ -1,10626 +0,0 @@ -/*! - * @overview Ember Data - * @copyright Copyright 2011-2014 Tilde Inc. and contributors. - * Portions Copyright 2011 LivingSocial Inc. - * @license Licensed under MIT license (see license.js) - * @version 1.0.0-beta.6 - */ - - -(function() { -var define, requireModule; - -(function() { - var registry = {}, seen = {}; - - define = function(name, deps, callback) { - registry[name] = { deps: deps, callback: callback }; - }; - - requireModule = function(name) { - if (seen[name]) { return seen[name]; } - seen[name] = {}; - - var mod, deps, callback, reified , exports; - - mod = registry[name]; - - if (!mod) { - throw new Error("Module '" + name + "' not found."); - } - - deps = mod.deps; - callback = mod.callback; - reified = []; - exports; - - for (var i=0, l=deps.length; i 0; i--) { - var proxyPair = proxyPairs[i - 1], - deprecated = proxyPair['deprecated'], - valid = proxyPair['valid']; - - this.registerDeprecation(deprecated, valid); - } -}; - -DS.ContainerProxy = ContainerProxy; - -})(); - - - -(function() { -var get = Ember.get, set = Ember.set, isNone = Ember.isNone; - -// Simple dispatcher to support overriding the aliased -// method in subclasses. -function aliasMethod(methodName) { - return function() { - return this[methodName].apply(this, arguments); - }; -} - -/** - In Ember Data a Serializer is used to serialize and deserialize - records when they are transferred in and out of an external source. - This process involves normalizing property names, transforming - attribute values and serializing relationships. - - For maximum performance Ember Data recommends you use the - [RESTSerializer](DS.RESTSerializer.html) or one of its subclasses. - - `JSONSerializer` is useful for simpler or legacy backends that may - not support the http://jsonapi.org/ spec. - - @class JSONSerializer - @namespace DS -*/ -DS.JSONSerializer = Ember.Object.extend({ - /** - The primaryKey is used when serializing and deserializing - data. Ember Data always uses the `id` property to store the id of - the record. The external source may not always follow this - convention. In these cases it is useful to override the - primaryKey property to match the primaryKey of your external - store. - - Example - - ```javascript - App.ApplicationSerializer = DS.JSONSerializer.extend({ - primaryKey: '_id' - }); - ``` - - @property primaryKey - @type {String} - @default 'id' - */ - primaryKey: 'id', - - /** - Given a subclass of `DS.Model` and a JSON object this method will - iterate through each attribute of the `DS.Model` and invoke the - `DS.Transform#deserialize` method on the matching property of the - JSON object. This method is typically called after the - serializer's `normalize` method. - - @method applyTransforms - @private - @param {subclass of DS.Model} type - @param {Object} data The data to transform - @return {Object} data The transformed data object - */ - applyTransforms: function(type, data) { - type.eachTransformedAttribute(function(key, type) { - var transform = this.transformFor(type); - data[key] = transform.deserialize(data[key]); - }, this); - - return data; - }, - - /** - Normalizes a part of the JSON payload returned by - the server. You should override this method, munge the hash - and call super if you have generic normalization to do. - - It takes the type of the record that is being normalized - (as a DS.Model class), the property where the hash was - originally found, and the hash to normalize. - - You can use this method, for example, to normalize underscored keys to camelized - or other general-purpose normalizations. - - Example - - ```javascript - App.ApplicationSerializer = DS.JSONSerializer.extend({ - normalize: function(type, hash) { - var fields = Ember.get(type, 'fields'); - fields.forEach(function(field) { - var payloadField = Ember.String.underscore(field); - if (field === payloadField) { return; } - - hash[field] = hash[payloadField]; - delete hash[payloadField]; - }); - return this._super.apply(this, arguments); - } - }); - ``` - - @method normalize - @param {subclass of DS.Model} type - @param {Object} hash - @return {Object} - */ - normalize: function(type, hash) { - if (!hash) { return hash; } - - this.applyTransforms(type, hash); - return hash; - }, - - // SERIALIZE - /** - Called when a record is saved in order to convert the - record into JSON. - - By default, it creates a JSON object with a key for - each attribute and belongsTo relationship. - - For example, consider this model: - - ```javascript - App.Comment = DS.Model.extend({ - title: DS.attr(), - body: DS.attr(), - - author: DS.belongsTo('user') - }); - ``` - - The default serialization would create a JSON object like: - - ```javascript - { - "title": "Rails is unagi", - "body": "Rails? Omakase? O_O", - "author": 12 - } - ``` - - By default, attributes are passed through as-is, unless - you specified an attribute type (`DS.attr('date')`). If - you specify a transform, the JavaScript value will be - serialized when inserted into the JSON hash. - - By default, belongs-to relationships are converted into - IDs when inserted into the JSON hash. - - ## IDs - - `serialize` takes an options hash with a single option: - `includeId`. If this option is `true`, `serialize` will, - by default include the ID in the JSON object it builds. - - The adapter passes in `includeId: true` when serializing - a record for `createRecord`, but not for `updateRecord`. - - ## Customization - - Your server may expect a different JSON format than the - built-in serialization format. - - In that case, you can implement `serialize` yourself and - return a JSON hash of your choosing. - - ```javascript - App.PostSerializer = DS.JSONSerializer.extend({ - serialize: function(post, options) { - var json = { - POST_TTL: post.get('title'), - POST_BDY: post.get('body'), - POST_CMS: post.get('comments').mapProperty('id') - } - - if (options.includeId) { - json.POST_ID_ = post.get('id'); - } - - return json; - } - }); - ``` - - ## Customizing an App-Wide Serializer - - If you want to define a serializer for your entire - application, you'll probably want to use `eachAttribute` - and `eachRelationship` on the record. - - ```javascript - App.ApplicationSerializer = DS.JSONSerializer.extend({ - serialize: function(record, options) { - var json = {}; - - record.eachAttribute(function(name) { - json[serverAttributeName(name)] = record.get(name); - }) - - record.eachRelationship(function(name, relationship) { - if (relationship.kind === 'hasMany') { - json[serverHasManyName(name)] = record.get(name).mapBy('id'); - } - }); - - if (options.includeId) { - json.ID_ = record.get('id'); - } - - return json; - } - }); - - function serverAttributeName(attribute) { - return attribute.underscore().toUpperCase(); - } - - function serverHasManyName(name) { - return serverAttributeName(name.singularize()) + "_IDS"; - } - ``` - - This serializer will generate JSON that looks like this: - - ```javascript - { - "TITLE": "Rails is omakase", - "BODY": "Yep. Omakase.", - "COMMENT_IDS": [ 1, 2, 3 ] - } - ``` - - ## Tweaking the Default JSON - - If you just want to do some small tweaks on the default JSON, - you can call super first and make the tweaks on the returned - JSON. - - ```javascript - App.PostSerializer = DS.JSONSerializer.extend({ - serialize: function(record, options) { - var json = this._super.apply(this, arguments); - - json.subject = json.title; - delete json.title; - - return json; - } - }); - ``` - - @method serialize - @param {subclass of DS.Model} record - @param {Object} options - @return {Object} json - */ - serialize: function(record, options) { - var json = {}; - - if (options && options.includeId) { - var id = get(record, 'id'); - - if (id) { - json[get(this, 'primaryKey')] = id; - } - } - - record.eachAttribute(function(key, attribute) { - this.serializeAttribute(record, json, key, attribute); - }, this); - - record.eachRelationship(function(key, relationship) { - if (relationship.kind === 'belongsTo') { - this.serializeBelongsTo(record, json, relationship); - } else if (relationship.kind === 'hasMany') { - this.serializeHasMany(record, json, relationship); - } - }, this); - - return json; - }, - - /** - `serializeAttribute` can be used to customize how `DS.attr` - properties are serialized - - For example if you wanted to ensure all you attributes were always - serialized as properties on an `attributes` object you could - write: - - ```javascript - App.ApplicationSerializer = DS.JSONSerializer.extend({ - serializeAttribute: function(record, json, key, attributes) { - json.attributes = json.attributes || {}; - this._super(record, json.attributes, key, attributes); - } - }); - ``` - - @method serializeAttribute - @param {DS.Model} record - @param {Object} json - @param {String} key - @param {Object} attribute - */ - serializeAttribute: function(record, json, key, attribute) { - var attrs = get(this, 'attrs'); - var value = get(record, key), type = attribute.type; - - if (type) { - var transform = this.transformFor(type); - value = transform.serialize(value); - } - - // if provided, use the mapping provided by `attrs` in - // the serializer - key = attrs && attrs[key] || (this.keyForAttribute ? this.keyForAttribute(key) : key); - - json[key] = value; - }, - - /** - `serializeBelongsTo` can be used to customize how `DS.belongsTo` - properties are serialized. - - Example - - ```javascript - App.PostSerializer = DS.JSONSerializer.extend({ - serializeBelongsTo: function(record, json, relationship) { - var key = relationship.key; - - var belongsTo = get(record, key); - - key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key; - - json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.toJSON(); - } - }); - ``` - - @method serializeBelongsTo - @param {DS.Model} record - @param {Object} json - @param {Object} relationship - */ - serializeBelongsTo: function(record, json, relationship) { - var key = relationship.key; - - var belongsTo = get(record, key); - - key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key; - - if (isNone(belongsTo)) { - json[key] = belongsTo; - } else { - json[key] = get(belongsTo, 'id'); - } - - if (relationship.options.polymorphic) { - this.serializePolymorphicType(record, json, relationship); - } - }, - - /** - `serializeHasMany` can be used to customize how `DS.hasMany` - properties are serialized. - - Example - - ```javascript - App.PostSerializer = DS.JSONSerializer.extend({ - serializeHasMany: function(record, json, relationship) { - var key = relationship.key; - if (key === 'comments') { - return; - } else { - this._super.apply(this, arguments); - } - } - }); - ``` - - @method serializeHasMany - @param {DS.Model} record - @param {Object} json - @param {Object} relationship - */ - serializeHasMany: function(record, json, relationship) { - var key = relationship.key; - - var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship); - - if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') { - json[key] = get(record, key).mapBy('id'); - // TODO support for polymorphic manyToNone and manyToMany relationships - } - }, - - /** - You can use this method to customize how polymorphic objects are - serialized. Objects are considered to be polymorphic if - `{polymorphic: true}` is pass as the second argument to the - `DS.belongsTo` function. - - Example - - ```javascript - App.CommentSerializer = DS.JSONSerializer.extend({ - serializePolymorphicType: function(record, json, relationship) { - var key = relationship.key, - belongsTo = get(record, key); - key = this.keyForAttribute ? this.keyForAttribute(key) : key; - json[key + "_type"] = belongsTo.constructor.typeKey; - } - }); - ``` - - @method serializePolymorphicType - @param {DS.Model} record - @param {Object} json - @param {Object} relationship - */ - serializePolymorphicType: Ember.K, - - // EXTRACT - - /** - The `extract` method is used to deserialize payload data from the - server. By default the `JSONSerializer` does not push the records - into the store. However records that subclass `JSONSerializer` - such as the `RESTSerializer` may push records into the store as - part of the extract call. - - This method delegates to a more specific extract method based on - the `requestType`. - - Example - - ```javascript - var get = Ember.get; - socket.on('message', function(message) { - var modelName = message.model; - var data = message.data; - var type = store.modelFor(modelName); - var serializer = store.serializerFor(type.typeKey); - var record = serializer.extract(store, type, data, get(data, 'id'), 'single'); - store.push(modelName, record); - }); - ``` - - @method extract - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {Object} payload - @param {String or Number} id - @param {String} requestType - @return {Object} json The deserialized payload - */ - extract: function(store, type, payload, id, requestType) { - this.extractMeta(store, type, payload); - - var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1); - return this[specificExtract](store, type, payload, id, requestType); - }, - - /** - `extractFindAll` is a hook into the extract method used when a - call is made to `DS.Store#findAll`. By default this method is an - alias for [extractArray](#method_extractArray). - - @method extractFindAll - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {Object} payload - @return {Array} array An array of deserialized objects - */ - extractFindAll: aliasMethod('extractArray'), - /** - `extractFindQuery` is a hook into the extract method used when a - call is made to `DS.Store#findQuery`. By default this method is an - alias for [extractArray](#method_extractArray). - - @method extractFindQuery - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {Object} payload - @return {Array} array An array of deserialized objects - */ - extractFindQuery: aliasMethod('extractArray'), - /** - `extractFindMany` is a hook into the extract method used when a - call is made to `DS.Store#findMany`. By default this method is - alias for [extractArray](#method_extractArray). - - @method extractFindMany - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {Object} payload - @return {Array} array An array of deserialized objects - */ - extractFindMany: aliasMethod('extractArray'), - /** - `extractFindHasMany` is a hook into the extract method used when a - call is made to `DS.Store#findHasMany`. By default this method is - alias for [extractArray](#method_extractArray). - - @method extractFindHasMany - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {Object} payload - @return {Array} array An array of deserialized objects - */ - extractFindHasMany: aliasMethod('extractArray'), - - /** - `extractCreateRecord` is a hook into the extract method used when a - call is made to `DS.Store#createRecord`. By default this method is - alias for [extractSave](#method_extractSave). - - @method extractCreateRecord - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {Object} payload - @return {Object} json The deserialized payload - */ - extractCreateRecord: aliasMethod('extractSave'), - /** - `extractUpdateRecord` is a hook into the extract method used when - a call is made to `DS.Store#update`. By default this method is alias - for [extractSave](#method_extractSave). - - @method extractUpdateRecord - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {Object} payload - @return {Object} json The deserialized payload - */ - extractUpdateRecord: aliasMethod('extractSave'), - /** - `extractDeleteRecord` is a hook into the extract method used when - a call is made to `DS.Store#deleteRecord`. By default this method is - alias for [extractSave](#method_extractSave). - - @method extractDeleteRecord - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {Object} payload - @return {Object} json The deserialized payload - */ - extractDeleteRecord: aliasMethod('extractSave'), - - /** - `extractFind` is a hook into the extract method used when - a call is made to `DS.Store#find`. By default this method is - alias for [extractSingle](#method_extractSingle). - - @method extractFind - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {Object} payload - @return {Object} json The deserialized payload - */ - extractFind: aliasMethod('extractSingle'), - /** - `extractFindBelongsTo` is a hook into the extract method used when - a call is made to `DS.Store#findBelongsTo`. By default this method is - alias for [extractSingle](#method_extractSingle). - - @method extractFindBelongsTo - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {Object} payload - @return {Object} json The deserialized payload - */ - extractFindBelongsTo: aliasMethod('extractSingle'), - /** - `extractSave` is a hook into the extract method used when a call - is made to `DS.Model#save`. By default this method is alias - for [extractSingle](#method_extractSingle). - - @method extractSave - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {Object} payload - @return {Object} json The deserialized payload - */ - extractSave: aliasMethod('extractSingle'), - - /** - `extractSingle` is used to deserialize a single record returned - from the adapter. - - Example - - ```javascript - App.PostSerializer = DS.JSONSerializer.extend({ - extractSingle: function(store, type, payload) { - payload.comments = payload._embedded.comment; - delete payload._embedded; - - return this._super(store, type, payload); - }, - }); - ``` - - @method extractSingle - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {Object} payload - @return {Object} json The deserialized payload - */ - extractSingle: function(store, type, payload) { - return this.normalize(type, payload); - }, - - /** - `extractArray` is used to deserialize an array of records - returned from the adapter. - - Example - - ```javascript - App.PostSerializer = DS.JSONSerializer.extend({ - extractArray: function(store, type, payload) { - return payload.map(function(json) { - return this.extractSingle(json); - }, this); - } - }); - ``` - - @method extractArray - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {Object} payload - @return {Array} array An array of deserialized objects - */ - extractArray: function(store, type, payload) { - return this.normalize(type, payload); - }, - - /** - `extractMeta` is used to deserialize any meta information in the - adapter payload. By default Ember Data expects meta information to - be located on the `meta` property of the payload object. - - Example - - ```javascript - App.PostSerializer = DS.JSONSerializer.extend({ - extractMeta: function(store, type, payload) { - if (payload && payload._pagination) { - store.metaForType(type, payload._pagination); - delete payload._pagination; - } - } - }); - ``` - - @method extractMeta - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {Object} payload - */ - extractMeta: function(store, type, payload) { - if (payload && payload.meta) { - store.metaForType(type, payload.meta); - delete payload.meta; - } - }, - - /** - `keyForAttribute` can be used to define rules for how to convert an - attribute name in your model to a key in your JSON. - - Example - - ```javascript - App.ApplicationSerializer = DS.RESTSerializer.extend({ - keyForAttribute: function(attr) { - return Ember.String.underscore(attr).toUpperCase(); - } - }); - ``` - - @method keyForAttribute - @param {String} key - @return {String} normalized key - */ - - - /** - `keyForRelationship` can be used to define a custom key when - serializing relationship properties. By default `JSONSerializer` - does not provide an implementation of this method. - - Example - - ```javascript - App.PostSerializer = DS.JSONSerializer.extend({ - keyForRelationship: function(key, relationship) { - return 'rel_' + Ember.String.underscore(key); - } - }); - ``` - - @method keyForRelationship - @param {String} key - @param {String} relationship type - @return {String} normalized key - */ - - // HELPERS - - /** - @method transformFor - @private - @param {String} attributeType - @param {Boolean} skipAssertion - @return {DS.Transform} transform - */ - transformFor: function(attributeType, skipAssertion) { - var transform = this.container.lookup('transform:' + attributeType); - Ember.assert("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform); - return transform; - } -}); - -})(); - - - -(function() { -/** - @module ember-data -*/ -var get = Ember.get, capitalize = Ember.String.capitalize, underscore = Ember.String.underscore, DS = window.DS ; - -/** - Extend `Ember.DataAdapter` with ED specific code. - - @class DebugAdapter - @namespace DS - @extends Ember.DataAdapter - @private -*/ -DS.DebugAdapter = Ember.DataAdapter.extend({ - getFilters: function() { - return [ - { name: 'isNew', desc: 'New' }, - { name: 'isModified', desc: 'Modified' }, - { name: 'isClean', desc: 'Clean' } - ]; - }, - - detect: function(klass) { - return klass !== DS.Model && DS.Model.detect(klass); - }, - - columnsForType: function(type) { - var columns = [{ name: 'id', desc: 'Id' }], count = 0, self = this; - get(type, 'attributes').forEach(function(name, meta) { - if (count++ > self.attributeLimit) { return false; } - var desc = capitalize(underscore(name).replace('_', ' ')); - columns.push({ name: name, desc: desc }); - }); - return columns; - }, - - getRecords: function(type) { - return this.get('store').all(type); - }, - - getRecordColumnValues: function(record) { - var self = this, count = 0, - columnValues = { id: get(record, 'id') }; - - record.eachAttribute(function(key) { - if (count++ > self.attributeLimit) { - return false; - } - var value = get(record, key); - columnValues[key] = value; - }); - return columnValues; - }, - - getRecordKeywords: function(record) { - var keywords = [], keys = Ember.A(['id']); - record.eachAttribute(function(key) { - keys.push(key); - }); - keys.forEach(function(key) { - keywords.push(get(record, key)); - }); - return keywords; - }, - - getRecordFilterValues: function(record) { - return { - isNew: record.get('isNew'), - isModified: record.get('isDirty') && !record.get('isNew'), - isClean: !record.get('isDirty') - }; - }, - - getRecordColor: function(record) { - var color = 'black'; - if (record.get('isNew')) { - color = 'green'; - } else if (record.get('isDirty')) { - color = 'blue'; - } - return color; - }, - - observeRecord: function(record, recordUpdated) { - var releaseMethods = Ember.A(), self = this, - keysToObserve = Ember.A(['id', 'isNew', 'isDirty']); - - record.eachAttribute(function(key) { - keysToObserve.push(key); - }); - - keysToObserve.forEach(function(key) { - var handler = function() { - recordUpdated(self.wrapRecord(record)); - }; - Ember.addObserver(record, key, handler); - releaseMethods.push(function() { - Ember.removeObserver(record, key, handler); - }); - }); - - var release = function() { - releaseMethods.forEach(function(fn) { fn(); } ); - }; - - return release; - } - -}); - -})(); - - - -(function() { -/** - The `DS.Transform` class is used to serialize and deserialize model - attributes when they are saved or loaded from an - adapter. Subclassing `DS.Transform` is useful for creating custom - attributes. All subclasses of `DS.Transform` must implement a - `serialize` and a `deserialize` method. - - Example - - ```javascript - App.RawTransform = DS.Transform.extend({ - deserialize: function(serialized) { - return serialized; - }, - serialize: function(deserialized) { - return deserialized; - } - }); - ``` - - Usage - - ```javascript - var attr = DS.attr; - App.Requirement = DS.Model.extend({ - name: attr('string'), - optionsArray: attr('raw') - }); - ``` - - @class Transform - @namespace DS - */ -DS.Transform = Ember.Object.extend({ - /** - When given a deserialized value from a record attribute this - method must return the serialized value. - - Example - - ```javascript - serialize: function(deserialized) { - return Ember.isEmpty(deserialized) ? null : Number(deserialized); - } - ``` - - @method serialize - @param deserialized The deserialized value - @return The serialized value - */ - serialize: Ember.required(), - - /** - When given a serialize value from a JSON object this method must - return the deserialized value for the record attribute. - - Example - - ```javascript - deserialize: function(serialized) { - return empty(serialized) ? null : Number(serialized); - } - ``` - - @method deserialize - @param serialized The serialized value - @return The deserialized value - */ - deserialize: Ember.required() - -}); - -})(); - - - -(function() { - -/** - The `DS.BooleanTransform` class is used to serialize and deserialize - boolean attributes on Ember Data record objects. This transform is - used when `boolean` is passed as the type parameter to the - [DS.attr](../../data#method_attr) function. - - Usage - - ```javascript - var attr = DS.attr; - App.User = DS.Model.extend({ - isAdmin: attr('boolean'), - name: attr('string'), - email: attr('string') - }); - ``` - - @class BooleanTransform - @extends DS.Transform - @namespace DS - */ -DS.BooleanTransform = DS.Transform.extend({ - deserialize: function(serialized) { - var type = typeof serialized; - - if (type === "boolean") { - return serialized; - } else if (type === "string") { - return serialized.match(/^true$|^t$|^1$/i) !== null; - } else if (type === "number") { - return serialized === 1; - } else { - return false; - } - }, - - serialize: function(deserialized) { - return Boolean(deserialized); - } -}); - -})(); - - - -(function() { -/** - The `DS.DateTransform` class is used to serialize and deserialize - date attributes on Ember Data record objects. This transform is used - when `date` is passed as the type parameter to the - [DS.attr](../../data#method_attr) function. - - ```javascript - var attr = DS.attr; - App.Score = DS.Model.extend({ - value: attr('number'), - player: DS.belongsTo('player'), - date: attr('date') - }); - ``` - - @class DateTransform - @extends DS.Transform - @namespace DS - */ -DS.DateTransform = DS.Transform.extend({ - - deserialize: function(serialized) { - var type = typeof serialized; - - if (type === "string") { - return new Date(Ember.Date.parse(serialized)); - } else if (type === "number") { - return new Date(serialized); - } else if (serialized === null || serialized === undefined) { - // if the value is not present in the data, - // return undefined, not null. - return serialized; - } else { - return null; - } - }, - - serialize: function(date) { - if (date instanceof Date) { - // Serialize it as a number to maintain millisecond precision - return Number(date); - } else { - return null; - } - } - -}); - -})(); - - - -(function() { -var empty = Ember.isEmpty; -/** - The `DS.NumberTransform` class is used to serialize and deserialize - numeric attributes on Ember Data record objects. This transform is - used when `number` is passed as the type parameter to the - [DS.attr](../../data#method_attr) function. - - Usage - - ```javascript - var attr = DS.attr; - App.Score = DS.Model.extend({ - value: attr('number'), - player: DS.belongsTo('player'), - date: attr('date') - }); - ``` - - @class NumberTransform - @extends DS.Transform - @namespace DS - */ -DS.NumberTransform = DS.Transform.extend({ - - deserialize: function(serialized) { - return empty(serialized) ? null : Number(serialized); - }, - - serialize: function(deserialized) { - return empty(deserialized) ? null : Number(deserialized); - } -}); - -})(); - - - -(function() { -var none = Ember.isNone; - -/** - The `DS.StringTransform` class is used to serialize and deserialize - string attributes on Ember Data record objects. This transform is - used when `string` is passed as the type parameter to the - [DS.attr](../../data#method_attr) function. - - Usage - - ```javascript - var attr = DS.attr; - App.User = DS.Model.extend({ - isAdmin: attr('boolean'), - name: attr('string'), - email: attr('string') - }); - ``` - - @class StringTransform - @extends DS.Transform - @namespace DS - */ -DS.StringTransform = DS.Transform.extend({ - - deserialize: function(serialized) { - return none(serialized) ? null : String(serialized); - }, - - serialize: function(deserialized) { - return none(deserialized) ? null : String(deserialized); - } - -}); - -})(); - - - -(function() { - -})(); - - - -(function() { -/** - @module ember-data -*/ - -var set = Ember.set; - -/* - This code registers an injection for Ember.Application. - - If an Ember.js developer defines a subclass of DS.Store on their application, - this code will automatically instantiate it and make it available on the - router. - - Additionally, after an application's controllers have been injected, they will - each have the store made available to them. - - For example, imagine an Ember.js application with the following classes: - - App.Store = DS.Store.extend({ - adapter: 'custom' - }); - - App.PostsController = Ember.ArrayController.extend({ - // ... - }); - - When the application is initialized, `App.Store` will automatically be - instantiated, and the instance of `App.PostsController` will have its `store` - property set to that instance. - - Note that this code will only be run if the `ember-application` package is - loaded. If Ember Data is being used in an environment other than a - typical application (e.g., node.js where only `ember-runtime` is available), - this code will be ignored. -*/ - -Ember.onLoad('Ember.Application', function(Application) { - Application.initializer({ - name: "store", - - initialize: function(container, application) { - application.register('store:main', application.Store || DS.Store); - - // allow older names to be looked up - - var proxy = new DS.ContainerProxy(container); - proxy.registerDeprecations([ - {deprecated: 'serializer:_default', valid: 'serializer:-default'}, - {deprecated: 'serializer:_rest', valid: 'serializer:-rest'}, - {deprecated: 'adapter:_rest', valid: 'adapter:-rest'} - ]); - - // new go forward paths - application.register('serializer:-default', DS.JSONSerializer); - application.register('serializer:-rest', DS.RESTSerializer); - application.register('adapter:-rest', DS.RESTAdapter); - - // Eagerly generate the store so defaultStore is populated. - // TODO: Do this in a finisher hook - container.lookup('store:main'); - } - }); - - Application.initializer({ - name: "transforms", - before: "store", - - initialize: function(container, application) { - application.register('transform:boolean', DS.BooleanTransform); - application.register('transform:date', DS.DateTransform); - application.register('transform:number', DS.NumberTransform); - application.register('transform:string', DS.StringTransform); - } - }); - - Application.initializer({ - name: "data-adapter", - before: "store", - - initialize: function(container, application) { - application.register('data-adapter:main', DS.DebugAdapter); - } - }); - - Application.initializer({ - name: "injectStore", - before: "store", - - initialize: function(container, application) { - application.inject('controller', 'store', 'store:main'); - application.inject('route', 'store', 'store:main'); - application.inject('serializer', 'store', 'store:main'); - application.inject('data-adapter', 'store', 'store:main'); - } - }); - -}); - -})(); - - - -(function() { -/** - @module ember-data -*/ - -/** - Date.parse with progressive enhancement for ISO 8601 - - © 2011 Colin Snover - - Released under MIT license. - - @class Date - @namespace Ember - @static -*/ -Ember.Date = Ember.Date || {}; - -var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ]; - -/** - @method parse - @param date -*/ -Ember.Date.parse = function (date) { - var timestamp, struct, minutesOffset = 0; - - // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string - // before falling back to any implementation-specific date parsing, so that’s what we do, even if native - // implementations could be faster - // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm - if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) { - // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC - for (var i = 0, k; (k = numericKeys[i]); ++i) { - struct[k] = +struct[k] || 0; - } - - // allow undefined days and months - struct[2] = (+struct[2] || 1) - 1; - struct[3] = +struct[3] || 1; - - if (struct[8] !== 'Z' && struct[9] !== undefined) { - minutesOffset = struct[10] * 60 + struct[11]; - - if (struct[9] === '+') { - minutesOffset = 0 - minutesOffset; - } - } - - timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); - } - else { - timestamp = origParse ? origParse(date) : NaN; - } - - return timestamp; -}; - -if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) { - Date.parse = Ember.Date.parse; -} - -})(); - - - -(function() { - -})(); - - - -(function() { -/** - @module ember-data -*/ - -var get = Ember.get, set = Ember.set; - -/** - A record array is an array that contains records of a certain type. The record - array materializes records as needed when they are retrieved for the first - time. You should not create record arrays yourself. Instead, an instance of - `DS.RecordArray` or its subclasses will be returned by your application's store - in response to queries. - - @class RecordArray - @namespace DS - @extends Ember.ArrayProxy - @uses Ember.Evented -*/ - -DS.RecordArray = Ember.ArrayProxy.extend(Ember.Evented, { - /** - The model type contained by this record array. - - @property type - @type DS.Model - */ - type: null, - - /** - The array of client ids backing the record array. When a - record is requested from the record array, the record - for the client id at the same index is materialized, if - necessary, by the store. - - @property content - @private - @type Ember.Array - */ - content: null, - - /** - The flag to signal a `RecordArray` is currently loading data. - - Example - - ```javascript - var people = store.all(App.Person); - people.get('isLoaded'); // true - ``` - - @property isLoaded - @type Boolean - */ - isLoaded: false, - /** - The flag to signal a `RecordArray` is currently loading data. - - Example - - ```javascript - var people = store.all(App.Person); - people.get('isUpdating'); // false - people.update(); - people.get('isUpdating'); // true - ``` - - @property isUpdating - @type Boolean - */ - isUpdating: false, - - /** - The store that created this record array. - - @property store - @private - @type DS.Store - */ - store: null, - - /** - Retrieves an object from the content by index. - - @method objectAtContent - @private - @param {Number} index - @return {DS.Model} record - */ - objectAtContent: function(index) { - var content = get(this, 'content'); - - return content.objectAt(index); - }, - - /** - Used to get the latest version of all of the records in this array - from the adapter. - - Example - - ```javascript - var people = store.all(App.Person); - people.get('isUpdating'); // false - people.update(); - people.get('isUpdating'); // true - ``` - - @method update - */ - update: function() { - if (get(this, 'isUpdating')) { return; } - - var store = get(this, 'store'), - type = get(this, 'type'); - - return store.fetchAll(type, this); - }, - - /** - Adds a record to the `RecordArray`. - - @method addRecord - @private - @param {DS.Model} record - */ - addRecord: function(record) { - get(this, 'content').addObject(record); - }, - - /** - Removes a record to the `RecordArray`. - - @method removeRecord - @private - @param {DS.Model} record - */ - removeRecord: function(record) { - get(this, 'content').removeObject(record); - }, - - /** - Saves all of the records in the `RecordArray`. - - Example - - ```javascript - var messages = store.all(App.Message); - messages.forEach(function(message) { - message.set('hasBeenSeen', true); - }); - messages.save(); - ``` - - @method save - @return {DS.PromiseArray} promise - */ - save: function() { - var promiseLabel = "DS: RecordArray#save " + get(this, 'type'); - var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function(array) { - return Ember.A(array); - }, null, "DS: RecordArray#save apply Ember.NativeArray"); - - return DS.PromiseArray.create({ promise: promise }); - } -}); - -})(); - - - -(function() { -/** - @module ember-data -*/ - -var get = Ember.get; - -/** - Represents a list of records whose membership is determined by the - store. As records are created, loaded, or modified, the store - evaluates them to determine if they should be part of the record - array. - - @class FilteredRecordArray - @namespace DS - @extends DS.RecordArray -*/ -DS.FilteredRecordArray = DS.RecordArray.extend({ - /** - The filterFunction is a function used to test records from the store to - determine if they should be part of the record array. - - Example - - ```javascript - var allPeople = store.all('person'); - allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"] - - var people = store.filter('person', function(person) { - if (person.get('name').match(/Katz$/)) { return true; } - }); - people.mapBy('name'); // ["Yehuda Katz"] - - var notKatzFilter = function(person) { - return !person.get('name').match(/Katz$/); - }; - people.set('filterFunction', notKatzFilter); - people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"] - ``` - - @method filterFunction - @param {DS.Model} record - @return {Boolean} `true` if the record should be in the array - */ - filterFunction: null, - isLoaded: true, - - replace: function() { - var type = get(this, 'type').toString(); - throw new Error("The result of a client-side filter (on " + type + ") is immutable."); - }, - - /** - @method updateFilter - @private - */ - updateFilter: Ember.observer(function() { - var manager = get(this, 'manager'); - manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction')); - }, 'filterFunction') -}); - -})(); - - - -(function() { -/** - @module ember-data -*/ - -var get = Ember.get, set = Ember.set; - -/** - Represents an ordered list of records whose order and membership is - determined by the adapter. For example, a query sent to the adapter - may trigger a search on the server, whose results would be loaded - into an instance of the `AdapterPopulatedRecordArray`. - - @class AdapterPopulatedRecordArray - @namespace DS - @extends DS.RecordArray -*/ -DS.AdapterPopulatedRecordArray = DS.RecordArray.extend({ - query: null, - - replace: function() { - var type = get(this, 'type').toString(); - throw new Error("The result of a server query (on " + type + ") is immutable."); - }, - - /** - @method load - @private - @param {Array} data - */ - load: function(data) { - var store = get(this, 'store'), - type = get(this, 'type'), - records = store.pushMany(type, data), - meta = store.metadataFor(type); - - this.setProperties({ - content: Ember.A(records), - isLoaded: true, - meta: meta - }); - - // TODO: does triggering didLoad event should be the last action of the runLoop? - Ember.run.once(this, 'trigger', 'didLoad'); - } -}); - -})(); - - - -(function() { -/** - @module ember-data -*/ - -var get = Ember.get, set = Ember.set; -var map = Ember.EnumerableUtils.map; - -/** - A `ManyArray` is a `RecordArray` that represents the contents of a has-many - relationship. - - The `ManyArray` is instantiated lazily the first time the relationship is - requested. - - ### Inverses - - Often, the relationships in Ember Data applications will have - an inverse. For example, imagine the following models are - defined: - - ```javascript - App.Post = DS.Model.extend({ - comments: DS.hasMany('comment') - }); - - App.Comment = DS.Model.extend({ - post: DS.belongsTo('post') - }); - ``` - - If you created a new instance of `App.Post` and added - a `App.Comment` record to its `comments` has-many - relationship, you would expect the comment's `post` - property to be set to the post that contained - the has-many. - - We call the record to which a relationship belongs the - relationship's _owner_. - - @class ManyArray - @namespace DS - @extends DS.RecordArray -*/ -DS.ManyArray = DS.RecordArray.extend({ - init: function() { - this._super.apply(this, arguments); - this._changesToSync = Ember.OrderedSet.create(); - }, - - /** - The property name of the relationship - - @property {String} name - @private - */ - name: null, - - /** - The record to which this relationship belongs. - - @property {DS.Model} owner - @private - */ - owner: null, - - /** - `true` if the relationship is polymorphic, `false` otherwise. - - @property {Boolean} isPolymorphic - @private - */ - isPolymorphic: false, - - // LOADING STATE - - isLoaded: false, - - /** - Used for async `hasMany` arrays - to keep track of when they will resolve. - - @property {Ember.RSVP.Promise} promise - @private - */ - promise: null, - - /** - @method loadingRecordsCount - @param {Number} count - @private - */ - loadingRecordsCount: function(count) { - this.loadingRecordsCount = count; - }, - - /** - @method loadedRecord - @private - */ - loadedRecord: function() { - this.loadingRecordsCount--; - if (this.loadingRecordsCount === 0) { - set(this, 'isLoaded', true); - this.trigger('didLoad'); - } - }, - - /** - @method fetch - @private - */ - fetch: function() { - var records = get(this, 'content'), - store = get(this, 'store'), - owner = get(this, 'owner'), - resolver = Ember.RSVP.defer("DS: ManyArray#fetch " + get(this, 'type')); - - var unloadedRecords = records.filterProperty('isEmpty', true); - store.fetchMany(unloadedRecords, owner, resolver); - }, - - // Overrides Ember.Array's replace method to implement - replaceContent: function(index, removed, added) { - // Map the array of record objects into an array of client ids. - added = map(added, function(record) { - Ember.assert("You cannot add '" + record.constructor.typeKey + "' records to this relationship (only '" + this.type.typeKey + "' allowed)", !this.type || record instanceof this.type); - return record; - }, this); - - this._super(index, removed, added); - }, - - arrangedContentDidChange: function() { - Ember.run.once(this, 'fetch'); - }, - - arrayContentWillChange: function(index, removed, added) { - var owner = get(this, 'owner'), - name = get(this, 'name'); - - if (!owner._suspendedRelationships) { - // This code is the first half of code that continues inside - // of arrayContentDidChange. It gets or creates a change from - // the child object, adds the current owner as the old - // parent if this is the first time the object was removed - // from a ManyArray, and sets `newParent` to null. - // - // Later, if the object is added to another ManyArray, - // the `arrayContentDidChange` will set `newParent` on - // the change. - for (var i=index; i "root.created.uncommitted" - ``` - - The hierarchy of valid states that ship with ember data looks like - this: - - ```text - * root - * deleted - * saved - * uncommitted - * inFlight - * empty - * loaded - * created - * uncommitted - * inFlight - * saved - * updated - * uncommitted - * inFlight - * loading - ``` - - The `DS.Model` states are themselves stateless. What we mean is - that, the hierarchical states that each of *those* points to is a - shared data structure. For performance reasons, instead of each - record getting its own copy of the hierarchy of states, each record - points to this global, immutable shared instance. How does a state - know which record it should be acting on? We pass the record - instance into the state's event handlers as the first argument. - - The record passed as the first parameter is where you should stash - state about the record if needed; you should never store data on the state - object itself. - - ### Events and Flags - - A state may implement zero or more events and flags. - - #### Events - - Events are named functions that are invoked when sent to a record. The - record will first look for a method with the given name on the - current state. If no method is found, it will search the current - state's parent, and then its grandparent, and so on until reaching - the top of the hierarchy. If the root is reached without an event - handler being found, an exception will be raised. This can be very - helpful when debugging new features. - - Here's an example implementation of a state with a `myEvent` event handler: - - ```javascript - aState: DS.State.create({ - myEvent: function(manager, param) { - console.log("Received myEvent with", param); - } - }) - ``` - - To trigger this event: - - ```javascript - record.send('myEvent', 'foo'); - //=> "Received myEvent with foo" - ``` - - Note that an optional parameter can be sent to a record's `send()` method, - which will be passed as the second parameter to the event handler. - - Events should transition to a different state if appropriate. This can be - done by calling the record's `transitionTo()` method with a path to the - desired state. The state manager will attempt to resolve the state path - relative to the current state. If no state is found at that path, it will - attempt to resolve it relative to the current state's parent, and then its - parent, and so on until the root is reached. For example, imagine a hierarchy - like this: - - * created - * uncommitted <-- currentState - * inFlight - * updated - * inFlight - - If we are currently in the `uncommitted` state, calling - `transitionTo('inFlight')` would transition to the `created.inFlight` state, - while calling `transitionTo('updated.inFlight')` would transition to - the `updated.inFlight` state. - - Remember that *only events* should ever cause a state transition. You should - never call `transitionTo()` from outside a state's event handler. If you are - tempted to do so, create a new event and send that to the state manager. - - #### Flags - - Flags are Boolean values that can be used to introspect a record's current - state in a more user-friendly way than examining its state path. For example, - instead of doing this: - - ```javascript - var statePath = record.get('stateManager.currentPath'); - if (statePath === 'created.inFlight') { - doSomething(); - } - ``` - - You can say: - - ```javascript - if (record.get('isNew') && record.get('isSaving')) { - doSomething(); - } - ``` - - If your state does not set a value for a given flag, the value will - be inherited from its parent (or the first place in the state hierarchy - where it is defined). - - The current set of flags are defined below. If you want to add a new flag, - in addition to the area below, you will also need to declare it in the - `DS.Model` class. - - - * [isEmpty](DS.Model.html#property_isEmpty) - * [isLoading](DS.Model.html#property_isLoading) - * [isLoaded](DS.Model.html#property_isLoaded) - * [isDirty](DS.Model.html#property_isDirty) - * [isSaving](DS.Model.html#property_isSaving) - * [isDeleted](DS.Model.html#property_isDeleted) - * [isNew](DS.Model.html#property_isNew) - * [isValid](DS.Model.html#property_isValid) - - @namespace DS - @class RootState -*/ - -var hasDefinedProperties = function(object) { - // Ignore internal property defined by simulated `Ember.create`. - var names = Ember.keys(object); - var i, l, name; - for (i = 0, l = names.length; i < l; i++ ) { - name = names[i]; - if (object.hasOwnProperty(name) && object[name]) { return true; } - } - - return false; -}; - -var didSetProperty = function(record, context) { - if (context.value === context.originalValue) { - delete record._attributes[context.name]; - record.send('propertyWasReset', context.name); - } else if (context.value !== context.oldValue) { - record.send('becomeDirty'); - } - - record.updateRecordArraysLater(); -}; - -// Implementation notes: -// -// Each state has a boolean value for all of the following flags: -// -// * isLoaded: The record has a populated `data` property. When a -// record is loaded via `store.find`, `isLoaded` is false -// until the adapter sets it. When a record is created locally, -// its `isLoaded` property is always true. -// * isDirty: The record has local changes that have not yet been -// saved by the adapter. This includes records that have been -// created (but not yet saved) or deleted. -// * isSaving: The record has been committed, but -// the adapter has not yet acknowledged that the changes have -// been persisted to the backend. -// * isDeleted: The record was marked for deletion. When `isDeleted` -// is true and `isDirty` is true, the record is deleted locally -// but the deletion was not yet persisted. When `isSaving` is -// true, the change is in-flight. When both `isDirty` and -// `isSaving` are false, the change has persisted. -// * isError: The adapter reported that it was unable to save -// local changes to the backend. This may also result in the -// record having its `isValid` property become false if the -// adapter reported that server-side validations failed. -// * isNew: The record was created on the client and the adapter -// did not yet report that it was successfully saved. -// * isValid: No client-side validations have failed and the -// adapter did not report any server-side validation failures. - -// The dirty state is a abstract state whose functionality is -// shared between the `created` and `updated` states. -// -// The deleted state shares the `isDirty` flag with the -// subclasses of `DirtyState`, but with a very different -// implementation. -// -// Dirty states have three child states: -// -// `uncommitted`: the store has not yet handed off the record -// to be saved. -// `inFlight`: the store has handed off the record to be saved, -// but the adapter has not yet acknowledged success. -// `invalid`: the record has invalid information and cannot be -// send to the adapter yet. -var DirtyState = { - initialState: 'uncommitted', - - // FLAGS - isDirty: true, - - // SUBSTATES - - // When a record first becomes dirty, it is `uncommitted`. - // This means that there are local pending changes, but they - // have not yet begun to be saved, and are not invalid. - uncommitted: { - // EVENTS - didSetProperty: didSetProperty, - - propertyWasReset: function(record, name) { - var stillDirty = false; - - for (var prop in record._attributes) { - stillDirty = true; - break; - } - - if (!stillDirty) { record.send('rolledBack'); } - }, - - pushedData: Ember.K, - - becomeDirty: Ember.K, - - willCommit: function(record) { - record.transitionTo('inFlight'); - }, - - reloadRecord: function(record, resolve) { - resolve(get(record, 'store').reloadRecord(record)); - }, - - rolledBack: function(record) { - record.transitionTo('loaded.saved'); - }, - - becameInvalid: function(record) { - record.transitionTo('invalid'); - }, - - rollback: function(record) { - record.rollback(); - } - }, - - // Once a record has been handed off to the adapter to be - // saved, it is in the 'in flight' state. Changes to the - // record cannot be made during this window. - inFlight: { - // FLAGS - isSaving: true, - - // EVENTS - didSetProperty: didSetProperty, - becomeDirty: Ember.K, - pushedData: Ember.K, - - // TODO: More robust semantics around save-while-in-flight - willCommit: Ember.K, - - didCommit: function(record) { - var dirtyType = get(this, 'dirtyType'); - - record.transitionTo('saved'); - record.send('invokeLifecycleCallbacks', dirtyType); - }, - - becameInvalid: function(record) { - record.transitionTo('invalid'); - record.send('invokeLifecycleCallbacks'); - }, - - becameError: function(record) { - record.transitionTo('uncommitted'); - record.triggerLater('becameError', record); - } - }, - - // A record is in the `invalid` state when its client-side - // invalidations have failed, or if the adapter has indicated - // the the record failed server-side invalidations. - invalid: { - // FLAGS - isValid: false, - - // EVENTS - deleteRecord: function(record) { - record.transitionTo('deleted.uncommitted'); - record.clearRelationships(); - }, - - didSetProperty: function(record, context) { - get(record, 'errors').remove(context.name); - - didSetProperty(record, context); - }, - - becomeDirty: Ember.K, - - rolledBack: function(record) { - get(record, 'errors').clear(); - }, - - becameValid: function(record) { - record.transitionTo('uncommitted'); - }, - - invokeLifecycleCallbacks: function(record) { - record.triggerLater('becameInvalid', record); - } - } -}; - -// The created and updated states are created outside the state -// chart so we can reopen their substates and add mixins as -// necessary. - -function deepClone(object) { - var clone = {}, value; - - for (var prop in object) { - value = object[prop]; - if (value && typeof value === 'object') { - clone[prop] = deepClone(value); - } else { - clone[prop] = value; - } - } - - return clone; -} - -function mixin(original, hash) { - for (var prop in hash) { - original[prop] = hash[prop]; - } - - return original; -} - -function dirtyState(options) { - var newState = deepClone(DirtyState); - return mixin(newState, options); -} - -var createdState = dirtyState({ - dirtyType: 'created', - - // FLAGS - isNew: true -}); - -createdState.uncommitted.rolledBack = function(record) { - record.transitionTo('deleted.saved'); -}; - -var updatedState = dirtyState({ - dirtyType: 'updated' -}); - -createdState.uncommitted.deleteRecord = function(record) { - record.clearRelationships(); - record.transitionTo('deleted.saved'); -}; - -createdState.uncommitted.rollback = function(record) { - DirtyState.uncommitted.rollback.apply(this, arguments); - record.transitionTo('deleted.saved'); -}; - -createdState.uncommitted.propertyWasReset = Ember.K; - -updatedState.uncommitted.deleteRecord = function(record) { - record.transitionTo('deleted.uncommitted'); - record.clearRelationships(); -}; - -var RootState = { - // FLAGS - isEmpty: false, - isLoading: false, - isLoaded: false, - isDirty: false, - isSaving: false, - isDeleted: false, - isNew: false, - isValid: true, - - // DEFAULT EVENTS - - // Trying to roll back if you're not in the dirty state - // doesn't change your state. For example, if you're in the - // in-flight state, rolling back the record doesn't move - // you out of the in-flight state. - rolledBack: Ember.K, - - propertyWasReset: Ember.K, - - // SUBSTATES - - // A record begins its lifecycle in the `empty` state. - // If its data will come from the adapter, it will - // transition into the `loading` state. Otherwise, if - // the record is being created on the client, it will - // transition into the `created` state. - empty: { - isEmpty: true, - - // EVENTS - loadingData: function(record, promise) { - record._loadingPromise = promise; - record.transitionTo('loading'); - }, - - loadedData: function(record) { - record.transitionTo('loaded.created.uncommitted'); - - record.suspendRelationshipObservers(function() { - record.notifyPropertyChange('data'); - }); - }, - - pushedData: function(record) { - record.transitionTo('loaded.saved'); - record.triggerLater('didLoad'); - } - }, - - // A record enters this state when the store asks - // the adapter for its data. It remains in this state - // until the adapter provides the requested data. - // - // Usually, this process is asynchronous, using an - // XHR to retrieve the data. - loading: { - // FLAGS - isLoading: true, - - exit: function(record) { - record._loadingPromise = null; - }, - - // EVENTS - pushedData: function(record) { - record.transitionTo('loaded.saved'); - record.triggerLater('didLoad'); - set(record, 'isError', false); - }, - - becameError: function(record) { - record.triggerLater('becameError', record); - }, - - notFound: function(record) { - record.transitionTo('empty'); - } - }, - - // A record enters this state when its data is populated. - // Most of a record's lifecycle is spent inside substates - // of the `loaded` state. - loaded: { - initialState: 'saved', - - // FLAGS - isLoaded: true, - - // SUBSTATES - - // If there are no local changes to a record, it remains - // in the `saved` state. - saved: { - setup: function(record) { - var attrs = record._attributes, - isDirty = false; - - for (var prop in attrs) { - if (attrs.hasOwnProperty(prop)) { - isDirty = true; - break; - } - } - - if (isDirty) { - record.adapterDidDirty(); - } - }, - - // EVENTS - didSetProperty: didSetProperty, - - pushedData: Ember.K, - - becomeDirty: function(record) { - record.transitionTo('updated.uncommitted'); - }, - - willCommit: function(record) { - record.transitionTo('updated.inFlight'); - }, - - reloadRecord: function(record, resolve) { - resolve(get(record, 'store').reloadRecord(record)); - }, - - deleteRecord: function(record) { - record.transitionTo('deleted.uncommitted'); - record.clearRelationships(); - }, - - unloadRecord: function(record) { - // clear relationships before moving to deleted state - // otherwise it fails - record.clearRelationships(); - record.transitionTo('deleted.saved'); - }, - - didCommit: function(record) { - record.send('invokeLifecycleCallbacks', get(record, 'lastDirtyType')); - }, - - // loaded.saved.notFound would be triggered by a failed - // `reload()` on an unchanged record - notFound: Ember.K - - }, - - // A record is in this state after it has been locally - // created but before the adapter has indicated that - // it has been saved. - created: createdState, - - // A record is in this state if it has already been - // saved to the server, but there are new local changes - // that have not yet been saved. - updated: updatedState - }, - - // A record is in this state if it was deleted from the store. - deleted: { - initialState: 'uncommitted', - dirtyType: 'deleted', - - // FLAGS - isDeleted: true, - isLoaded: true, - isDirty: true, - - // TRANSITIONS - setup: function(record) { - record.updateRecordArrays(); - }, - - // SUBSTATES - - // When a record is deleted, it enters the `start` - // state. It will exit this state when the record - // starts to commit. - uncommitted: { - - // EVENTS - - willCommit: function(record) { - record.transitionTo('inFlight'); - }, - - rollback: function(record) { - record.rollback(); - }, - - becomeDirty: Ember.K, - deleteRecord: Ember.K, - - rolledBack: function(record) { - record.transitionTo('loaded.saved'); - } - }, - - // After a record starts committing, but - // before the adapter indicates that the deletion - // has saved to the server, a record is in the - // `inFlight` substate of `deleted`. - inFlight: { - // FLAGS - isSaving: true, - - // EVENTS - - // TODO: More robust semantics around save-while-in-flight - willCommit: Ember.K, - didCommit: function(record) { - record.transitionTo('saved'); - - record.send('invokeLifecycleCallbacks'); - }, - - becameError: function(record) { - record.transitionTo('uncommitted'); - record.triggerLater('becameError', record); - } - }, - - // Once the adapter indicates that the deletion has - // been saved, the record enters the `saved` substate - // of `deleted`. - saved: { - // FLAGS - isDirty: false, - - setup: function(record) { - var store = get(record, 'store'); - store.dematerializeRecord(record); - }, - - invokeLifecycleCallbacks: function(record) { - record.triggerLater('didDelete', record); - record.triggerLater('didCommit', record); - } - } - }, - - invokeLifecycleCallbacks: function(record, dirtyType) { - if (dirtyType === 'created') { - record.triggerLater('didCreate', record); - } else { - record.triggerLater('didUpdate', record); - } - - record.triggerLater('didCommit', record); - } -}; - -function wireState(object, parent, name) { - /*jshint proto:true*/ - // TODO: Use Object.create and copy instead - object = mixin(parent ? Ember.create(parent) : {}, object); - object.parentState = parent; - object.stateName = name; - - for (var prop in object) { - if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; } - if (typeof object[prop] === 'object') { - object[prop] = wireState(object[prop], object, name + "." + prop); - } - } - - return object; -} - -RootState = wireState(RootState, null, "root"); - -DS.RootState = RootState; - -})(); - - - -(function() { -var get = Ember.get, isEmpty = Ember.isEmpty; - -/** -@module ember-data -*/ - -/** - Holds validation errors for a given record organized by attribute names. - - @class Errors - @namespace DS - @extends Ember.Object - @uses Ember.Enumerable - @uses Ember.Evented - */ -DS.Errors = Ember.Object.extend(Ember.Enumerable, Ember.Evented, { - /** - Register with target handler - - @method registerHandlers - @param {Object} target - @param {Function} becameInvalid - @param {Function} becameValid - */ - registerHandlers: function(target, becameInvalid, becameValid) { - this.on('becameInvalid', target, becameInvalid); - this.on('becameValid', target, becameValid); - }, - - /** - @property errorsByAttributeName - @type {Ember.MapWithDefault} - @private - */ - errorsByAttributeName: Ember.reduceComputed("content", { - initialValue: function() { - return Ember.MapWithDefault.create({ - defaultValue: function() { - return Ember.A(); - } - }); - }, - - addedItem: function(errors, error) { - errors.get(error.attribute).pushObject(error); - - return errors; - }, - - removedItem: function(errors, error) { - errors.get(error.attribute).removeObject(error); - - return errors; - } - }), - - /** - Returns errors for a given attribute - - @method errorsFor - @param {String} attribute - @returns {Array} - */ - errorsFor: function(attribute) { - return get(this, 'errorsByAttributeName').get(attribute); - }, - - /** - */ - messages: Ember.computed.mapBy('content', 'message'), - - /** - @property content - @type {Array} - @private - */ - content: Ember.computed(function() { - return Ember.A(); - }), - - /** - @method unknownProperty - @private - */ - unknownProperty: function(attribute) { - var errors = this.errorsFor(attribute); - if (isEmpty(errors)) { return null; } - return errors; - }, - - /** - @method nextObject - @private - */ - nextObject: function(index, previousObject, context) { - return get(this, 'content').objectAt(index); - }, - - /** - Total number of errors. - - @property length - @type {Number} - @readOnly - */ - length: Ember.computed.oneWay('content.length').readOnly(), - - /** - @property isEmpty - @type {Boolean} - @readOnly - */ - isEmpty: Ember.computed.not('length').readOnly(), - - /** - Adds error messages to a given attribute and sends - `becameInvalid` event to the record. - - @method add - @param {String} attribute - @param {Array|String} messages - */ - add: function(attribute, messages) { - var wasEmpty = get(this, 'isEmpty'); - - messages = this._findOrCreateMessages(attribute, messages); - get(this, 'content').addObjects(messages); - - this.notifyPropertyChange(attribute); - this.enumerableContentDidChange(); - - if (wasEmpty && !get(this, 'isEmpty')) { - this.trigger('becameInvalid'); - } - }, - - /** - @method _findOrCreateMessages - @private - */ - _findOrCreateMessages: function(attribute, messages) { - var errors = this.errorsFor(attribute); - - return Ember.makeArray(messages).map(function(message) { - return errors.findBy('message', message) || { - attribute: attribute, - message: message - }; - }); - }, - - /** - Removes all error messages from the given attribute and sends - `becameValid` event to the record if there no more errors left. - - @method remove - @param {String} attribute - */ - remove: function(attribute) { - if (get(this, 'isEmpty')) { return; } - - var content = get(this, 'content').rejectBy('attribute', attribute); - get(this, 'content').setObjects(content); - - this.notifyPropertyChange(attribute); - this.enumerableContentDidChange(); - - if (get(this, 'isEmpty')) { - this.trigger('becameValid'); - } - }, - - /** - Removes all error messages and sends `becameValid` event - to the record. - - @method clear - */ - clear: function() { - if (get(this, 'isEmpty')) { return; } - - get(this, 'content').clear(); - this.enumerableContentDidChange(); - - this.trigger('becameValid'); - }, - - /** - Checks if there is error messages for the given attribute. - - @method has - @param {String} attribute - @returns {Boolean} true if there some errors on given attribute - */ - has: function(attribute) { - return !isEmpty(this.errorsFor(attribute)); - } -}); - -})(); - - - -(function() { -/** - @module ember-data -*/ - -var get = Ember.get, set = Ember.set, - merge = Ember.merge; - -var retrieveFromCurrentState = Ember.computed('currentState', function(key, value) { - return get(get(this, 'currentState'), key); -}).readOnly(); - -/** - - The model class that all Ember Data records descend from. - - @class Model - @namespace DS - @extends Ember.Object - @uses Ember.Evented -*/ -DS.Model = Ember.Object.extend(Ember.Evented, { - /** - If this property is `true` the record is in the `empty` - state. Empty is the first state all records enter after they have - been created. Most records created by the store will quickly - transition to the `loading` state if data needs to be fetched from - the server or the `created` state if the record is created on the - client. A record can also enter the empty state if the adapter is - unable to locate the record. - - @property isEmpty - @type {Boolean} - @readOnly - */ - isEmpty: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `loading` state. A - record enters this state when the store asks the adapter for its - data. It remains in this state until the adapter provides the - requested data. - - @property isLoading - @type {Boolean} - @readOnly - */ - isLoading: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `loaded` state. A - record enters this state when its data is populated. Most of a - record's lifecycle is spent inside substates of the `loaded` - state. - - Example - - ```javascript - var record = store.createRecord(App.Model); - record.get('isLoaded'); // true - - store.find('model', 1).then(function(model) { - model.get('isLoaded'); // true - }); - ``` - - @property isLoaded - @type {Boolean} - @readOnly - */ - isLoaded: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `dirty` state. The - record has local changes that have not yet been saved by the - adapter. This includes records that have been created (but not yet - saved) or deleted. - - Example - - ```javascript - var record = store.createRecord(App.Model); - record.get('isDirty'); // true - - store.find('model', 1).then(function(model) { - model.get('isDirty'); // false - model.set('foo', 'some value'); - model.set('isDirty'); // true - }); - ``` - - @property isDirty - @type {Boolean} - @readOnly - */ - isDirty: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `saving` state. A - record enters the saving state when `save` is called, but the - adapter has not yet acknowledged that the changes have been - persisted to the backend. - - Example - - ```javascript - var record = store.createRecord(App.Model); - record.get('isSaving'); // false - var promise = record.save(); - record.get('isSaving'); // true - promise.then(function() { - record.get('isSaving'); // false - }); - ``` - - @property isSaving - @type {Boolean} - @readOnly - */ - isSaving: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `deleted` state - and has been marked for deletion. When `isDeleted` is true and - `isDirty` is true, the record is deleted locally but the deletion - was not yet persisted. When `isSaving` is true, the change is - in-flight. When both `isDirty` and `isSaving` are false, the - change has persisted. - - Example - - ```javascript - var record = store.createRecord(App.Model); - record.get('isDeleted'); // false - record.deleteRecord(); - record.get('isDeleted'); // true - ``` - - @property isDeleted - @type {Boolean} - @readOnly - */ - isDeleted: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `new` state. A - record will be in the `new` state when it has been created on the - client and the adapter has not yet report that it was successfully - saved. - - Example - - ```javascript - var record = store.createRecord(App.Model); - record.get('isNew'); // true - - record.save().then(function(model) { - model.get('isNew'); // false - }); - ``` - - @property isNew - @type {Boolean} - @readOnly - */ - isNew: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `valid` state. A - record will be in the `valid` state when no client-side - validations have failed and the adapter did not report any - server-side validation failures. - - @property isValid - @type {Boolean} - @readOnly - */ - isValid: retrieveFromCurrentState, - /** - If the record is in the dirty state this property will report what - kind of change has caused it to move into the dirty - state. Possible values are: - - - `created` The record has been created by the client and not yet saved to the adapter. - - `updated` The record has been updated by the client and not yet saved to the adapter. - - `deleted` The record has been deleted by the client and not yet saved to the adapter. - - Example - - ```javascript - var record = store.createRecord(App.Model); - record.get('dirtyType'); // 'created' - ``` - - @property dirtyType - @type {String} - @readOnly - */ - dirtyType: retrieveFromCurrentState, - - /** - If `true` the adapter reported that it was unable to save local - changes to the backend. This may also result in the record having - its `isValid` property become false if the adapter reported that - server-side validations failed. - - Example - - ```javascript - record.get('isError'); // false - record.set('foo', 'invalid value'); - record.save().then(null, function() { - record.get('isError'); // true - }); - ``` - - @property isError - @type {Boolean} - @readOnly - */ - isError: false, - /** - If `true` the store is attempting to reload the record form the adapter. - - Example - - ```javascript - record.get('isReloading'); // false - record.reload(); - record.get('isReloading'); // true - ``` - - @property isReloading - @type {Boolean} - @readOnly - */ - isReloading: false, - - /** - The `clientId` property is a transient numerical identifier - generated at runtime by the data store. It is important - primarily because newly created objects may not yet have an - externally generated id. - - @property clientId - @private - @type {Number|String} - */ - clientId: null, - /** - All ember models have an id property. This is an identifier - managed by an external source. These are always coerced to be - strings before being used internally. Note when declaring the - attributes for a model it is an error to declare an id - attribute. - - ```javascript - var record = store.createRecord(App.Model); - record.get('id'); // null - - store.find('model', 1).then(function(model) { - model.get('id'); // '1' - }); - ``` - - @property id - @type {String} - */ - id: null, - transaction: null, - /** - @property currentState - @private - @type {Object} - */ - currentState: null, - /** - When the record is in the `invalid` state this object will contain - any errors returned by the adapter. When present the errors hash - typically contains keys corresponding to the invalid property names - and values which are an array of error messages. - - ```javascript - record.get('errors.length'); // 0 - record.set('foo', 'invalid value'); - record.save().then(null, function() { - record.get('errors').get('foo'); // ['foo should be a number.'] - }); - ``` - - @property errors - @type {Object} - */ - errors: null, - - /** - Create a JSON representation of the record, using the serialization - strategy of the store's adapter. - - `serialize` takes an optional hash as a parameter, currently - supported options are: - - - `includeId`: `true` if the record's ID should be included in the - JSON representation. - - @method serialize - @param {Object} options - @returns {Object} an object whose values are primitive JSON values only - */ - serialize: function(options) { - var store = get(this, 'store'); - return store.serialize(this, options); - }, - - /** - Use [DS.JSONSerializer](DS.JSONSerializer.html) to - get the JSON representation of a record. - - `toJSON` takes an optional hash as a parameter, currently - supported options are: - - - `includeId`: `true` if the record's ID should be included in the - JSON representation. - - @method toJSON - @param {Object} options - @returns {Object} A JSON representation of the object. - */ - toJSON: function(options) { - // container is for lazy transform lookups - var serializer = DS.JSONSerializer.create({ container: this.container }); - return serializer.serialize(this, options); - }, - - /** - Fired when the record is loaded from the server. - - @event didLoad - */ - didLoad: Ember.K, - - /** - Fired when the record is updated. - - @event didUpdate - */ - didUpdate: Ember.K, - - /** - Fired when the record is created. - - @event didCreate - */ - didCreate: Ember.K, - - /** - Fired when the record is deleted. - - @event didDelete - */ - didDelete: Ember.K, - - /** - Fired when the record becomes invalid. - - @event becameInvalid - */ - becameInvalid: Ember.K, - - /** - Fired when the record enters the error state. - - @event becameError - */ - becameError: Ember.K, - - /** - @property data - @private - @type {Object} - */ - data: Ember.computed(function() { - this._data = this._data || {}; - return this._data; - }).property(), - - _data: null, - - init: function() { - set(this, 'currentState', DS.RootState.empty); - var errors = DS.Errors.create(); - errors.registerHandlers(this, function() { - this.send('becameInvalid'); - }, function() { - this.send('becameValid'); - }); - set(this, 'errors', errors); - this._super(); - this._setup(); - }, - - _setup: function() { - this._changesToSync = {}; - this._deferredTriggers = []; - this._data = {}; - this._attributes = {}; - this._inFlightAttributes = {}; - this._relationships = {}; - }, - - /** - @method send - @private - @param {String} name - @param {Object} context - */ - send: function(name, context) { - var currentState = get(this, 'currentState'); - - if (!currentState[name]) { - this._unhandledEvent(currentState, name, context); - } - - return currentState[name](this, context); - }, - - /** - @method transitionTo - @private - @param {String} name - */ - transitionTo: function(name) { - // POSSIBLE TODO: Remove this code and replace with - // always having direct references to state objects - - var pivotName = name.split(".", 1), - currentState = get(this, 'currentState'), - state = currentState; - - do { - if (state.exit) { state.exit(this); } - state = state.parentState; - } while (!state.hasOwnProperty(pivotName)); - - var path = name.split("."); - - var setups = [], enters = [], i, l; - - for (i=0, l=path.length; i')` from " + this.toString(), name !== 'id'); - - meta.name = name; - map.set(name, meta); - } - }); - - return map; - }), - - /** - A map whose keys are the attributes of the model (properties - described by DS.attr) and whose values are type of transformation - applied to each attribute. This map does not include any - attributes that do not have an transformation type. - - Example - - ```javascript - App.Person = DS.Model.extend({ - firstName: attr(), - lastName: attr('string'), - birthday: attr('date') - }); - - var transformedAttributes = Ember.get(App.Person, 'transformedAttributes') - - transformedAttributes.forEach(function(field, type) { - console.log(field, type); - }); - - // prints: - // lastName string - // birthday date - ``` - - @property transformedAttributes - @static - @type {Ember.Map} - @readOnly - */ - transformedAttributes: Ember.computed(function() { - var map = Ember.Map.create(); - - this.eachAttribute(function(key, meta) { - if (meta.type) { - map.set(key, meta.type); - } - }); - - return map; - }), - - /** - Iterates through the attributes of the model, calling the passed function on each - attribute. - - The callback method you provide should have the following signature (all - parameters are optional): - - ```javascript - function(name, meta); - ``` - - - `name` the name of the current property in the iteration - - `meta` the meta object for the attribute property in the iteration - - Note that in addition to a callback, you can also pass an optional target - object that will be set as `this` on the context. - - Example - - ```javascript - App.Person = DS.Model.extend({ - firstName: attr('string'), - lastName: attr('string'), - birthday: attr('date') - }); - - App.Person.eachAttribute(function(name, meta) { - console.log(name, meta); - }); - - // prints: - // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} - // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} - // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} - ``` - - @method eachAttribute - @param {Function} callback The callback to execute - @param {Object} [target] The target object to use - @static - */ - eachAttribute: function(callback, binding) { - get(this, 'attributes').forEach(function(name, meta) { - callback.call(binding, name, meta); - }, binding); - }, - - /** - Iterates through the transformedAttributes of the model, calling - the passed function on each attribute. Note the callback will not be - called for any attributes that do not have an transformation type. - - The callback method you provide should have the following signature (all - parameters are optional): - - ```javascript - function(name, type); - ``` - - - `name` the name of the current property in the iteration - - `type` a string containing the name of the type of transformed - applied to the attribute - - Note that in addition to a callback, you can also pass an optional target - object that will be set as `this` on the context. - - Example - - ```javascript - App.Person = DS.Model.extend({ - firstName: attr(), - lastName: attr('string'), - birthday: attr('date') - }); - - App.Person.eachTransformedAttribute(function(name, type) { - console.log(name, type); - }); - - // prints: - // lastName string - // birthday date - ``` - - @method eachTransformedAttribute - @param {Function} callback The callback to execute - @param {Object} [target] The target object to use - @static - */ - eachTransformedAttribute: function(callback, binding) { - get(this, 'transformedAttributes').forEach(function(name, type) { - callback.call(binding, name, type); - }); - } -}); - - -DS.Model.reopen({ - eachAttribute: function(callback, binding) { - this.constructor.eachAttribute(callback, binding); - } -}); - -function getDefaultValue(record, options, key) { - if (typeof options.defaultValue === "function") { - return options.defaultValue(); - } else { - return options.defaultValue; - } -} - -function hasValue(record, key) { - return record._attributes.hasOwnProperty(key) || - record._inFlightAttributes.hasOwnProperty(key) || - record._data.hasOwnProperty(key); -} - -function getValue(record, key) { - if (record._attributes.hasOwnProperty(key)) { - return record._attributes[key]; - } else if (record._inFlightAttributes.hasOwnProperty(key)) { - return record._inFlightAttributes[key]; - } else { - return record._data[key]; - } -} - -/** - `DS.attr` defines an attribute on a [DS.Model](DS.Model.html). - By default, attributes are passed through as-is, however you can specify an - optional type to have the value automatically transformed. - Ember Data ships with four basic transform types: `string`, `number`, - `boolean` and `date`. You can define your own transforms by subclassing - [DS.Transform](DS.Transform.html). - - `DS.attr` takes an optional hash as a second parameter, currently - supported options are: - - - `defaultValue`: Pass a string or a function to be called to set the attribute - to a default value if none is supplied. - - Example - - ```javascript - var attr = DS.attr; - - App.User = DS.Model.extend({ - username: attr('string'), - email: attr('string'), - verified: attr('boolean', {defaultValue: false}) - }); - ``` - - @namespace - @method attr - @for DS - @param {String} type the attribute type - @param {Object} options a hash of options - @return {Attribute} -*/ - -DS.attr = function(type, options) { - options = options || {}; - - var meta = { - type: type, - isAttribute: true, - options: options - }; - - return Ember.computed(function(key, value) { - if (arguments.length > 1) { - Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('')` from " + this.constructor.toString(), key !== 'id'); - var oldValue = this._attributes[key] || this._inFlightAttributes[key] || this._data[key]; - - this.send('didSetProperty', { - name: key, - oldValue: oldValue, - originalValue: this._data[key], - value: value - }); - - this._attributes[key] = value; - return value; - } else if (hasValue(this, key)) { - return getValue(this, key); - } else { - return getDefaultValue(this, options, key); - } - - // `data` is never set directly. However, it may be - // invalidated from the state manager's setData - // event. - }).property('data').meta(meta); -}; - - -})(); - - - -(function() { -/** - @module ember-data -*/ - -})(); - - - -(function() { -/** - @module ember-data -*/ - -/** - An AttributeChange object is created whenever a record's - attribute changes value. It is used to track changes to a - record between transaction commits. - - @class AttributeChange - @namespace DS - @private - @constructor -*/ -var AttributeChange = DS.AttributeChange = function(options) { - this.record = options.record; - this.store = options.store; - this.name = options.name; - this.value = options.value; - this.oldValue = options.oldValue; -}; - -AttributeChange.createChange = function(options) { - return new AttributeChange(options); -}; - -AttributeChange.prototype = { - sync: function() { - if (this.value !== this.oldValue) { - this.record.send('becomeDirty'); - this.record.updateRecordArraysLater(); - } - - // TODO: Use this object in the commit process - this.destroy(); - }, - - /** - If the AttributeChange is destroyed (either by being rolled back - or being committed), remove it from the list of pending changes - on the record. - - @method destroy - */ - destroy: function() { - delete this.record._changesToSync[this.name]; - } -}; - -})(); - - - -(function() { -/** - @module ember-data -*/ - -var get = Ember.get, set = Ember.set; -var forEach = Ember.EnumerableUtils.forEach; - -/** - @class RelationshipChange - @namespace DS - @private - @constructor -*/ -DS.RelationshipChange = function(options) { - this.parentRecord = options.parentRecord; - this.childRecord = options.childRecord; - this.firstRecord = options.firstRecord; - this.firstRecordKind = options.firstRecordKind; - this.firstRecordName = options.firstRecordName; - this.secondRecord = options.secondRecord; - this.secondRecordKind = options.secondRecordKind; - this.secondRecordName = options.secondRecordName; - this.changeType = options.changeType; - this.store = options.store; - - this.committed = {}; -}; - -/** - @class RelationshipChangeAdd - @namespace DS - @private - @constructor -*/ -DS.RelationshipChangeAdd = function(options){ - DS.RelationshipChange.call(this, options); -}; - -/** - @class RelationshipChangeRemove - @namespace DS - @private - @constructor -*/ -DS.RelationshipChangeRemove = function(options){ - DS.RelationshipChange.call(this, options); -}; - -DS.RelationshipChange.create = function(options) { - return new DS.RelationshipChange(options); -}; - -DS.RelationshipChangeAdd.create = function(options) { - return new DS.RelationshipChangeAdd(options); -}; - -DS.RelationshipChangeRemove.create = function(options) { - return new DS.RelationshipChangeRemove(options); -}; - -DS.OneToManyChange = {}; -DS.OneToNoneChange = {}; -DS.ManyToNoneChange = {}; -DS.OneToOneChange = {}; -DS.ManyToManyChange = {}; - -DS.RelationshipChange._createChange = function(options){ - if(options.changeType === "add"){ - return DS.RelationshipChangeAdd.create(options); - } - if(options.changeType === "remove"){ - return DS.RelationshipChangeRemove.create(options); - } -}; - - -DS.RelationshipChange.determineRelationshipType = function(recordType, knownSide){ - var knownKey = knownSide.key, key, otherKind; - var knownKind = knownSide.kind; - - var inverse = recordType.inverseFor(knownKey); - - if (inverse){ - key = inverse.name; - otherKind = inverse.kind; - } - - if (!inverse){ - return knownKind === "belongsTo" ? "oneToNone" : "manyToNone"; - } - else{ - if(otherKind === "belongsTo"){ - return knownKind === "belongsTo" ? "oneToOne" : "manyToOne"; - } - else{ - return knownKind === "belongsTo" ? "oneToMany" : "manyToMany"; - } - } - -}; - -DS.RelationshipChange.createChange = function(firstRecord, secondRecord, store, options){ - // Get the type of the child based on the child's client ID - var firstRecordType = firstRecord.constructor, changeType; - changeType = DS.RelationshipChange.determineRelationshipType(firstRecordType, options); - if (changeType === "oneToMany"){ - return DS.OneToManyChange.createChange(firstRecord, secondRecord, store, options); - } - else if (changeType === "manyToOne"){ - return DS.OneToManyChange.createChange(secondRecord, firstRecord, store, options); - } - else if (changeType === "oneToNone"){ - return DS.OneToNoneChange.createChange(firstRecord, secondRecord, store, options); - } - else if (changeType === "manyToNone"){ - return DS.ManyToNoneChange.createChange(firstRecord, secondRecord, store, options); - } - else if (changeType === "oneToOne"){ - return DS.OneToOneChange.createChange(firstRecord, secondRecord, store, options); - } - else if (changeType === "manyToMany"){ - return DS.ManyToManyChange.createChange(firstRecord, secondRecord, store, options); - } -}; - -DS.OneToNoneChange.createChange = function(childRecord, parentRecord, store, options) { - var key = options.key; - var change = DS.RelationshipChange._createChange({ - parentRecord: parentRecord, - childRecord: childRecord, - firstRecord: childRecord, - store: store, - changeType: options.changeType, - firstRecordName: key, - firstRecordKind: "belongsTo" - }); - - store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); - - return change; -}; - -DS.ManyToNoneChange.createChange = function(childRecord, parentRecord, store, options) { - var key = options.key; - var change = DS.RelationshipChange._createChange({ - parentRecord: childRecord, - childRecord: parentRecord, - secondRecord: childRecord, - store: store, - changeType: options.changeType, - secondRecordName: options.key, - secondRecordKind: "hasMany" - }); - - store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); - return change; -}; - - -DS.ManyToManyChange.createChange = function(childRecord, parentRecord, store, options) { - // If the name of the belongsTo side of the relationship is specified, - // use that - // If the type of the parent is specified, look it up on the child's type - // definition. - var key = options.key; - - var change = DS.RelationshipChange._createChange({ - parentRecord: parentRecord, - childRecord: childRecord, - firstRecord: childRecord, - secondRecord: parentRecord, - firstRecordKind: "hasMany", - secondRecordKind: "hasMany", - store: store, - changeType: options.changeType, - firstRecordName: key - }); - - store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); - - - return change; -}; - -DS.OneToOneChange.createChange = function(childRecord, parentRecord, store, options) { - var key; - - // If the name of the belongsTo side of the relationship is specified, - // use that - // If the type of the parent is specified, look it up on the child's type - // definition. - if (options.parentType) { - key = options.parentType.inverseFor(options.key).name; - } else if (options.key) { - key = options.key; - } else { - Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false); - } - - var change = DS.RelationshipChange._createChange({ - parentRecord: parentRecord, - childRecord: childRecord, - firstRecord: childRecord, - secondRecord: parentRecord, - firstRecordKind: "belongsTo", - secondRecordKind: "belongsTo", - store: store, - changeType: options.changeType, - firstRecordName: key - }); - - store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); - - - return change; -}; - -DS.OneToOneChange.maintainInvariant = function(options, store, childRecord, key){ - if (options.changeType === "add" && store.recordIsMaterialized(childRecord)) { - var oldParent = get(childRecord, key); - if (oldParent){ - var correspondingChange = DS.OneToOneChange.createChange(childRecord, oldParent, store, { - parentType: options.parentType, - hasManyName: options.hasManyName, - changeType: "remove", - key: options.key - }); - store.addRelationshipChangeFor(childRecord, key, options.parentRecord , null, correspondingChange); - correspondingChange.sync(); - } - } -}; - -DS.OneToManyChange.createChange = function(childRecord, parentRecord, store, options) { - var key; - - // If the name of the belongsTo side of the relationship is specified, - // use that - // If the type of the parent is specified, look it up on the child's type - // definition. - if (options.parentType) { - key = options.parentType.inverseFor(options.key).name; - DS.OneToManyChange.maintainInvariant( options, store, childRecord, key ); - } else if (options.key) { - key = options.key; - } else { - Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false); - } - - var change = DS.RelationshipChange._createChange({ - parentRecord: parentRecord, - childRecord: childRecord, - firstRecord: childRecord, - secondRecord: parentRecord, - firstRecordKind: "belongsTo", - secondRecordKind: "hasMany", - store: store, - changeType: options.changeType, - firstRecordName: key - }); - - store.addRelationshipChangeFor(childRecord, key, parentRecord, change.getSecondRecordName(), change); - - - return change; -}; - - -DS.OneToManyChange.maintainInvariant = function(options, store, childRecord, key){ - if (options.changeType === "add" && childRecord) { - var oldParent = get(childRecord, key); - if (oldParent){ - var correspondingChange = DS.OneToManyChange.createChange(childRecord, oldParent, store, { - parentType: options.parentType, - hasManyName: options.hasManyName, - changeType: "remove", - key: options.key - }); - store.addRelationshipChangeFor(childRecord, key, options.parentRecord, correspondingChange.getSecondRecordName(), correspondingChange); - correspondingChange.sync(); - } - } -}; - -/** - @class RelationshipChange - @namespace DS -*/ -DS.RelationshipChange.prototype = { - - getSecondRecordName: function() { - var name = this.secondRecordName, parent; - - if (!name) { - parent = this.secondRecord; - if (!parent) { return; } - - var childType = this.firstRecord.constructor; - var inverse = childType.inverseFor(this.firstRecordName); - this.secondRecordName = inverse.name; - } - - return this.secondRecordName; - }, - - /** - Get the name of the relationship on the belongsTo side. - - @method getFirstRecordName - @return {String} - */ - getFirstRecordName: function() { - var name = this.firstRecordName; - return name; - }, - - /** - @method destroy - @private - */ - destroy: function() { - var childRecord = this.childRecord, - belongsToName = this.getFirstRecordName(), - hasManyName = this.getSecondRecordName(), - store = this.store; - - store.removeRelationshipChangeFor(childRecord, belongsToName, this.parentRecord, hasManyName, this.changeType); - }, - - getSecondRecord: function(){ - return this.secondRecord; - }, - - /** - @method getFirstRecord - @private - */ - getFirstRecord: function() { - return this.firstRecord; - }, - - coalesce: function(){ - var relationshipPairs = this.store.relationshipChangePairsFor(this.firstRecord); - forEach(relationshipPairs, function(pair){ - var addedChange = pair["add"]; - var removedChange = pair["remove"]; - if(addedChange && removedChange) { - addedChange.destroy(); - removedChange.destroy(); - } - }); - } -}; - -DS.RelationshipChangeAdd.prototype = Ember.create(DS.RelationshipChange.create({})); -DS.RelationshipChangeRemove.prototype = Ember.create(DS.RelationshipChange.create({})); - -// the object is a value, and not a promise -function isValue(object) { - return typeof object === 'object' && (!object.then || typeof object.then !== 'function'); -} - -DS.RelationshipChangeAdd.prototype.changeType = "add"; -DS.RelationshipChangeAdd.prototype.sync = function() { - var secondRecordName = this.getSecondRecordName(), - firstRecordName = this.getFirstRecordName(), - firstRecord = this.getFirstRecord(), - secondRecord = this.getSecondRecord(); - - //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); - //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); - - if (secondRecord instanceof DS.Model && firstRecord instanceof DS.Model) { - if(this.secondRecordKind === "belongsTo"){ - secondRecord.suspendRelationshipObservers(function(){ - set(secondRecord, secondRecordName, firstRecord); - }); - - } - else if(this.secondRecordKind === "hasMany"){ - secondRecord.suspendRelationshipObservers(function(){ - var relationship = get(secondRecord, secondRecordName); - if (isValue(relationship)) { relationship.addObject(firstRecord); } - }); - } - } - - if (firstRecord instanceof DS.Model && secondRecord instanceof DS.Model && get(firstRecord, firstRecordName) !== secondRecord) { - if(this.firstRecordKind === "belongsTo"){ - firstRecord.suspendRelationshipObservers(function(){ - set(firstRecord, firstRecordName, secondRecord); - }); - } - else if(this.firstRecordKind === "hasMany"){ - firstRecord.suspendRelationshipObservers(function(){ - var relationship = get(firstRecord, firstRecordName); - if (isValue(relationship)) { relationship.addObject(secondRecord); } - }); - } - } - - this.coalesce(); -}; - -DS.RelationshipChangeRemove.prototype.changeType = "remove"; -DS.RelationshipChangeRemove.prototype.sync = function() { - var secondRecordName = this.getSecondRecordName(), - firstRecordName = this.getFirstRecordName(), - firstRecord = this.getFirstRecord(), - secondRecord = this.getSecondRecord(); - - //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); - //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); - - if (secondRecord instanceof DS.Model && firstRecord instanceof DS.Model) { - if(this.secondRecordKind === "belongsTo"){ - secondRecord.suspendRelationshipObservers(function(){ - set(secondRecord, secondRecordName, null); - }); - } - else if(this.secondRecordKind === "hasMany"){ - secondRecord.suspendRelationshipObservers(function(){ - var relationship = get(secondRecord, secondRecordName); - if (isValue(relationship)) { relationship.removeObject(firstRecord); } - }); - } - } - - if (firstRecord instanceof DS.Model && get(firstRecord, firstRecordName)) { - if(this.firstRecordKind === "belongsTo"){ - firstRecord.suspendRelationshipObservers(function(){ - set(firstRecord, firstRecordName, null); - }); - } - else if(this.firstRecordKind === "hasMany"){ - firstRecord.suspendRelationshipObservers(function(){ - var relationship = get(firstRecord, firstRecordName); - if (isValue(relationship)) { relationship.removeObject(secondRecord); } - }); - } - } - - this.coalesce(); -}; - -})(); - - - -(function() { -/** - @module ember-data -*/ - -})(); - - - -(function() { -var get = Ember.get, set = Ember.set, - isNone = Ember.isNone; - -/** - @module ember-data -*/ - -function asyncBelongsTo(type, options, meta) { - return Ember.computed(function(key, value) { - var data = get(this, 'data'), - store = get(this, 'store'), - promiseLabel = "DS: Async belongsTo " + this + " : " + key; - - if (arguments.length === 2) { - Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof store.modelFor(type)); - return value === undefined ? null : DS.PromiseObject.create({ promise: Ember.RSVP.resolve(value, promiseLabel) }); - } - - var link = data.links && data.links[key], - belongsTo = data[key]; - - if(!isNone(belongsTo)) { - var promise = store.fetchRecord(belongsTo) || Ember.RSVP.resolve(belongsTo, promiseLabel); - return DS.PromiseObject.create({ promise: promise}); - } else if (link) { - var resolver = Ember.RSVP.defer("DS: Async belongsTo (link) " + this + " : " + key); - store.findBelongsTo(this, link, meta, resolver); - return DS.PromiseObject.create({ promise: resolver.promise }); - } else { - return null; - } - }).property('data').meta(meta); -} - -/** - `DS.belongsTo` is used to define One-To-One and One-To-Many - relationships on a [DS.Model](DS.Model.html). - - - `DS.belongsTo` takes an optional hash as a second parameter, currently - supported options are: - - - `async`: A boolean value used to explicitly declare this to be an async relationship. - - `inverse`: A string used to identify the inverse property on a - related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses) - - #### One-To-One - To declare a one-to-one relationship between two models, use - `DS.belongsTo`: - - ```javascript - App.User = DS.Model.extend({ - profile: DS.belongsTo('profile') - }); - - App.Profile = DS.Model.extend({ - user: DS.belongsTo('user') - }); - ``` - - #### One-To-Many - To declare a one-to-many relationship between two models, use - `DS.belongsTo` in combination with `DS.hasMany`, like this: - - ```javascript - App.Post = DS.Model.extend({ - comments: DS.hasMany('comment') - }); - - App.Comment = DS.Model.extend({ - post: DS.belongsTo('post') - }); - ``` - - @namespace - @method belongsTo - @for DS - @param {String or DS.Model} type the model type of the relationship - @param {Object} options a hash of options - @return {Ember.computed} relationship -*/ -DS.belongsTo = function(type, options) { - if (typeof type === 'object') { - options = type; - type = undefined; - } else { - Ember.assert("The first argument DS.belongsTo must be a model type or string, like DS.belongsTo(App.Person)", !!type && (typeof type === 'string' || DS.Model.detect(type))); - } - - options = options || {}; - - var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo' }; - - if (options.async) { - return asyncBelongsTo(type, options, meta); - } - - return Ember.computed(function(key, value) { - var data = get(this, 'data'), - store = get(this, 'store'), belongsTo, typeClass; - - if (typeof type === 'string') { - typeClass = store.modelFor(type); - } else { - typeClass = type; - } - - if (arguments.length === 2) { - Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof typeClass); - return value === undefined ? null : value; - } - - belongsTo = data[key]; - - if (isNone(belongsTo)) { return null; } - - store.fetchRecord(belongsTo); - - return belongsTo; - }).property('data').meta(meta); -}; - -/** - These observers observe all `belongsTo` relationships on the record. See - `relationships/ext` to see how these observers get their dependencies. - - @class Model - @namespace DS -*/ -DS.Model.reopen({ - - /** - @method belongsToWillChange - @private - @static - @param record - @param key - */ - belongsToWillChange: Ember.beforeObserver(function(record, key) { - if (get(record, 'isLoaded')) { - var oldParent = get(record, key); - - if (oldParent) { - var store = get(record, 'store'), - change = DS.RelationshipChange.createChange(record, oldParent, store, { key: key, kind: "belongsTo", changeType: "remove" }); - - change.sync(); - this._changesToSync[key] = change; - } - } - }), - - /** - @method belongsToDidChange - @private - @static - @param record - @param key - */ - belongsToDidChange: Ember.immediateObserver(function(record, key) { - if (get(record, 'isLoaded')) { - var newParent = get(record, key); - - if (newParent) { - var store = get(record, 'store'), - change = DS.RelationshipChange.createChange(record, newParent, store, { key: key, kind: "belongsTo", changeType: "add" }); - - change.sync(); - } - } - - delete this._changesToSync[key]; - }) -}); - -})(); - - - -(function() { -/** - @module ember-data -*/ - -var get = Ember.get, set = Ember.set, setProperties = Ember.setProperties; - -function asyncHasMany(type, options, meta) { - return Ember.computed(function(key, value) { - var relationship = this._relationships[key], - promiseLabel = "DS: Async hasMany " + this + " : " + key; - - if (!relationship) { - var resolver = Ember.RSVP.defer(promiseLabel); - relationship = buildRelationship(this, key, options, function(store, data) { - var link = data.links && data.links[key]; - var rel; - if (link) { - rel = store.findHasMany(this, link, meta, resolver); - } else { - rel = store.findMany(this, data[key], meta.type, resolver); - } - // cache the promise so we can use it - // when we come back and don't need to rebuild - // the relationship. - set(rel, 'promise', resolver.promise); - return rel; - }); - } - - var promise = relationship.get('promise').then(function() { - return relationship; - }, null, "DS: Async hasMany records received"); - - return DS.PromiseArray.create({ promise: promise }); - }).property('data').meta(meta); -} - -function buildRelationship(record, key, options, callback) { - var rels = record._relationships; - - if (rels[key]) { return rels[key]; } - - var data = get(record, 'data'), - store = get(record, 'store'); - - var relationship = rels[key] = callback.call(record, store, data); - - return setProperties(relationship, { - owner: record, name: key, isPolymorphic: options.polymorphic - }); -} - -function hasRelationship(type, options) { - options = options || {}; - - var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany' }; - - if (options.async) { - return asyncHasMany(type, options, meta); - } - - return Ember.computed(function(key, value) { - return buildRelationship(this, key, options, function(store, data) { - var records = data[key]; - Ember.assert("You looked up the '" + key + "' relationship on '" + this + "' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)", Ember.A(records).everyProperty('isEmpty', false)); - return store.findMany(this, data[key], meta.type); - }); - }).property('data').meta(meta); -} - -/** - `DS.hasMany` is used to define One-To-Many and Many-To-Many - relationships on a [DS.Model](DS.Model.html). - - `DS.hasMany` takes an optional hash as a second parameter, currently - supported options are: - - - `async`: A boolean value used to explicitly declare this to be an async relationship. - - `inverse`: A string used to identify the inverse property on a related model. - - #### One-To-Many - To declare a one-to-many relationship between two models, use - `DS.belongsTo` in combination with `DS.hasMany`, like this: - - ```javascript - App.Post = DS.Model.extend({ - comments: DS.hasMany('comment') - }); - - App.Comment = DS.Model.extend({ - post: DS.belongsTo('post') - }); - ``` - - #### Many-To-Many - To declare a many-to-many relationship between two models, use - `DS.hasMany`: - - ```javascript - App.Post = DS.Model.extend({ - tags: DS.hasMany('tag') - }); - - App.Tag = DS.Model.extend({ - posts: DS.hasMany('post') - }); - ``` - - #### Explicit Inverses - - Ember Data will do its best to discover which relationships map to - one another. In the one-to-many code above, for example, Ember Data - can figure out that changing the `comments` relationship should update - the `post` relationship on the inverse because post is the only - relationship to that model. - - However, sometimes you may have multiple `belongsTo`/`hasManys` for the - same type. You can specify which property on the related model is - the inverse using `DS.hasMany`'s `inverse` option: - - ```javascript - var belongsTo = DS.belongsTo, - hasMany = DS.hasMany; - - App.Comment = DS.Model.extend({ - onePost: belongsTo('post'), - twoPost: belongsTo('post'), - redPost: belongsTo('post'), - bluePost: belongsTo('post') - }); - - App.Post = DS.Model.extend({ - comments: hasMany('comment', { - inverse: 'redPost' - }) - }); - ``` - - You can also specify an inverse on a `belongsTo`, which works how - you'd expect. - - @namespace - @method hasMany - @for DS - @param {String or DS.Model} type the model type of the relationship - @param {Object} options a hash of options - @return {Ember.computed} relationship -*/ -DS.hasMany = function(type, options) { - if (typeof type === 'object') { - options = type; - type = undefined; - } - return hasRelationship(type, options); -}; - -})(); - - - -(function() { -var get = Ember.get, set = Ember.set; - -/** - @module ember-data -*/ - -/* - This file defines several extensions to the base `DS.Model` class that - add support for one-to-many relationships. -*/ - -/** - @class Model - @namespace DS -*/ -DS.Model.reopen({ - - /** - This Ember.js hook allows an object to be notified when a property - is defined. - - In this case, we use it to be notified when an Ember Data user defines a - belongs-to relationship. In that case, we need to set up observers for - each one, allowing us to track relationship changes and automatically - reflect changes in the inverse has-many array. - - This hook passes the class being set up, as well as the key and value - being defined. So, for example, when the user does this: - - ```javascript - DS.Model.extend({ - parent: DS.belongsTo('user') - }); - ``` - - This hook would be called with "parent" as the key and the computed - property returned by `DS.belongsTo` as the value. - - @method didDefineProperty - @param proto - @param key - @param value - */ - didDefineProperty: function(proto, key, value) { - // Check if the value being set is a computed property. - if (value instanceof Ember.Descriptor) { - - // If it is, get the metadata for the relationship. This is - // populated by the `DS.belongsTo` helper when it is creating - // the computed property. - var meta = value.meta(); - - if (meta.isRelationship && meta.kind === 'belongsTo') { - Ember.addObserver(proto, key, null, 'belongsToDidChange'); - Ember.addBeforeObserver(proto, key, null, 'belongsToWillChange'); - } - - meta.parentType = proto.constructor; - } - } -}); - -/* - These DS.Model extensions add class methods that provide relationship - introspection abilities about relationships. - - A note about the computed properties contained here: - - **These properties are effectively sealed once called for the first time.** - To avoid repeatedly doing expensive iteration over a model's fields, these - values are computed once and then cached for the remainder of the runtime of - your application. - - If your application needs to modify a class after its initial definition - (for example, using `reopen()` to add additional attributes), make sure you - do it before using your model with the store, which uses these properties - extensively. -*/ - -DS.Model.reopenClass({ - /** - For a given relationship name, returns the model type of the relationship. - - For example, if you define a model like this: - - ```javascript - App.Post = DS.Model.extend({ - comments: DS.hasMany('comment') - }); - ``` - - Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`. - - @method typeForRelationship - @static - @param {String} name the name of the relationship - @return {subclass of DS.Model} the type of the relationship, or undefined - */ - typeForRelationship: function(name) { - var relationship = get(this, 'relationshipsByName').get(name); - return relationship && relationship.type; - }, - - inverseFor: function(name) { - var inverseType = this.typeForRelationship(name); - - if (!inverseType) { return null; } - - var options = this.metaForProperty(name).options; - - if (options.inverse === null) { return null; } - - var inverseName, inverseKind; - - if (options.inverse) { - inverseName = options.inverse; - inverseKind = Ember.get(inverseType, 'relationshipsByName').get(inverseName).kind; - } else { - var possibleRelationships = findPossibleInverses(this, inverseType); - - if (possibleRelationships.length === 0) { return null; } - - Ember.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", possibleRelationships.length === 1); - - inverseName = possibleRelationships[0].name; - inverseKind = possibleRelationships[0].kind; - } - - function findPossibleInverses(type, inverseType, possibleRelationships) { - possibleRelationships = possibleRelationships || []; - - var relationshipMap = get(inverseType, 'relationships'); - if (!relationshipMap) { return; } - - var relationships = relationshipMap.get(type); - if (relationships) { - possibleRelationships.push.apply(possibleRelationships, relationshipMap.get(type)); - } - - if (type.superclass) { - findPossibleInverses(type.superclass, inverseType, possibleRelationships); - } - - return possibleRelationships; - } - - return { - type: inverseType, - name: inverseName, - kind: inverseKind - }; - }, - - /** - The model's relationships as a map, keyed on the type of the - relationship. The value of each entry is an array containing a descriptor - for each relationship with that type, describing the name of the relationship - as well as the type. - - For example, given the following model definition: - - ```javascript - App.Blog = DS.Model.extend({ - users: DS.hasMany('user'), - owner: DS.belongsTo('user'), - posts: DS.hasMany('post') - }); - ``` - - This computed property would return a map describing these - relationships, like this: - - ```javascript - var relationships = Ember.get(App.Blog, 'relationships'); - relationships.get(App.User); - //=> [ { name: 'users', kind: 'hasMany' }, - // { name: 'owner', kind: 'belongsTo' } ] - relationships.get(App.Post); - //=> [ { name: 'posts', kind: 'hasMany' } ] - ``` - - @property relationships - @static - @type Ember.Map - @readOnly - */ - relationships: Ember.computed(function() { - var map = new Ember.MapWithDefault({ - defaultValue: function() { return []; } - }); - - // Loop through each computed property on the class - this.eachComputedProperty(function(name, meta) { - - // If the computed property is a relationship, add - // it to the map. - if (meta.isRelationship) { - if (typeof meta.type === 'string') { - meta.type = this.store.modelFor(meta.type); - } - - var relationshipsForType = map.get(meta.type); - - relationshipsForType.push({ name: name, kind: meta.kind }); - } - }); - - return map; - }), - - /** - A hash containing lists of the model's relationships, grouped - by the relationship kind. For example, given a model with this - definition: - - ```javascript - App.Blog = DS.Model.extend({ - users: DS.hasMany('user'), - owner: DS.belongsTo('user'), - - posts: DS.hasMany('post') - }); - ``` - - This property would contain the following: - - ```javascript - var relationshipNames = Ember.get(App.Blog, 'relationshipNames'); - relationshipNames.hasMany; - //=> ['users', 'posts'] - relationshipNames.belongsTo; - //=> ['owner'] - ``` - - @property relationshipNames - @static - @type Object - @readOnly - */ - relationshipNames: Ember.computed(function() { - var names = { hasMany: [], belongsTo: [] }; - - this.eachComputedProperty(function(name, meta) { - if (meta.isRelationship) { - names[meta.kind].push(name); - } - }); - - return names; - }), - - /** - An array of types directly related to a model. Each type will be - included once, regardless of the number of relationships it has with - the model. - - For example, given a model with this definition: - - ```javascript - App.Blog = DS.Model.extend({ - users: DS.hasMany('user'), - owner: DS.belongsTo('user'), - - posts: DS.hasMany('post') - }); - ``` - - This property would contain the following: - - ```javascript - var relatedTypes = Ember.get(App.Blog, 'relatedTypes'); - //=> [ App.User, App.Post ] - ``` - - @property relatedTypes - @static - @type Ember.Array - @readOnly - */ - relatedTypes: Ember.computed(function() { - var type, - types = Ember.A(); - - // Loop through each computed property on the class, - // and create an array of the unique types involved - // in relationships - this.eachComputedProperty(function(name, meta) { - if (meta.isRelationship) { - type = meta.type; - - if (typeof type === 'string') { - type = get(this, type, false) || this.store.modelFor(type); - } - - Ember.assert("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", type); - - if (!types.contains(type)) { - Ember.assert("Trying to sideload " + name + " on " + this.toString() + " but the type doesn't exist.", !!type); - types.push(type); - } - } - }); - - return types; - }), - - /** - A map whose keys are the relationships of a model and whose values are - relationship descriptors. - - For example, given a model with this - definition: - - ```javascript - App.Blog = DS.Model.extend({ - users: DS.hasMany('user'), - owner: DS.belongsTo('user'), - - posts: DS.hasMany('post') - }); - ``` - - This property would contain the following: - - ```javascript - var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName'); - relationshipsByName.get('users'); - //=> { key: 'users', kind: 'hasMany', type: App.User } - relationshipsByName.get('owner'); - //=> { key: 'owner', kind: 'belongsTo', type: App.User } - ``` - - @property relationshipsByName - @static - @type Ember.Map - @readOnly - */ - relationshipsByName: Ember.computed(function() { - var map = Ember.Map.create(), type; - - this.eachComputedProperty(function(name, meta) { - if (meta.isRelationship) { - meta.key = name; - type = meta.type; - - if (!type && meta.kind === 'hasMany') { - type = Ember.String.singularize(name); - } else if (!type) { - type = name; - } - - if (typeof type === 'string') { - meta.type = this.store.modelFor(type); - } - - map.set(name, meta); - } - }); - - return map; - }), - - /** - A map whose keys are the fields of the model and whose values are strings - describing the kind of the field. A model's fields are the union of all of its - attributes and relationships. - - For example: - - ```javascript - - App.Blog = DS.Model.extend({ - users: DS.hasMany('user'), - owner: DS.belongsTo('user'), - - posts: DS.hasMany('post'), - - title: DS.attr('string') - }); - - var fields = Ember.get(App.Blog, 'fields'); - fields.forEach(function(field, kind) { - console.log(field, kind); - }); - - // prints: - // users, hasMany - // owner, belongsTo - // posts, hasMany - // title, attribute - ``` - - @property fields - @static - @type Ember.Map - @readOnly - */ - fields: Ember.computed(function() { - var map = Ember.Map.create(); - - this.eachComputedProperty(function(name, meta) { - if (meta.isRelationship) { - map.set(name, meta.kind); - } else if (meta.isAttribute) { - map.set(name, 'attribute'); - } - }); - - return map; - }), - - /** - Given a callback, iterates over each of the relationships in the model, - invoking the callback with the name of each relationship and its relationship - descriptor. - - @method eachRelationship - @static - @param {Function} callback the callback to invoke - @param {any} binding the value to which the callback's `this` should be bound - */ - eachRelationship: function(callback, binding) { - get(this, 'relationshipsByName').forEach(function(name, relationship) { - callback.call(binding, name, relationship); - }); - }, - - /** - Given a callback, iterates over each of the types related to a model, - invoking the callback with the related type's class. Each type will be - returned just once, regardless of how many different relationships it has - with a model. - - @method eachRelatedType - @static - @param {Function} callback the callback to invoke - @param {any} binding the value to which the callback's `this` should be bound - */ - eachRelatedType: function(callback, binding) { - get(this, 'relatedTypes').forEach(function(type) { - callback.call(binding, type); - }); - } -}); - -DS.Model.reopen({ - /** - Given a callback, iterates over each of the relationships in the model, - invoking the callback with the name of each relationship and its relationship - descriptor. - - @method eachRelationship - @param {Function} callback the callback to invoke - @param {any} binding the value to which the callback's `this` should be bound - */ - eachRelationship: function(callback, binding) { - this.constructor.eachRelationship(callback, binding); - } -}); - -})(); - - - -(function() { -/** - @module ember-data -*/ - -})(); - - - -(function() { -/** - @module ember-data -*/ - -var get = Ember.get, set = Ember.set; -var forEach = Ember.EnumerableUtils.forEach; - -/** - @class RecordArrayManager - @namespace DS - @private - @extends Ember.Object -*/ -DS.RecordArrayManager = Ember.Object.extend({ - init: function() { - this.filteredRecordArrays = Ember.MapWithDefault.create({ - defaultValue: function() { return []; } - }); - - this.changedRecords = []; - }, - - recordDidChange: function(record) { - if (this.changedRecords.push(record) !== 1) { return; } - - Ember.run.schedule('actions', this, this.updateRecordArrays); - }, - - recordArraysForRecord: function(record) { - record._recordArrays = record._recordArrays || Ember.OrderedSet.create(); - return record._recordArrays; - }, - - /** - This method is invoked whenever data is loaded into the store by the - adapter or updated by the adapter, or when a record has changed. - - It updates all record arrays that a record belongs to. - - To avoid thrashing, it only runs at most once per run loop. - - @method updateRecordArrays - @param {Class} type - @param {Number|String} clientId - */ - updateRecordArrays: function() { - forEach(this.changedRecords, function(record) { - if (get(record, 'isDeleted')) { - this._recordWasDeleted(record); - } else { - this._recordWasChanged(record); - } - }, this); - - this.changedRecords.length = 0; - }, - - _recordWasDeleted: function (record) { - var recordArrays = record._recordArrays; - - if (!recordArrays) { return; } - - forEach(recordArrays, function(array) { - array.removeRecord(record); - }); - }, - - _recordWasChanged: function (record) { - var type = record.constructor, - recordArrays = this.filteredRecordArrays.get(type), - filter; - - forEach(recordArrays, function(array) { - filter = get(array, 'filterFunction'); - this.updateRecordArray(array, filter, type, record); - }, this); - - // loop through all manyArrays containing an unloaded copy of this - // clientId and notify them that the record was loaded. - var manyArrays = record._loadingRecordArrays; - - if (manyArrays) { - for (var i=0, l=manyArrays.length; i 'kine' - inflector.singularize('kine') //=> 'cow' - ``` - - Creating an inflector and adding rules later. - - ```javascript - var inflector = Ember.Inflector.inflector; - - inflector.pluralize('advice') // => 'advices' - inflector.uncountable('advice'); - inflector.pluralize('advice') // => 'advice' - - inflector.pluralize('formula') // => 'formulas' - inflector.irregular('formula', 'formulae'); - inflector.pluralize('formula') // => 'formulae' - - // you would not need to add these as they are the default rules - inflector.plural(/$/, 's'); - inflector.singular(/s$/i, ''); - ``` - - Creating an inflector with a nondefault ruleset. - - ```javascript - var rules = { - plurals: [ /$/, 's' ], - singular: [ /\s$/, '' ], - irregularPairs: [ - [ 'cow', 'kine' ] - ], - uncountable: [ 'fish' ] - }; - - var inflector = new Ember.Inflector(rules); - ``` - - @class Inflector - @namespace Ember -*/ -function Inflector(ruleSet) { - ruleSet = ruleSet || {}; - ruleSet.uncountable = ruleSet.uncountable || {}; - ruleSet.irregularPairs = ruleSet.irregularPairs || {}; - - var rules = this.rules = { - plurals: ruleSet.plurals || [], - singular: ruleSet.singular || [], - irregular: {}, - irregularInverse: {}, - uncountable: {} - }; - - loadUncountable(rules, ruleSet.uncountable); - loadIrregular(rules, ruleSet.irregularPairs); -} - -Inflector.prototype = { - /** - @method plural - @param {RegExp} regex - @param {String} string - */ - plural: function(regex, string) { - this.rules.plurals.push([regex, string.toLowerCase()]); - }, - - /** - @method singular - @param {RegExp} regex - @param {String} string - */ - singular: function(regex, string) { - this.rules.singular.push([regex, string.toLowerCase()]); - }, - - /** - @method uncountable - @param {String} regex - */ - uncountable: function(string) { - loadUncountable(this.rules, [string.toLowerCase()]); - }, - - /** - @method irregular - @param {String} singular - @param {String} plural - */ - irregular: function (singular, plural) { - loadIrregular(this.rules, [[singular, plural]]); - }, - - /** - @method pluralize - @param {String} word - */ - pluralize: function(word) { - return this.inflect(word, this.rules.plurals, this.rules.irregular); - }, - - /** - @method singularize - @param {String} word - */ - singularize: function(word) { - return this.inflect(word, this.rules.singular, this.rules.irregularInverse); - }, - - /** - @protected - - @method inflect - @param {String} word - @param {Object} typeRules - @param {Object} irregular - */ - inflect: function(word, typeRules, irregular) { - var inflection, substitution, result, lowercase, isBlank, - isUncountable, isIrregular, isIrregularInverse, rule; - - isBlank = BLANK_REGEX.test(word); - - if (isBlank) { - return word; - } - - lowercase = word.toLowerCase(); - - isUncountable = this.rules.uncountable[lowercase]; - - if (isUncountable) { - return word; - } - - isIrregular = irregular && irregular[lowercase]; - - if (isIrregular) { - return isIrregular; - } - - for (var i = typeRules.length, min = 0; i > min; i--) { - inflection = typeRules[i-1]; - rule = inflection[0]; - - if (rule.test(word)) { - break; - } - } - - inflection = inflection || []; - - rule = inflection[0]; - substitution = inflection[1]; - - result = word.replace(rule, substitution); - - return result; - } -}; - -Ember.Inflector = Inflector; - -})(); - - - -(function() { -Ember.Inflector.defaultRules = { - plurals: [ - [/$/, 's'], - [/s$/i, 's'], - [/^(ax|test)is$/i, '$1es'], - [/(octop|vir)us$/i, '$1i'], - [/(octop|vir)i$/i, '$1i'], - [/(alias|status)$/i, '$1es'], - [/(bu)s$/i, '$1ses'], - [/(buffal|tomat)o$/i, '$1oes'], - [/([ti])um$/i, '$1a'], - [/([ti])a$/i, '$1a'], - [/sis$/i, 'ses'], - [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], - [/(hive)$/i, '$1s'], - [/([^aeiouy]|qu)y$/i, '$1ies'], - [/(x|ch|ss|sh)$/i, '$1es'], - [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], - [/^(m|l)ouse$/i, '$1ice'], - [/^(m|l)ice$/i, '$1ice'], - [/^(ox)$/i, '$1en'], - [/^(oxen)$/i, '$1'], - [/(quiz)$/i, '$1zes'] - ], - - singular: [ - [/s$/i, ''], - [/(ss)$/i, '$1'], - [/(n)ews$/i, '$1ews'], - [/([ti])a$/i, '$1um'], - [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], - [/(^analy)(sis|ses)$/i, '$1sis'], - [/([^f])ves$/i, '$1fe'], - [/(hive)s$/i, '$1'], - [/(tive)s$/i, '$1'], - [/([lr])ves$/i, '$1f'], - [/([^aeiouy]|qu)ies$/i, '$1y'], - [/(s)eries$/i, '$1eries'], - [/(m)ovies$/i, '$1ovie'], - [/(x|ch|ss|sh)es$/i, '$1'], - [/^(m|l)ice$/i, '$1ouse'], - [/(bus)(es)?$/i, '$1'], - [/(o)es$/i, '$1'], - [/(shoe)s$/i, '$1'], - [/(cris|test)(is|es)$/i, '$1is'], - [/^(a)x[ie]s$/i, '$1xis'], - [/(octop|vir)(us|i)$/i, '$1us'], - [/(alias|status)(es)?$/i, '$1'], - [/^(ox)en/i, '$1'], - [/(vert|ind)ices$/i, '$1ex'], - [/(matr)ices$/i, '$1ix'], - [/(quiz)zes$/i, '$1'], - [/(database)s$/i, '$1'] - ], - - irregularPairs: [ - ['person', 'people'], - ['man', 'men'], - ['child', 'children'], - ['sex', 'sexes'], - ['move', 'moves'], - ['cow', 'kine'], - ['zombie', 'zombies'] - ], - - uncountable: [ - 'equipment', - 'information', - 'rice', - 'money', - 'species', - 'series', - 'fish', - 'sheep', - 'jeans', - 'police' - ] -}; - -})(); - - - -(function() { -if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { - /** - See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}} - - @method pluralize - @for String - */ - String.prototype.pluralize = function() { - return Ember.String.pluralize(this); - }; - - /** - See {{#crossLink "Ember.String/singularize"}}{{/crossLink}} - - @method singularize - @for String - */ - String.prototype.singularize = function() { - return Ember.String.singularize(this); - }; -} - -})(); - - - -(function() { -Ember.Inflector.inflector = new Ember.Inflector(Ember.Inflector.defaultRules); - -})(); - - - -(function() { - -})(); - -(function() { -/** - @module ember-data -*/ - -var get = Ember.get, - forEach = Ember.EnumerableUtils.forEach, - camelize = Ember.String.camelize, - capitalize = Ember.String.capitalize, - decamelize = Ember.String.decamelize, - singularize = Ember.String.singularize, - underscore = Ember.String.underscore; - -DS.ActiveModelSerializer = DS.RESTSerializer.extend({ - // SERIALIZE - - /** - Converts camelcased attributes to underscored when serializing. - - @method keyForAttribute - @param {String} attribute - @returns String - */ - keyForAttribute: function(attr) { - return decamelize(attr); - }, - - /** - Underscores relationship names and appends "_id" or "_ids" when serializing - relationship keys. - - @method keyForRelationship - @param {String} key - @param {String} kind - @returns String - */ - keyForRelationship: function(key, kind) { - key = decamelize(key); - if (kind === "belongsTo") { - return key + "_id"; - } else if (kind === "hasMany") { - return singularize(key) + "_ids"; - } else { - return key; - } - }, - - /** - Does not serialize hasMany relationships by default. - */ - serializeHasMany: Ember.K, - - /** - Underscores the JSON root keys when serializing. - - @method serializeIntoHash - @param {Object} hash - @param {subclass of DS.Model} type - @param {DS.Model} record - @param {Object} options - */ - serializeIntoHash: function(data, type, record, options) { - var root = underscore(decamelize(type.typeKey)); - data[root] = this.serialize(record, options); - }, - - /** - Serializes a polymorphic type as a fully capitalized model name. - - @method serializePolymorphicType - @param {DS.Model} record - @param {Object} json - @param relationship - */ - serializePolymorphicType: function(record, json, relationship) { - var key = relationship.key, - belongsTo = get(record, key); - key = this.keyForAttribute(key); - json[key + "_type"] = capitalize(camelize(belongsTo.constructor.typeKey)); - }, - - // EXTRACT - - /** - Extracts the model typeKey from underscored root objects. - - @method typeForRoot - @param {String} root - @returns String the model's typeKey - */ - typeForRoot: function(root) { - var camelized = camelize(root); - return singularize(camelized); - }, - - /** - Add extra step to `DS.RESTSerializer.normalize` so links are - normalized. - - If your payload looks like this - - ```js - { - "post": { - "id": 1, - "title": "Rails is omakase", - "links": { "flagged_comments": "api/comments/flagged" } - } - } - ``` - The normalized version would look like this - - ```js - { - "post": { - "id": 1, - "title": "Rails is omakase", - "links": { "flaggedComments": "api/comments/flagged" } - } - } - ``` - - @method normalize - @param {subclass of DS.Model} type - @param {Object} hash - @param {String} prop - @returns Object - */ - - normalize: function(type, hash, prop) { - this.normalizeLinks(hash); - - return this._super(type, hash, prop); - }, - - /** - Convert `snake_cased` links to `camelCase` - - @method normalizeLinks - @param {Object} hash - */ - - normalizeLinks: function(data){ - if (data.links) { - var links = data.links; - - for (var link in links) { - var camelizedLink = camelize(link); - - if (camelizedLink !== link) { - links[camelizedLink] = links[link]; - delete links[link]; - } - } - } - }, - - /** - Normalize the polymorphic type from the JSON. - - Normalize: - ```js - { - id: "1" - minion: { type: "evil_minion", id: "12"} - } - ``` - - To: - ```js - { - id: "1" - minion: { type: "evilMinion", id: "12"} - } - ``` - - @method normalizeRelationships - @private - */ - normalizeRelationships: function(type, hash) { - var payloadKey, payload; - - if (this.keyForRelationship) { - type.eachRelationship(function(key, relationship) { - if (relationship.options.polymorphic) { - payloadKey = this.keyForAttribute(key); - payload = hash[payloadKey]; - if (payload && payload.type) { - payload.type = this.typeForRoot(payload.type); - } else if (payload && relationship.kind === "hasMany") { - var self = this; - forEach(payload, function(single) { - single.type = self.typeForRoot(single.type); - }); - } - } else { - payloadKey = this.keyForRelationship(key, relationship.kind); - payload = hash[payloadKey]; - } - - hash[key] = payload; - - if (key !== payloadKey) { - delete hash[payloadKey]; - } - }, this); - } - } -}); - -})(); - - - -(function() { -var get = Ember.get; -var forEach = Ember.EnumerableUtils.forEach; - -/** - The EmbeddedRecordsMixin allows you to add embedded record support to your - serializers. - To set up embedded records, you include the mixin into the serializer and then - define your embedded relations. - - ```js - App.PostSerializer = DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, { - attrs: { - comments: {embedded: 'always'} - } - }) - ``` - - Currently only `{embedded: 'always'}` records are supported. - - @class EmbeddedRecordsMixin - @namespace DS -*/ -DS.EmbeddedRecordsMixin = Ember.Mixin.create({ - - /** - Serialize has-may relationship when it is configured as embedded objects. - - @method serializeHasMany - */ - serializeHasMany: function(record, json, relationship) { - var key = relationship.key, - attrs = get(this, 'attrs'), - embed = attrs && attrs[key] && attrs[key].embedded === 'always'; - - if (embed) { - json[this.keyForAttribute(key)] = get(record, key).map(function(relation) { - var data = relation.serialize(), - primaryKey = get(this, 'primaryKey'); - - data[primaryKey] = get(relation, primaryKey); - - return data; - }, this); - } - }, - - /** - Extract embedded objects out of the payload for a single object - and add them as sideloaded objects instead. - - @method extractSingle - */ - extractSingle: function(store, primaryType, payload, recordId, requestType) { - var root = this.keyForAttribute(primaryType.typeKey), - partial = payload[root]; - - updatePayloadWithEmbedded(store, this, primaryType, partial, payload); - - return this._super(store, primaryType, payload, recordId, requestType); - }, - - /** - Extract embedded objects out of a standard payload - and add them as sideloaded objects instead. - - @method extractArray - */ - extractArray: function(store, type, payload) { - var root = this.keyForAttribute(type.typeKey), - partials = payload[Ember.String.pluralize(root)]; - - forEach(partials, function(partial) { - updatePayloadWithEmbedded(store, this, type, partial, payload); - }, this); - - return this._super(store, type, payload); - } -}); - -function updatePayloadWithEmbedded(store, serializer, type, partial, payload) { - var attrs = get(serializer, 'attrs'); - - if (!attrs) { - return; - } - - type.eachRelationship(function(key, relationship) { - var expandedKey, embeddedTypeKey, attribute, ids, - config = attrs[key], - serializer = store.serializerFor(relationship.type.typeKey), - primaryKey = get(serializer, "primaryKey"); - - if (relationship.kind !== "hasMany") { - return; - } - - if (config && (config.embedded === 'always' || config.embedded === 'load')) { - // underscore forces the embedded records to be side loaded. - // it is needed when main type === relationship.type - embeddedTypeKey = '_' + Ember.String.pluralize(relationship.type.typeKey); - expandedKey = this.keyForRelationship(key, relationship.kind); - attribute = this.keyForAttribute(key); - ids = []; - - if (!partial[attribute]) { - return; - } - - payload[embeddedTypeKey] = payload[embeddedTypeKey] || []; - - forEach(partial[attribute], function(data) { - var embeddedType = store.modelFor(relationship.type.typeKey); - updatePayloadWithEmbedded(store, serializer, embeddedType, data, payload); - ids.push(data[primaryKey]); - payload[embeddedTypeKey].push(data); - }); - - partial[expandedKey] = ids; - delete partial[attribute]; - } - }, serializer); -} -})(); - - - -(function() { -/** - @module ember-data -*/ - -var forEach = Ember.EnumerableUtils.forEach; -var decamelize = Ember.String.decamelize, - underscore = Ember.String.underscore, - pluralize = Ember.String.pluralize; - -/** - The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate - with a JSON API that uses an underscored naming convention instead of camelcasing. - It has been designed to work out of the box with the - [active_model_serializers](http://github.com/rails-api/active_model_serializers) - Ruby gem. - - This adapter extends the DS.RESTAdapter by making consistent use of the camelization, - decamelization and pluralization methods to normalize the serialized JSON into a - format that is compatible with a conventional Rails backend and Ember Data. - - ## JSON Structure - - The ActiveModelAdapter expects the JSON returned from your server to follow - the REST adapter conventions substituting underscored keys for camelcased ones. - - ### Conventional Names - - Attribute names in your JSON payload should be the underscored versions of - the attributes in your Ember.js models. - - For example, if you have a `Person` model: - - ```js - App.FamousPerson = DS.Model.extend({ - firstName: DS.attr('string'), - lastName: DS.attr('string'), - occupation: DS.attr('string') - }); - ``` - - The JSON returned should look like this: - - ```js - { - "famous_person": { - "first_name": "Barack", - "last_name": "Obama", - "occupation": "President" - } - } - ``` - - @class ActiveModelAdapter - @constructor - @namespace DS - @extends DS.Adapter -**/ - -DS.ActiveModelAdapter = DS.RESTAdapter.extend({ - defaultSerializer: '-active-model', - /** - The ActiveModelAdapter overrides the `pathForType` method to build - underscored URLs by decamelizing and pluralizing the object type name. - - ```js - this.pathForType("famousPerson"); - //=> "famous_people" - ``` - - @method pathForType - @param {String} type - @returns String - */ - pathForType: function(type) { - var decamelized = decamelize(type); - var underscored = underscore(decamelized); - return pluralize(underscored); - }, - - /** - The ActiveModelAdapter overrides the `ajaxError` method - to return a DS.InvalidError for all 422 Unprocessable Entity - responses. - - A 422 HTTP response from the server generally implies that the request - was well formed but the API was unable to process it because the - content was not semantically correct or meaningful per the API. - - For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918 - https://tools.ietf.org/html/rfc4918#section-11.2 - - @method ajaxError - @param jqXHR - @returns error - */ - ajaxError: function(jqXHR) { - var error = this._super(jqXHR); - - if (jqXHR && jqXHR.status === 422) { - var response = Ember.$.parseJSON(jqXHR.responseText), - errors = {}; - - if (response.errors !== undefined) { - var jsonErrors = response.errors; - - forEach(Ember.keys(jsonErrors), function(key) { - errors[Ember.String.camelize(key)] = jsonErrors[key]; - }); - } - - return new DS.InvalidError(errors); - } else { - return error; - } - } -}); - -})(); - - - -(function() { - -})(); - - - -(function() { -Ember.onLoad('Ember.Application', function(Application) { - Application.initializer({ - name: "activeModelAdapter", - - initialize: function(container, application) { - var proxy = new DS.ContainerProxy(container); - proxy.registerDeprecations([ - {deprecated: 'serializer:_ams', valid: 'serializer:-active-model'}, - {deprecated: 'adapter:_ams', valid: 'adapter:-active-model'} - ]); - - application.register('serializer:-active-model', DS.ActiveModelSerializer); - application.register('adapter:-active-model', DS.ActiveModelAdapter); - } - }); -}); - -})(); - - - -(function() { - -})(); - - -})(); - - -if (typeof location !== 'undefined' && (location.hostname === 'localhost' || location.hostname === '127.0.0.1')) { - Ember.Logger.warn("You are running a production build of Ember on localhost and won't receive detailed error messages. "+ - "If you want full error messages please use the non-minified build provided on the Ember website."); -} diff --git a/perf/todomvc-benchmark/todomvc/architecture-examples/emberjs/bower_components/ember/ember.min.js b/perf/todomvc-benchmark/todomvc/architecture-examples/emberjs/bower_components/ember/ember.min.js new file mode 100644 index 0000000000..ca6b4769b1 --- /dev/null +++ b/perf/todomvc-benchmark/todomvc/architecture-examples/emberjs/bower_components/ember/ember.min.js @@ -0,0 +1,19 @@ +/*! + * @overview Ember - JavaScript Application Framework + * @copyright Copyright 2011-2014 Tilde Inc. and contributors + * Portions Copyright 2006-2011 Strobe Inc. + * Portions Copyright 2008-2011 Apple Inc. All rights reserved. + * @license Licensed under MIT license + * See https://raw.github.com/emberjs/ember.js/master/LICENSE + * @version 1.5.0-beta.1+canary.dd10025a + */ +!function(){var e,t,r,n;!function(){var i={},o={};e=function(e,t,r){i[e]={deps:t,callback:r}},n=r=t=function(e){function r(t){if("."!==t.charAt(0))return t;for(var r=t.split("/"),n=e.split("/").slice(0,-1),i=0,o=r.length;o>i;i++){var a=r[i];if(".."===a)n.pop();else{if("."===a)continue;n.push(a)}}return n.join("/")}if(n._eak_seen=i,o[e])return o[e];if(o[e]={},!i[e])throw new Error("Could not find module "+e);for(var a,s=i[e],u=s.deps,l=s.callback,c=[],h=0,m=u.length;m>h;h++)"exports"===u[h]?c.push(a={}):c.push(t(r(u[h])));var p=l.apply(this,c);return o[e]=a||p}}(),function(){"undefined"==typeof Ember&&(Ember={});{var e=(Ember.imports=Ember.imports||this,Ember.exports=Ember.exports||this);Ember.lookup=Ember.lookup||this}e.Em=e.Ember=Em=Ember,Ember.isNamespace=!0,Ember.toString=function(){return"Ember"},Ember.VERSION="1.5.0-beta.1+canary.dd10025a",Ember.ENV||(Ember.ENV="undefined"!=typeof EmberENV?EmberENV:"undefined"!=typeof ENV?ENV:{}),Ember.config=Ember.config||{},"undefined"==typeof Ember.ENV.DISABLE_RANGE_API&&(Ember.ENV.DISABLE_RANGE_API=!0),"undefined"==typeof MetamorphENV&&(e.MetamorphENV={}),MetamorphENV.DISABLE_RANGE_API=Ember.ENV.DISABLE_RANGE_API,Ember.FEATURES=Ember.ENV.FEATURES||{},Ember.FEATURES.isEnabled=function(e){var t=Ember.FEATURES[e];return Ember.ENV.ENABLE_ALL_FEATURES?!0:t===!0||t===!1||void 0===t?t:Ember.ENV.ENABLE_OPTIONAL_FEATURES?!0:!1},Ember.EXTEND_PROTOTYPES=Ember.ENV.EXTEND_PROTOTYPES,"undefined"==typeof Ember.EXTEND_PROTOTYPES&&(Ember.EXTEND_PROTOTYPES=!0),Ember.LOG_STACKTRACE_ON_DEPRECATION=Ember.ENV.LOG_STACKTRACE_ON_DEPRECATION!==!1,Ember.SHIM_ES5=Ember.ENV.SHIM_ES5===!1?!1:Ember.EXTEND_PROTOTYPES,Ember.LOG_VERSION=Ember.ENV.LOG_VERSION===!1?!1:!0,Ember.K=function(){return this},"undefined"==typeof Ember.assert&&(Ember.assert=Ember.K),"undefined"==typeof Ember.warn&&(Ember.warn=Ember.K),"undefined"==typeof Ember.debug&&(Ember.debug=Ember.K),"undefined"==typeof Ember.deprecate&&(Ember.deprecate=Ember.K),"undefined"==typeof Ember.deprecateFunc&&(Ember.deprecateFunc=function(e,t){return t}),Ember.uuid=0,Ember.merge=function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);return e},Ember.isNone=function(e){return null===e||void 0===e},Ember.none=Ember.deprecateFunc("Ember.none is deprecated. Please use Ember.isNone instead.",Ember.isNone),Ember.isEmpty=function(e){return Ember.isNone(e)||0===e.length&&"function"!=typeof e||"object"==typeof e&&0===Ember.get(e,"length")},Ember.empty=Ember.deprecateFunc("Ember.empty is deprecated. Please use Ember.isEmpty instead.",Ember.isEmpty),Ember.isBlank=function(e){return Ember.isEmpty(e)||"string"==typeof e&&null===e.match(/\S/)}}(),function(){var e=Ember.platform={};if(Ember.create=Object.create,Ember.create&&2!==Ember.create({a:1},{a:{value:2}}).a&&(Ember.create=null),!Ember.create||Ember.ENV.STUB_OBJECT_CREATE){var t=function(){};Ember.create=function(e,r){if(t.prototype=e,e=new t,r){t.prototype=e;for(var n in r)t.prototype[n]=r[n].value;e=new t}return t.prototype=null,e},Ember.create.isSimulated=!0}var r,n,i=Object.defineProperty;if(i)try{i({},"a",{get:function(){}})}catch(o){i=null}i&&(r=function(){var e={};return i(e,"a",{configurable:!0,enumerable:!0,get:function(){},set:function(){}}),i(e,"a",{configurable:!0,enumerable:!0,writable:!0,value:!0}),e.a===!0}(),n=function(){try{return i(document.createElement("div"),"definePropertyOnDOM",{}),!0}catch(e){}return!1}(),r?n||(i=function(e,t,r){var n;return n="object"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName,n?e[t]=r.value:Object.defineProperty(e,t,r)}):i=null),e.defineProperty=i,e.hasPropertyAccessors=!0,e.defineProperty||(e.hasPropertyAccessors=!1,e.defineProperty=function(e,t,r){r.get||(e[t]=r.value)},e.defineProperty.isSimulated=!0),Ember.ENV.MANDATORY_SETTER&&!e.hasPropertyAccessors&&(Ember.ENV.MANDATORY_SETTER=!1)}(),function(){var e=function(e){return e&&Function.prototype.toString.call(e).indexOf("[native code]")>-1},t=e(Array.prototype.map)?Array.prototype.map:function(e){if(void 0===this||null===this)throw new TypeError;var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError;for(var n=new Array(r),i=arguments[1],o=0;r>o;o++)o in t&&(n[o]=e.call(i,t[o],o,t));return n},r=e(Array.prototype.forEach)?Array.prototype.forEach:function(e){if(void 0===this||null===this)throw new TypeError;var t=Object(this),r=t.length>>>0;if("function"!=typeof e)throw new TypeError;for(var n=arguments[1],i=0;r>i;i++)i in t&&e.call(n,t[i],i,t)},n=e(Array.prototype.indexOf)?Array.prototype.indexOf:function(e,t){null===t||void 0===t?t=0:0>t&&(t=Math.max(0,this.length+t));for(var r=t,n=this.length;n>r;r++)if(this[r]===e)return r;return-1},i=e(Array.prototype.filter)?Array.prototype.filter:function(e,t){var r,n,i=[],o=this.length;for(r=0;o>r;r++)this.hasOwnProperty(r)&&(n=this[r],e.call(t,n,r,this)&&i.push(n));return i};Ember.ArrayPolyfills={map:t,forEach:r,filter:i,indexOf:n},Ember.SHIM_ES5&&(Array.prototype.map||(Array.prototype.map=t),Array.prototype.forEach||(Array.prototype.forEach=r),Array.prototype.filter||(Array.prototype.filter=i),Array.prototype.indexOf||(Array.prototype.indexOf=n))}(),function(){var e=["description","fileName","lineNumber","message","name","number","stack"];Ember.Error=function(){var t=Error.apply(this,arguments);Error.captureStackTrace&&Error.captureStackTrace(this,Ember.Error);for(var r=0;rs;s++){if(i=t[s],o=a[i]){if(o.__ember_source__!==e){if(!r)return void 0;o=a[i]=n(o),o.__ember_source__=e}}else{if(!r)return void 0;o=a[i]={__ember_source__:e}}a=o}return o},Ember.wrap=function(e,t){function r(){var r,n=this.__nextSuper;return this.__nextSuper=t,r=e.apply(this,arguments),this.__nextSuper=n,r}return r.wrappedFunction=e,r.__ember_observes__=e.__ember_observes__,r.__ember_observesBefore__=e.__ember_observesBefore__,r.__ember_listens__=e.__ember_listens__,r},Ember.isArray=function(e){return!e||e.setInterval?!1:Array.isArray&&Array.isArray(e)?!0:Ember.Array&&Ember.Array.detect(e)?!0:void 0!==e.length&&"object"==typeof e?!0:!1},Ember.makeArray=function(e){return null===e||void 0===e?[]:Ember.isArray(e)?e:[e]},Ember.canInvoke=t,Ember.tryInvoke=function(e,r,n){return t(e,r)?e[r].apply(e,n||[]):void 0};var f=function(){var e=0;try{try{}finally{throw e++,new Error("needsFinallyFixTest")}}catch(t){}return 1!==e}();Ember.tryFinally=f?function(e,t,r){var n,i,o;r=r||this;try{n=e.call(r)}finally{try{i=t.call(r)}catch(a){o=a}}if(o)throw o;return void 0===i?n:i}:function(e,t,r){var n,i;r=r||this;try{n=e.call(r)}finally{i=t.call(r)}return void 0===i?n:i},Ember.tryCatchFinally=f?function(e,t,r,n){var i,o,a;n=n||this;try{i=e.call(n)}catch(s){i=t.call(n,s)}finally{try{o=r.call(n)}catch(u){a=u}}if(a)throw a;return void 0===o?i:o}:function(e,t,r,n){var i,o;n=n||this;try{i=e.call(n)}catch(a){i=t.call(n,a)}finally{o=r.call(n)}return void 0===o?i:o};var d={},b="Boolean Number String Function Array Date RegExp Object".split(" ");Ember.ArrayPolyfills.forEach.call(b,function(e){d["[object "+e+"]"]=e.toLowerCase()});var v=Object.prototype.toString;Ember.typeOf=function(e){var t;return t=null===e||void 0===e?String(e):d[v.call(e)]||"object","function"===t?Ember.Object&&Ember.Object.detect(e)&&(t="class"):"object"===t&&(e instanceof Error?t="error":Ember.Object&&e instanceof Ember.Object?t="instance":e instanceof Date&&(t="date")),t},Ember.inspect=function(e){var t=Ember.typeOf(e);if("array"===t)return"["+e+"]";if("object"!==t)return e+"";var r,n=[];for(var i in e)if(e.hasOwnProperty(i)){if(r=e[i],"toString"===r)continue;"function"===Ember.typeOf(r)&&(r="function() { ... }"),n.push(i+": "+r)}return"{"+n.join(", ")+"}"}}(),function(){Ember.Instrumentation={};var e=[],t={},r=function(r){for(var n,i=[],o=0,a=e.length;a>o;o++)n=e[o],n.regex.test(r)&&i.push(n.object);return t[r]=i,i},n=function(){var e="undefined"!=typeof window?window.performance||{}:{},t=e.now||e.mozNow||e.webkitNow||e.msNow||e.oNow;return t?t.bind(e):function(){return+new Date}}();Ember.Instrumentation.instrument=function(e,i,o,a){function s(){for(f=0,d=m.length;d>f;f++)p=m[f],b[f]=p.before(e,n(),i);return o.call(a)}function u(e){i=i||{},i.exception=e}function l(){for(f=0,d=m.length;d>f;f++)p=m[f],p.after(e,n(),i,b[f]);Ember.STRUCTURED_PROFILE&&console.timeEnd(c)}var c,h,m=t[e];if(Ember.STRUCTURED_PROFILE&&(c=e+": "+i.object,console.time(c)),m||(m=r(e)),0===m.length)return h=o.call(a),Ember.STRUCTURED_PROFILE&&console.timeEnd(c),h;var p,f,d,b=[];return Ember.tryCatchFinally(s,u,l)},Ember.Instrumentation.subscribe=function(r,n){for(var i,o=r.split("."),a=[],s=0,u=o.length;u>s;s++)i=o[s],"*"===i?a.push("[^\\.]*"):a.push(i);a=a.join("\\."),a+="(\\..*)?";var l={pattern:r,regex:new RegExp("^"+a+"$"),object:n};return e.push(l),t={},l},Ember.Instrumentation.unsubscribe=function(r){for(var n,i=0,o=e.length;o>i;i++)e[i]===r&&(n=i);e.splice(n,1),t={}},Ember.Instrumentation.reset=function(){e=[],t={}},Ember.instrument=Ember.Instrumentation.instrument,Ember.subscribe=Ember.Instrumentation.subscribe}(),function(){var e,t,r,n,i;e=Array.prototype.map||Ember.ArrayPolyfills.map,t=Array.prototype.forEach||Ember.ArrayPolyfills.forEach,r=Array.prototype.indexOf||Ember.ArrayPolyfills.indexOf,i=Array.prototype.filter||Ember.ArrayPolyfills.filter,n=Array.prototype.splice;var o=Ember.EnumerableUtils={map:function(t,r,n){return t.map?t.map.call(t,r,n):e.call(t,r,n)},forEach:function(e,r,n){return e.forEach?e.forEach.call(e,r,n):t.call(e,r,n)},filter:function(e,t,r){return e.filter?e.filter.call(e,t,r):i.call(e,t,r)},indexOf:function(e,t,n){return e.indexOf?e.indexOf.call(e,t,n):r.call(e,t,n)},indexesOf:function(e,t){return void 0===t?[]:o.map(t,function(t){return o.indexOf(e,t)})},addObject:function(e,t){var r=o.indexOf(e,t);-1===r&&e.push(t)},removeObject:function(e,t){var r=o.indexOf(e,t);-1!==r&&e.splice(r,1)},_replace:function(e,t,r,i){for(var o,a,s=[].concat(i),u=[],l=6e4,c=t,h=r;s.length;)a=h>l?l:h,0>=a&&(a=0),o=s.splice(0,l),o=[c,a].concat(o),c+=l,h-=a,u=u.concat(n.apply(e,o));return u},replace:function(e,t,r,n){return e.replace?e.replace(t,r,n):o._replace(e,t,r,n)},intersection:function(e,t){var r=[];return o.forEach(e,function(e){o.indexOf(t,e)>=0&&r.push(e)}),r}}}(),function(){var e,t=Ember.META_KEY,r=Ember.ENV.MANDATORY_SETTER,n=/^([A-Z$]|([0-9][A-Z$])).*[\.\*]/,i=/^this[\.\*]/,o=/^([^\.\*]+)/;e=function(e,n){if(""===n)return e;if(n||"string"!=typeof e||(n=e,e=null),null===e)return s(e,n);var i,o=e[t],a=o&&o.descs[n];return void 0===a&&-1!==n.indexOf(".")?s(e,n):a?a.get(e,n):(i=r&&o&&o.watching[n]>0?o.values[n]:e[n],void 0!==i||"object"!=typeof e||n in e||"function"!=typeof e.unknownProperty?i:e.unknownProperty(n))},Ember.config.overrideAccessors&&(Ember.get=e,Ember.config.overrideAccessors(),e=Ember.get);var a=Ember.normalizeTuple=function(t,r){var a,s=i.test(r),u=!s&&n.test(r);if((!t||u)&&(t=Ember.lookup),s&&(r=r.slice(5)),t===Ember.lookup&&(a=r.match(o)[0],t=e(t,a),r=r.slice(a.length+1)),!r||0===r.length)throw new Ember.Error("Path cannot be empty");return[t,r]},s=Ember._getPath=function(t,r){var n,o,s,u,l;if(null===t&&-1===r.indexOf("."))return e(Ember.lookup,r);for(n=i.test(r),(!t||n)&&(s=a(t,r),t=s[0],r=s[1],s.length=0),o=r.split("."),l=o.length,u=0;null!=t&&l>u;u++)if(t=e(t,o[u],!0),t&&t.isDestroyed)return void 0;return t};Ember.getWithDefault=function(t,r,n){var i=e(t,r);return void 0===i?n:i},Ember.get=e}(),function(){function e(e,t,r){for(var n=-1,i=e.length-3;i>=0;i-=3)if(t===e[i]&&r===e[i+1]){n=i;break}return n}function t(e,t){var r,n=p(e,!0);return n.listeners||(n.listeners={}),n.hasOwnProperty("listeners")||(n.listeners=m(n.listeners)),r=n.listeners[t],r&&!n.listeners.hasOwnProperty(t)?r=n.listeners[t]=n.listeners[t].slice():r||(r=n.listeners[t]=[]),r}function r(t,r,n){var i=t[f],o=i&&i.listeners&&i.listeners[r];if(o)for(var a=o.length-3;a>=0;a-=3){var s=o[a],u=o[a+1],l=o[a+2],c=e(n,s,u);-1===c&&n.push(s,u,l)}}function n(t,r,n){var i=t[f],o=i&&i.listeners&&i.listeners[r],a=[];if(o){for(var s=o.length-3;s>=0;s-=3){var u=o[s],l=o[s+1],c=o[s+2],h=e(n,u,l);-1===h&&(n.push(u,l,c),a.push(u,l,c))}return a}}function i(r,n,i,o,a){o||"function"!=typeof i||(o=i,i=null);var s=t(r,n),u=e(s,i,o),l=0;a&&(l|=b),-1===u&&(s.push(i,o,l),"function"==typeof r.didAddListener&&r.didAddListener(n,i,o))}function o(r,n,i,o){function a(i,o){var a=t(r,n),s=e(a,i,o);-1!==s&&(a.splice(s,3),"function"==typeof r.didRemoveListener&&r.didRemoveListener(n,i,o))}if(o||"function"!=typeof i||(o=i,i=null),o)a(i,o);else{var s=r[f],u=s&&s.listeners&&s.listeners[n];if(!u)return;for(var l=u.length-3;l>=0;l-=3)a(u[l],u[l+1])}}function a(r,n,i,o,a){function s(){return a.call(i)}function u(){-1!==c&&(l[c+2]&=~v)}o||"function"!=typeof i||(o=i,i=null);var l=t(r,n),c=e(l,i,o);return-1!==c&&(l[c+2]|=v),Ember.tryFinally(s,u)}function s(r,n,i,o,a){function s(){return a.call(i)}function u(){for(var e=0,t=p.length;t>e;e++){var r=p[e];f[e][r+2]&=~v}}o||"function"!=typeof i||(o=i,i=null);var l,c,h,m,p=[],f=[];for(h=0,m=n.length;m>h;h++){l=n[h],c=t(r,l);var d=e(c,i,o);-1!==d&&(c[d+2]|=v,p.push(d),f.push(c))}return Ember.tryFinally(s,u)}function u(e){var t=e[f].listeners,r=[];if(t)for(var n in t)t[n]&&r.push(n);return r}function l(e,t,r,n){if(e!==Ember&&"function"==typeof e.sendEvent&&e.sendEvent(t,r),!n){var i=e[f];n=i&&i.listeners&&i.listeners[t]}if(n){for(var a=n.length-3;a>=0;a-=3){var s=n[a],u=n[a+1],l=n[a+2];u&&(l&v||(l&b&&o(e,t,s,u),s||(s=e),"string"==typeof u&&(u=s[u]),r?u.apply(s,r):u.call(s)))}return!0}}function c(e,t){var r=e[f],n=r&&r.listeners&&r.listeners[t];return!(!n||!n.length)}function h(e,t){var r=[],n=e[f],i=n&&n.listeners&&n.listeners[t];if(!i)return r;for(var o=0,a=i.length;a>o;o+=3){var s=i[o],u=i[o+1];r.push([s,u])}return r}var m=Ember.create,p=Ember.meta,f=Ember.META_KEY,d=[].slice,b=1,v=2;Ember.on=function(){var e=d.call(arguments,-1)[0],t=d.call(arguments,0,-1);return e.__ember_listens__=t,e},Ember.addListener=i,Ember.removeListener=o,Ember._suspendListener=a,Ember._suspendListeners=s,Ember.sendEvent=l,Ember.hasListeners=c,Ember.watchedEvents=u,Ember.listenersFor=h,Ember.listenersDiff=n,Ember.listenersUnion=r}(),function(){var e=Ember.guidFor,t=Ember.sendEvent,r=Ember._ObserverSet=function(){this.clear()};r.prototype.add=function(t,r,n){var i,o=this.observerSet,a=this.observers,s=e(t),u=o[s];return u||(o[s]=u={}),i=u[r],void 0===i&&(i=a.push({sender:t,keyName:r,eventName:n,listeners:[]})-1,u[r]=i),a[i].listeners},r.prototype.flush=function(){var e,r,n,i,o=this.observers;for(this.clear(),e=0,r=o.length;r>e;++e)n=o[e],i=n.sender,i.isDestroying||i.isDestroyed||t(i,n.eventName,[i,n.keyName],n.listeners)},r.prototype.clear=function(){this.observerSet={},this.observers=[]}}(),function(){function e(e,t){var n=e[h],i=n&&n.watching[t]>0||"length"===t,a=n&&n.proto,s=n&&n.descs[t];i&&a!==e&&(s&&s.willChange&&s.willChange(e,t),r(e,t,n),o(e,t,n),l(e,t))}function t(e,t){var r=e[h],i=r&&r.watching[t]>0||"length"===t,o=r&&r.proto,s=r&&r.descs[t];o!==e&&(s&&s.didChange&&s.didChange(e,t),(i||"length"===t)&&(n(e,t,r),a(e,t,r,!1),c(e,t)))}function r(t,r,n){if(!t.isDestroying){var o=_,a=!o;a&&(o=_={}),i(e,t,r,o,n),a&&(_=null)}}function n(e,r,n){if(!e.isDestroying){var o=w,a=!o;a&&(o=w={}),i(t,e,r,o,n),a&&(w=null)}}function i(e,t,r,n,i){var o=m(t);if(n[o]||(n[o]={}),!n[o][r]){n[o][r]=!0;var a=i.deps;if(a=a&&a[r])for(var s in a){var u=i.descs[s];u&&u._suspended===t||e(t,s)}}}function o(t,r,n){if(n.hasOwnProperty("chainWatchers")&&n.chainWatchers[r]){var i,o,a=n.chainWatchers[r],s=[];for(i=0,o=a.length;o>i;i++)a[i].willChange(s);for(i=0,o=s.length;o>i;i+=2)e(s[i],s[i+1])}}function a(e,r,n,i){if(n&&n.hasOwnProperty("chainWatchers")&&n.chainWatchers[r]){var o,a,s=n.chainWatchers[r],u=i?null:[];for(o=0,a=s.length;a>o;o++)s[o].didChange(u);if(!i)for(o=0,a=u.length;a>o;o+=2)t(u[o],u[o+1])}}function s(){y++}function u(){y--,0>=y&&(E.clear(),g.flush())}function l(e,t){if(!e.isDestroying){var r,n,i=t+":before";y?(r=E.add(e,t,i),n=b(e,i,r),f(e,i,[e,t],n)):f(e,i,[e,t])}}function c(e,t){if(!e.isDestroying){var r,n=t+":change";y?(r=g.add(e,t,n),d(e,n,r)):f(e,n,[e,t])}}var h=Ember.META_KEY,m=Ember.guidFor,p=Ember.tryFinally,f=Ember.sendEvent,d=Ember.listenersUnion,b=Ember.listenersDiff,v=Ember._ObserverSet,E=new v,g=new v,y=0;Ember.propertyWillChange=e,Ember.propertyDidChange=t;var _,w;Ember.overrideChains=function(e,t,r){a(e,t,r,!0)},Ember.beginPropertyChanges=s,Ember.endPropertyChanges=u,Ember.changeProperties=function(e,t){s(),p(e,u,t)}}(),function(){function e(e,t,r,o){var a;if(a=t.slice(t.lastIndexOf(".")+1),t=t===a?a:t.slice(0,t.length-(a.length+1)),"this"!==t&&(e=n(e,t)),!a||0===a.length)throw new Ember.Error("Property set failed: You passed an empty path");if(!e){if(o)return;throw new Ember.Error('Property set failed: object in path "'+t+'" could not be found or was destroyed.')}return i(e,a,r)}var t=Ember.META_KEY,r=Ember.ENV.MANDATORY_SETTER,n=Ember._getPath,i=function(n,i,o,a){if("string"==typeof n&&(o=i,i=n,n=null),!n)return e(n,i,o,a);var s,u,l=n[t],c=l&&l.descs[i];if(void 0===c&&-1!==i.indexOf("."))return e(n,i,o,a);if(void 0!==c)c.set(n,i,o);else{if("object"==typeof n&&null!==n&&n[i]===o)return o;s="object"==typeof n&&!(i in n),s&&"function"==typeof n.setUnknownProperty?n.setUnknownProperty(i,o):l&&l.watching[i]>0?(u=r?l.values[i]:n[i],o!==u&&(Ember.propertyWillChange(n,i),r?(void 0!==u||i in n)&&n.propertyIsEnumerable(i)?l.values[i]=o:Ember.defineProperty(n,i,null,o):n[i]=o,Ember.propertyDidChange(n,i))):n[i]=o}return o};Ember.config.overrideAccessors&&(Ember.set=i,Ember.config.overrideAccessors(),i=Ember.set),Ember.set=i,Ember.trySet=function(e,t,r){return i(e,t,r,!0)}}(),function(){var e=Ember.set,t=Ember.guidFor,r=Ember.ArrayPolyfills.indexOf,n=function(e){var t={};for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t},i=function(e,t){var r=e.keys.copy(),i=n(e.values);return t.keys=r,t.values=i,t.length=e.length,t},o=Ember.OrderedSet=function(){this.clear()};o.create=function(){return new o},o.prototype={clear:function(){this.presenceSet={},this.list=[]},add:function(e){var r=t(e),n=this.presenceSet,i=this.list;r in n||(n[r]=!0,i.push(e))},remove:function(e){var n=t(e),i=this.presenceSet,o=this.list;delete i[n];var a=r.call(o,e);a>-1&&o.splice(a,1)},isEmpty:function(){return 0===this.list.length},has:function(e){var r=t(e),n=this.presenceSet;return r in n},forEach:function(e,t){for(var r=this.toArray(),n=0,i=r.length;i>n;n++)e.call(t,r[n])},toArray:function(){return this.list.slice()},copy:function(){var e=new o;return e.presenceSet=n(this.presenceSet),e.list=this.toArray(),e}};var a=Ember.Map=function(){this.keys=Ember.OrderedSet.create(),this.values={}};a.create=function(){return new a},a.prototype={length:0,get:function(e){var r=this.values,n=t(e);return r[n]},set:function(r,n){var i=this.keys,o=this.values,a=t(r);i.add(r),o[a]=n,e(this,"length",i.list.length)},remove:function(r){var n=this.keys,i=this.values,o=t(r);return i.hasOwnProperty(o)?(n.remove(r),delete i[o],e(this,"length",n.list.length),!0):!1},has:function(e){var r=this.values,n=t(e);return r.hasOwnProperty(n)},forEach:function(e,r){var n=this.keys,i=this.values;n.forEach(function(n){var o=t(n);e.call(r,n,i[o])})},copy:function(){return i(this,new a)}};var s=Ember.MapWithDefault=function(e){a.call(this),this.defaultValue=e.defaultValue};s.create=function(e){return e?new s(e):new a},s.prototype=Ember.create(a.prototype),s.prototype.get=function(e){var t=this.has(e);if(t)return a.prototype.get.call(this,e);var r=this.defaultValue(e);return this.set(e,r),r},s.prototype.copy=function(){return i(this,new s({defaultValue:this.defaultValue}))}}(),function(){function e(e){var t,r;Ember.imports.console?t=Ember.imports.console:"undefined"!=typeof console&&(t=console);var n="object"==typeof t?t[e]:null;return n?"function"==typeof n.apply?(r=function(){n.apply(t,arguments)},r.displayName="console."+e,r):function(){var e=Array.prototype.join.call(arguments,", ");n(e)}:void 0}function t(e,t){if(!e)try{throw new Ember.Error("assertion failed: "+t)}catch(r){setTimeout(function(){throw r},0)}}Ember.Logger={log:e("log")||Ember.K,warn:e("warn")||Ember.K,error:e("error")||Ember.K,info:e("info")||Ember.K,debug:e("debug")||e("info")||Ember.K,assert:e("assert")||t}}(),function(){var e=Ember.META_KEY,t=Ember.meta,r=Ember.platform.defineProperty,n=Ember.ENV.MANDATORY_SETTER;Ember.Descriptor=function(){};var i=Ember.MANDATORY_SETTER_FUNCTION=function(){},o=Ember.DEFAULT_GETTER_FUNCTION=function(t){return function(){var r=this[e];return r&&r.values[t]}};if(Ember.defineProperty=function(e,s,u,l,c){var h,m,p,f;return c||(c=t(e)),h=c.descs,m=c.descs[s],p=c.watching[s]>0,m instanceof Ember.Descriptor&&m.teardown(e,s),u instanceof Ember.Descriptor?(f=u,h[s]=u,n&&p?r(e,s,{configurable:!0,enumerable:!0,writable:!0,value:void 0}):e[s]=void 0,Ember.FEATURES.isEnabled("composable-computed-properties")&&u.func&&u._dependentCPs&&a(e,u._dependentCPs,c)):(h[s]=void 0,null==u?(f=l,n&&p?(c.values[s]=l,r(e,s,{configurable:!0,enumerable:!0,set:i,get:o(s)})):e[s]=l):(f=u,r(e,s,u))),p&&Ember.overrideChains(e,s,c),e.didDefineProperty&&e.didDefineProperty(e,s,f),this},Ember.FEATURES.isEnabled("composable-computed-properties"))var a=function(e,t,r){for(var n,i,o=t.length,s=0;o>s;++s)n=t[s],i=n.implicitCPKey,Ember.defineProperty(e,i,n,void 0,r),n._dependentCPs&&a(e,n._dependentCPs,r)}}(),function(){var e=Ember.get;Ember.getProperties=function(t){var r={},n=arguments,i=1;2===arguments.length&&"array"===Ember.typeOf(arguments[1])&&(i=0,n=arguments[1]);for(var o=n.length;o>i;i++)r[n[i]]=e(t,n[i]);return r}}(),function(){var e=Ember.changeProperties,t=Ember.set;Ember.setProperties=function(r,n){return e(function(){for(var e in n)n.hasOwnProperty(e)&&t(r,e,n[e])}),r}}(),function(){var e=Ember.meta,t=Ember.typeOf,r=Ember.ENV.MANDATORY_SETTER,n=Ember.platform.defineProperty;Ember.watchKey=function(i,o,a){if("length"!==o||"array"!==t(i)){var s=a||e(i),u=s.watching;u[o]?u[o]=(u[o]||0)+1:(u[o]=1,"function"==typeof i.willWatchProperty&&i.willWatchProperty(o),r&&o in i&&(s.values[o]=i[o],n(i,o,{configurable:!0,enumerable:i.propertyIsEnumerable(o),set:Ember.MANDATORY_SETTER_FUNCTION,get:Ember.DEFAULT_GETTER_FUNCTION(o)})))}},Ember.unwatchKey=function(t,i,o){var a=o||e(t),s=a.watching;1===s[i]?(s[i]=0,"function"==typeof t.didUnwatchProperty&&t.didUnwatchProperty(i),r&&i in t&&n(t,i,{configurable:!0,enumerable:t.propertyIsEnumerable(i),set:function(e){n(t,i,{configurable:!0,writable:!0,enumerable:!0,value:e}),delete a.values[i]},get:Ember.DEFAULT_GETTER_FUNCTION(i)})):s[i]>1&&s[i]--}}(),function(){function e(e){return e.match(c)[0]}function t(e,t,r){if(e&&"object"==typeof e){var i=n(e),o=i.chainWatchers;i.hasOwnProperty("chainWatchers")||(o=i.chainWatchers={}),o[t]||(o[t]=[]),o[t].push(r),u(e,t,i)}}function r(e,t){if(!e)return void 0;var r=e[h];if(r&&r.proto===e)return void 0;if("@each"===t)return i(e,t);var n=r&&r.descs[t];return n&&n._cacheable?t in r.cache?r.cache[t]:void 0:i(e,t)}var n=Ember.meta,i=Ember.get,o=Ember.normalizeTuple,a=Ember.ArrayPolyfills.forEach,s=Ember.warn,u=Ember.watchKey,l=Ember.unwatchKey,c=/^([^\.\*]+)/,h=Ember.META_KEY,m=[];Ember.flushPendingChains=function(){if(0!==m.length){var e=m;m=[],a.call(e,function(e){e[0].add(e[1])}),s("Watching an undefined global, Ember expects watched globals to be setup by the time the run loop is flushed, check for typos",0===m.length)}};var p=Ember.removeChainWatcher=function(e,t,r){if(e&&"object"==typeof e){var n=e[h];if(!n||n.hasOwnProperty("chainWatchers")){var i=n&&n.chainWatchers;if(i&&i[t]){i=i[t];for(var o=0,a=i.length;a>o;o++)i[o]===r&&i.splice(o,1)}l(e,t,n)}}},f=Ember._ChainNode=function(e,r,n){this._parent=e,this._key=r,this._watching=void 0===n,this._value=n,this._paths={},this._watching&&(this._object=e.value(),this._object&&t(this._object,this._key,this)),this._parent&&"@each"===this._parent._key&&this.value()},d=f.prototype;d.value=function(){if(void 0===this._value&&this._watching){var e=this._parent.value();this._value=r(e,this._key)}return this._value},d.destroy=function(){if(this._watching){var e=this._object;e&&p(e,this._key,this),this._watching=!1}},d.copy=function(e){var t,r=new f(null,null,e),n=this._paths;for(t in n)n[t]<=0||r.add(t);return r},d.add=function(t){var r,n,i,a,s;if(s=this._paths,s[t]=(s[t]||0)+1,r=this.value(),n=o(r,t),n[0]&&n[0]===r)t=n[1],i=e(t),t=t.slice(i.length+1);else{if(!n[0])return m.push([this,t]),n.length=0,void 0;a=n[0],i=t.slice(0,0-(n[1].length+1)),t=n[1]}n.length=0,this.chain(i,t,a)},d.remove=function(t){var r,n,i,a,s;s=this._paths,s[t]>0&&s[t]--,r=this.value(),n=o(r,t),n[0]===r?(t=n[1],i=e(t),t=t.slice(i.length+1)):(a=n[0],i=t.slice(0,0-(n[1].length+1)),t=n[1]),n.length=0,this.unchain(i,t)},d.count=0,d.chain=function(t,r,n){var i,o=this._chains;o||(o=this._chains={}),i=o[t],i||(i=o[t]=new f(this,t,n)),i.count++,r&&r.length>0&&(t=e(r),r=r.slice(t.length+1),i.chain(t,r))},d.unchain=function(t,r){var n=this._chains,i=n[t];r&&r.length>1&&(t=e(r),r=r.slice(t.length+1),i.unchain(t,r)),i.count--,i.count<=0&&(delete n[i._key],i.destroy())},d.willChange=function(e){var t=this._chains;if(t)for(var r in t)t.hasOwnProperty(r)&&t[r].willChange(e);this._parent&&this._parent.chainWillChange(this,this._key,1,e)},d.chainWillChange=function(e,t,r,n){this._key&&(t=this._key+"."+t),this._parent?this._parent.chainWillChange(this,t,r+1,n):(r>1&&n.push(this.value(),t),t="this."+t,this._paths[t]>0&&n.push(this.value(),t))},d.chainDidChange=function(e,t,r,n){this._key&&(t=this._key+"."+t),this._parent?this._parent.chainDidChange(this,t,r+1,n):(r>1&&n.push(this.value(),t),t="this."+t,this._paths[t]>0&&n.push(this.value(),t))},d.didChange=function(e){if(this._watching){var r=this._parent.value();r!==this._object&&(p(this._object,this._key,this),this._object=r,t(r,this._key,this)),this._value=void 0,this._parent&&"@each"===this._parent._key&&this.value()}var n=this._chains;if(n)for(var i in n)n.hasOwnProperty(i)&&n[i].didChange(e);null!==e&&this._parent&&this._parent.chainDidChange(this,this._key,1,e)},Ember.finishChains=function(e){var t=e[h],r=t&&t.chains;r&&(r.value()!==e?n(e).chains=r=r.copy(e):r.didChange(null))}}(),function(){var e=Ember.EnumerableUtils.forEach,t=/^((?:[^\.]*\.)*)\{(.*)\}$/;Ember.expandProperties=function(r,n){var i,o,a;(i=t.exec(r))?(o=i[1],a=i[2],e(a.split(","),function(e){n(o+e)})):n(r)}}(),function(){function e(e,r){var i=r||t(e),o=i.chains;return o?o.value()!==e&&(o=i.chains=o.copy(e)):o=i.chains=new n(null,null,e),o}var t=Ember.meta,r=Ember.typeOf,n=Ember._ChainNode;Ember.watchPath=function(n,i,o){if("length"!==i||"array"!==r(n)){var a=o||t(n),s=a.watching;s[i]?s[i]=(s[i]||0)+1:(s[i]=1,e(n,a).add(i))}},Ember.unwatchPath=function(r,n,i){var o=i||t(r),a=o.watching;1===a[n]?(a[n]=0,e(r,o).remove(n)):a[n]>1&&a[n]--}}(),function(){function e(e){return"*"===e||!c.test(e)}var t=(Ember.meta,Ember.GUID_KEY),r=Ember.META_KEY,n=Ember.removeChainWatcher,i=Ember.watchKey,o=Ember.unwatchKey,a=Ember.watchPath,s=Ember.unwatchPath,u=Ember.typeOf,l=Ember.generateGuid,c=/[\.\*]/;Ember.watch=function(t,r,n){("length"!==r||"array"!==u(t))&&(e(r)?i(t,r,n):a(t,r,n))},Ember.isWatching=function(e,t){var n=e[r];return(n&&n.watching[t])>0},Ember.watch.flushPending=Ember.flushPendingChains,Ember.unwatch=function(t,r,n){("length"!==r||"array"!==u(t))&&(e(r)?o(t,r,n):s(t,r,n))},Ember.rewatch=function(e){var n=e[r],i=n&&n.chains;t in e&&!e.hasOwnProperty(t)&&l(e),i&&i.value()!==e&&(n.chains=i.copy(e))};var h=[];Ember.destroy=function(e){var t,i,o,a,s=e[r];if(s&&(e[r]=null,t=s.chains))for(h.push(t);h.length>0;){if(t=h.pop(),i=t._chains)for(o in i)i.hasOwnProperty(o)&&h.push(i[o]);t._watching&&(a=t._object,a&&n(a,t._key,t))}}}(),function(){function e(){}function t(e,t){var r=e[t];return r?e.hasOwnProperty(t)||(r=e[t]=m(r)):r=e[t]={},r}function r(e){return t(e,"deps")}function n(e,n,i,o){var a,s,u,l,c,h=e._dependentKeys;if(h)for(a=r(o),s=0,u=h.length;u>s;s++)l=h[s],c=t(a,l),c[i]=(c[i]||0)+1,f(n,l,o)}function i(e,n,i,o){var a,s,u,l,c,h=e._dependentKeys;if(h)for(a=r(o),s=0,u=h.length;u>s;s++)l=h[s],c=t(a,l),c[i]=(c[i]||0)-1,d(n,l,o)}function o(e,t){this.func=e,Ember.FEATURES.isEnabled("composable-computed-properties")?x(this,t&&t.dependentKeys):this._dependentKeys=t&&t.dependentKeys,this._cacheable=t&&void 0!==t.cacheable?t.cacheable:!0,this._readOnly=t&&(void 0!==t.readOnly||!!t.readOnly)||!1}function a(e){for(var t=0,r=e.length;r>t;t++)e[t].didChange(null)}function s(e,t){for(var r={},n=0;nr;r++)b(arguments[r],t);return Ember.FEATURES.isEnabled("composable-computed-properties")?x(this,e):this._dependentKeys=e,this},E.meta=function(e){return 0===arguments.length?this._meta||{}:(this._meta=e,this)},E.didChange=function(e,t){if(this._cacheable&&this._suspended!==e){var r=c(e);void 0!==r.cache&&(r.cache[t]=void 0,i(this,e,t,r))}},E.get=function(t,r){var i,o,s,u;if(this._cacheable){s=c(t),o=s.cache;var l=o[r];if(l===e)return void 0;if(void 0!==l)return l;i=this.func.call(t,r),o[r]=void 0===i?e:i,u=s.chainWatchers&&s.chainWatchers[r],u&&a(u),n(this,t,r,s)}else i=this.func.call(t,r);return i},E.set=function(t,r,i){var o,a,s,u=this._cacheable,l=this.func,h=c(t,u),m=this._suspended,p=!1,f=h.cache;if(this._readOnly)throw new Ember.Error("Cannot Set: "+r+" on: "+Ember.inspect(t));this._suspended=t;try{if(u&&void 0!==f[r]&&(a=f[r],p=!0),o=l.wrappedFunction?l.wrappedFunction.length:l.__ember_arity__?l.__ember_arity__:l.__ember_arity__=l.length,3===o)s=l.call(t,r,i,a);else{if(2!==o)return Ember.defineProperty(t,r,null,a),Ember.set(t,r,i),void 0;s=l.call(t,r,i)}if(p&&a===s)return;var d=h.watching[r];d&&Ember.propertyWillChange(t,r),p&&(f[r]=void 0),u&&(p||n(this,t,r,h),f[r]=void 0===s?e:s),d&&Ember.propertyDidChange(t,r)}finally{this._suspended=m}return s},E.teardown=function(e,t){var r=c(e);return t in r.cache&&i(this,e,t,r),this._cacheable&&delete r.cache[t],null},Ember.computed=function(e){var t;if(arguments.length>1&&(t=h.call(arguments,0,-1),e=h.call(arguments,-1)[0]),"function"!=typeof e)throw new Ember.Error("Computed Property declared without a property function"); +var r=new o(e);return t&&r.property.apply(r,t),r},Ember.cacheFor=function(t,r){var n=t[p],i=n&&n.cache,o=i&&i[r];return o===e?void 0:o};var g,y;if(Ember.FEATURES.isEnabled("composable-computed-properties")){var _=Ember.guidFor,w=Ember.EnumerableUtils.map,C=Ember.EnumerableUtils.filter,O=(Ember.typeOf,function(e){return[_(e)].concat(e._dependentKeys).join("_").replace(/\./g,"_DOT_")}),P=function(e){return e instanceof Ember.ComputedProperty?O(e):e},A=function(e){return w(e,function(e){return P(e)})},T=function(e){return C(e,function(e){return e instanceof Ember.ComputedProperty})},x=function(e,t){t?(e._dependentKeys=A(t),e._dependentCPs=T(t)):e._dependentKeys=e._dependentCPs=[],e.implicitCPKey=O(e)};Ember.computed.normalizeDependentKey=P,Ember.computed.normalizeDependentKeys=A,g=function(e,t){Ember.computed[e]=function(e){var r=A(h.call(arguments));return Ember.computed(e,function(){return t.apply(this,r)})}}}Ember.FEATURES.isEnabled("composable-computed-properties")?y=function(e,t){Ember.computed[e]=function(){var e=h.call(arguments),r=A(e),n=Ember.computed(function(){return t.apply(this,[s(this,r)])});return n.property.apply(n,e)}}:(g=function(e,t){Ember.computed[e]=function(e){var r=h.call(arguments);return Ember.computed(e,function(){return t.apply(this,r)})}},y=function(e,t){Ember.computed[e]=function(){var e=h.call(arguments),r=Ember.computed(function(){return t.apply(this,[s(this,e)])});return r.property.apply(r,e)}}),Ember.FEATURES.isEnabled("composable-computed-properties")&&(Ember.computed.literal=function(e){return Ember.computed(function(){return e})}),Ember.FEATURES.isEnabled("ember-metal-computed-empty-array")?Ember.computed.empty=Ember.FEATURES.isEnabled("composable-computed-properties")?function(e){var t=h.call(arguments),r=P(e);return"string"!=typeof e||v.test(e)?t.push(r+".length"):t[0]=e+".length",Ember.computed.apply(Ember.computed,t.concat(function(){return Ember.isEmpty(u(this,r))}))}:function(e){return Ember.computed(e+".length",function(){return Ember.isEmpty(u(this,e))})}:g("empty",function(e){return Ember.isEmpty(u(this,e))}),g("notEmpty",function(e){return!Ember.isEmpty(u(this,e))}),g("none",function(e){return Ember.isNone(u(this,e))}),g("not",function(e){return!u(this,e)}),g("bool",function(e){return!!u(this,e)}),g("match",function(e,t){var r=u(this,e);return"string"==typeof r?t.test(r):!1}),g("equal",function(e,t){return u(this,e)===t}),g("gt",function(e,t){return u(this,e)>t}),g("gte",function(e,t){return u(this,e)>=t}),g("lt",function(e,t){return u(this,e)1?(l(this,e,r),r):u(this,e)})},Ember.computed.oneWay=function(e){return Ember.computed(e,function(){return u(this,e)})},Ember.FEATURES.isEnabled("query-params-new")&&(Ember.computed.reads=Ember.computed.oneWay),Ember.computed.readOnly=function(e){return Ember.computed(e,function(){return u(this,e)}).readOnly()},Ember.computed.defaultTo=function(e){return Ember.computed(function(t,r,n){return 1===arguments.length?null!=n?n:u(this,e):null!=r?r:u(this,e)})}}(),function(){function e(e){return e+r}function t(e){return e+n}var r=":change",n=":before";Ember.addObserver=function(t,r,n,i){return Ember.addListener(t,e(r),n,i),Ember.watch(t,r),this},Ember.observersFor=function(t,r){return Ember.listenersFor(t,e(r))},Ember.removeObserver=function(t,r,n,i){return Ember.unwatch(t,r),Ember.removeListener(t,e(r),n,i),this},Ember.addBeforeObserver=function(e,r,n,i){return Ember.addListener(e,t(r),n,i),Ember.watch(e,r),this},Ember._suspendBeforeObserver=function(e,r,n,i,o){return Ember._suspendListener(e,t(r),n,i,o)},Ember._suspendObserver=function(t,r,n,i,o){return Ember._suspendListener(t,e(r),n,i,o)};var i=Ember.ArrayPolyfills.map;Ember._suspendBeforeObservers=function(e,r,n,o,a){var s=i.call(r,t);return Ember._suspendListeners(e,s,n,o,a)},Ember._suspendObservers=function(t,r,n,o,a){var s=i.call(r,e);return Ember._suspendListeners(t,s,n,o,a)},Ember.beforeObserversFor=function(e,r){return Ember.listenersFor(e,t(r))},Ember.removeBeforeObserver=function(e,r,n,i){return Ember.unwatch(e,r),Ember.removeListener(e,t(r),n,i),this}}(),function(){e("backburner/queue",["exports"],function(e){"use strict";function t(e,t,r){this.daq=e,this.name=t,this.options=r,this._queue=[]}t.prototype={daq:null,name:null,options:null,_queue:null,push:function(e,t,r,n){var i=this._queue;return i.push(e,t,r,n),{queue:this,target:e,method:t}},pushUnique:function(e,t,r,n){var i,o,a,s,u=this._queue;for(a=0,s=u.length;s>a;a+=4)if(i=u[a],o=u[a+1],i===e&&o===t)return u[a+2]=r,u[a+3]=n,{queue:this,target:e,method:t};return this._queue.push(e,t,r,n),{queue:this,target:e,method:t}},flush:function(){var e,t,r,n,i,o=this._queue,a=this.options,s=a&&a.before,u=a&&a.after,l=o.length;for(l&&s&&s(),i=0;l>i;i+=4)e=o[i],t=o[i+1],r=o[i+2],n=o[i+3],r&&r.length>0?t.apply(e,r):t.call(e);l&&u&&u(),o.length>l?(this._queue=o.slice(l),this.flush()):this._queue.length=0},cancel:function(e){var t,r,n,i,o=this._queue;for(n=0,i=o.length;i>n;n+=4)if(t=o[n],r=o[n+1],t===e.target&&r===e.method)return o.splice(n,4),!0;if(o=this._queueBeingFlushed)for(n=0,i=o.length;i>n;n+=4)if(t=o[n],r=o[n+1],t===e.target&&r===e.method)return o[n+1]=null,!0}},e.Queue=t}),e("backburner/deferred_action_queues",["backburner/queue","exports"],function(e,t){"use strict";function r(e,t){var r=this.queues={};this.queueNames=e=e||[];for(var n,o=0,a=e.length;a>o;o++)n=e[o],r[n]=new i(this,n,t[n])}function n(e,t){for(var r,n,i=0,o=t;o>=i;i++)if(r=e.queueNames[i],n=e.queues[r],n._queue.length)return i;return-1}var i=e.Queue;r.prototype={queueNames:null,queues:null,schedule:function(e,t,r,n,i,o){var a=this.queues,s=a[e];if(!s)throw new Error("You attempted to schedule an action in a queue ("+e+") that doesn't exist");return i?s.pushUnique(t,r,n,o):s.push(t,r,n,o)},flush:function(){for(var e,t,r,i,o=this.queues,a=this.queueNames,s=0,u=a.length;u>s;){e=a[s],t=o[e],r=t._queueBeingFlushed=t._queue.slice(),t._queue=[];var l,c,h,m,p=t.options,f=p&&p.before,d=p&&p.after,b=0,v=r.length;for(v&&f&&f();v>b;)l=r[b],c=r[b+1],h=r[b+2],m=r[b+3],"string"==typeof c&&(c=l[c]),c&&(h&&h.length>0?c.apply(l,h):c.call(l)),b+=4;t._queueBeingFlushed=null,v&&d&&d(),-1===(i=n(this,s))?s++:s=i}}},t.DeferredActionQueues=r}),e("backburner",["backburner/deferred_action_queues","exports"],function(e,t){"use strict";function r(e){return"number"==typeof e||g.test(e)}function n(e,t){this.queueNames=e,this.options=t||{},this.options.defaultQueue||(this.options.defaultQueue=e[0]),this.instanceStack=[]}function i(e){e.begin(),l=E.setTimeout(function(){l=null,e.end()})}function o(e,t,r){(!c||h>t)&&(c&&clearTimeout(c),c=E.setTimeout(function(){c=null,h=null,a(e)},r),h=t)}function a(e){var t,r,n,i,a=+new Date;e.run(function(){for(n=0,i=v.length;i>n&&(t=v[n],!(t>a));n+=2);for(r=v.splice(0,n),n=1,i=r.length;i>n;n+=2)e.schedule(e.options.defaultQueue,null,r[n])}),v.length&&o(e,v[0],v[0]-a)}function s(e,t){for(var r,n=-1,i=0,o=b.length;o>i;i++)if(r=b[i],r[0]===e&&r[1]===t){n=i;break}return n}function u(e,t){for(var r,n=-1,i=0,o=d.length;o>i;i++)if(r=d[i],r[0]===e&&r[1]===t){n=i;break}return n}var l,c,h,m=e.DeferredActionQueues,p=[].slice,f=[].pop,d=[],b=[],v=[],E=this,g=/\d+/;n.prototype={queueNames:null,options:null,currentInstance:null,instanceStack:null,begin:function(){var e=this.options&&this.options.onBegin,t=this.currentInstance;t&&this.instanceStack.push(t),this.currentInstance=new m(this.queueNames,this.options),e&&e(this.currentInstance,t)},end:function(){var e=this.options&&this.options.onEnd,t=this.currentInstance,r=null;try{t.flush()}finally{this.currentInstance=null,this.instanceStack.length&&(r=this.instanceStack.pop(),this.currentInstance=r),e&&e(t,r)}},run:function(e,t){var r;this.begin(),t||(t=e,e=null),"string"==typeof t&&(t=e[t]);var n=!1;try{r=arguments.length>2?t.apply(e,p.call(arguments,2)):t.call(e)}finally{n||(n=!0,this.end())}return r},defer:function(e,t,r){r||(r=t,t=null),"string"==typeof r&&(r=t[r]);var n=this.DEBUG?new Error:void 0,o=arguments.length>3?p.call(arguments,3):void 0;return this.currentInstance||i(this),this.currentInstance.schedule(e,t,r,o,!1,n)},deferOnce:function(e,t,r){r||(r=t,t=null),"string"==typeof r&&(r=t[r]);var n=this.DEBUG?new Error:void 0,o=arguments.length>3?p.call(arguments,3):void 0;return this.currentInstance||i(this),this.currentInstance.schedule(e,t,r,o,!0,n)},setTimeout:function(){function e(){t.apply(i,l)}var t,n,i,a,s,u,l=p.call(arguments),c=l.length,h=this;if(0!==c){if(1===c)t=l.shift(),n=0;else if(2===c)a=l[0],s=l[1],"function"==typeof s||"function"==typeof a[s]?(i=l.shift(),t=l.shift(),n=0):r(s)?(t=l.shift(),n=l.shift()):(t=l.shift(),n=0);else{var m=l[l.length-1];r(m)&&(n=l.pop()),a=l[0],u=l[1],"function"==typeof u||"string"==typeof u&&null!==a&&u in a?(i=l.shift(),t=l.shift()):t=l.shift()}var f=+new Date+parseInt(n,10);"string"==typeof t&&(t=i[t]);var d,b;for(d=0,b=v.length;b>d&&!(f-1?d[i]:(o=E.setTimeout(function(){l||a.run.apply(a,s);var r=u(e,t);r>-1&&d.splice(r,1)},r),l&&a.run.apply(a,s),n=[e,t,o],d.push(n),n)},debounce:function(e,t){var r,n,i,o,a=this,u=arguments,l=f.call(u);return"number"==typeof l||"string"==typeof l?(r=l,l=!1):r=f.call(u),r=parseInt(r,10),n=s(e,t),n>-1&&(i=b[n],b.splice(n,1),clearTimeout(i[2])),o=E.setTimeout(function(){l||a.run.apply(a,u);var r=s(e,t);r>-1&&b.splice(r,1)},r),l&&-1===n&&a.run.apply(a,u),i=[e,t,o],b.push(i),i},cancelTimers:function(){var e,t;for(e=0,t=d.length;t>e;e++)clearTimeout(d[e][2]);for(d=[],e=0,t=b.length;t>e;e++)clearTimeout(b[e][2]);b=[],c&&(clearTimeout(c),c=null),v=[],l&&(clearTimeout(l),l=null)},hasTimers:function(){return!!v.length||l},cancel:function(e){var t=typeof e;if(e&&"object"===t&&e.queue&&e.method)return e.queue.cancel(e);if("function"!==t)return"[object Array]"===Object.prototype.toString.call(e)?this._cancelItem(u,d,e)||this._cancelItem(s,b,e):void 0;for(var r=0,n=v.length;n>r;r+=2)if(v[r+1]===e)return v.splice(r,2),!0},_cancelItem:function(e,t,r){var n,i;return r.length<3?!1:(i=e(r[0],r[1]),i>-1&&(n=t[i],n[2]===r[2])?(t.splice(i,1),clearTimeout(r[2]),!0):!1)}},n.prototype.schedule=n.prototype.defer,n.prototype.scheduleOnce=n.prototype.deferOnce,n.prototype.later=n.prototype.setTimeout,t.Backburner=n})}(),function(){function e(e){try{return a.run.apply(a,e)}catch(t){Ember.onerror(t)}}function r(){!Ember.run.currentRunLoop}{var n=function(e){Ember.run.currentRunLoop=e},i=function(e,t){Ember.run.currentRunLoop=t},o=t("backburner").Backburner,a=new o(["sync","actions","destroy"],{sync:{before:Ember.beginPropertyChanges,after:Ember.endPropertyChanges},defaultQueue:"actions",onBegin:n,onEnd:i}),s=[].slice;[].concat}Ember.run=function(){return Ember.onerror?e(arguments):a.run.apply(a,arguments)},Ember.run.join=function(){if(!Ember.run.currentRunLoop)return Ember.run.apply(Ember.run,arguments);var e=s.call(arguments);e.unshift("actions"),Ember.run.schedule.apply(Ember.run,e)},Ember.run.bind=function(){var e=arguments;return function(){return Ember.run.join.apply(Ember.run,e)}},Ember.run.backburner=a;Ember.run;Ember.run.currentRunLoop=null,Ember.run.queues=a.queueNames,Ember.run.begin=function(){a.begin()},Ember.run.end=function(){a.end()},Ember.run.schedule=function(){r(),a.schedule.apply(a,arguments)},Ember.run.hasScheduledTimers=function(){return a.hasTimers()},Ember.run.cancelTimers=function(){a.cancelTimers()},Ember.run.sync=function(){a.currentInstance&&a.currentInstance.queues.sync.flush()},Ember.run.later=function(){return a.later.apply(a,arguments)},Ember.run.once=function(){r();var e=s.call(arguments);return e.unshift("actions"),a.scheduleOnce.apply(a,e)},Ember.run.scheduleOnce=function(){return r(),a.scheduleOnce.apply(a,arguments)},Ember.run.next=function(){var e=s.call(arguments);return e.push(1),a.later.apply(a,e)},Ember.run.cancel=function(e){return a.cancel(e)},Ember.run.debounce=function(){return a.debounce.apply(a,arguments)},Ember.run.throttle=function(){return a.throttle.apply(a,arguments)}}(),function(){function e(e,t){return r(o(t)?Ember.lookup:e,t)}function t(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])}Ember.LOG_BINDINGS=!1||!!Ember.ENV.LOG_BINDINGS;var r=Ember.get,n=(Ember.set,Ember.guidFor),i=/^([A-Z$]|([0-9][A-Z$]))/,o=Ember.isGlobalPath=function(e){return i.test(e)},a=function(e,t){this._direction="fwd",this._from=t,this._to=e,this._directionMap=Ember.Map.create()};a.prototype={copy:function(){var e=new a(this._to,this._from);return this._oneWay&&(e._oneWay=!0),e},from:function(e){return this._from=e,this},to:function(e){return this._to=e,this},oneWay:function(){return this._oneWay=!0,this},toString:function(){var e=this._oneWay?"[oneWay]":"";return"Ember.Binding<"+n(this)+">("+this._from+" -> "+this._to+")"+e},connect:function(t){var r=this._from,n=this._to;return Ember.trySet(t,n,e(t,r)),Ember.addObserver(t,r,this,this.fromDidChange),this._oneWay||Ember.addObserver(t,n,this,this.toDidChange),this._readyToSync=!0,this},disconnect:function(e){var t=!this._oneWay;return Ember.removeObserver(e,this._from,this,this.fromDidChange),t&&Ember.removeObserver(e,this._to,this,this.toDidChange),this._readyToSync=!1,this},fromDidChange:function(e){this._scheduleSync(e,"fwd")},toDidChange:function(e){this._scheduleSync(e,"back")},_scheduleSync:function(e,t){var r=this._directionMap,n=r.get(e);n||(Ember.run.schedule("sync",this,this._sync,e),r.set(e,t)),"back"===n&&"fwd"===t&&r.set(e,"fwd")},_sync:function(t){var n=Ember.LOG_BINDINGS;if(!t.isDestroyed&&this._readyToSync){var i=this._directionMap,o=i.get(t),a=this._from,s=this._to;if(i.remove(t),"fwd"===o){var u=e(t,this._from);n&&Ember.Logger.log(" ",this.toString(),"->",u,t),this._oneWay?Ember.trySet(t,s,u):Ember._suspendObserver(t,s,this,this.toDidChange,function(){Ember.trySet(t,s,u)})}else if("back"===o){var l=r(t,this._to);n&&Ember.Logger.log(" ",this.toString(),"<-",l,t),Ember._suspendObserver(t,a,this,this.fromDidChange,function(){Ember.trySet(Ember.isGlobalPath(a)?Ember.lookup:t,a,l)})}}}},t(a,{from:function(){var e=this,t=new e;return t.from.apply(t,arguments)},to:function(){var e=this,t=new e;return t.to.apply(t,arguments)},oneWay:function(e,t){var r=this,n=new r(null,e);return n.oneWay(t)}}),Ember.Binding=a,Ember.bind=function(e,t,r){return new Ember.Binding(t,r).connect(e)},Ember.oneWay=function(e,t,r){return new Ember.Binding(t,r).oneWay().connect(e)}}(),function(){function e(){var e,t=this.__nextSuper;return t&&(this.__nextSuper=null,e=t.apply(this,arguments),this.__nextSuper=t),e}function t(e){var t=N(e,!0),r=t.mixins;return r?t.hasOwnProperty("mixins")||(r=t.mixins=x(r)):r=t.mixins={},r}function r(e,t){return t&&t.length>0&&(e.mixins=O.call(t,function(e){if(e instanceof _)return e;var t=new _;return t.properties=e,t})),e}function n(e){return"function"==typeof e&&e.isMethod!==!1&&e!==Boolean&&e!==Object&&e!==Number&&e!==Array&&e!==Date&&e!==String}function i(e,t){var r;return t instanceof _?(r=V(t),e[r]?D:(e[r]=t,t.properties)):t}function o(e,t,r,n){var i;return i=r[e]||n[e],t[e]&&(i=i?i.concat(t[e]):t[e]),i}function a(e,t,r,n,i){var o;return void 0===n[t]&&(o=i[t]),o=o||e.descs[t],o&&o instanceof Ember.ComputedProperty?(r=x(r),r.func=Ember.wrap(r.func,o.func),r):r}function s(e,t,r,n,i){var o;return void 0===i[t]&&(o=n[t]),o=o||e[t],"function"!=typeof o?r:Ember.wrap(r,o)}function u(e,t,r,n){var i=n[t]||e[t];return i?"function"==typeof i.concat?i.concat(r):Ember.makeArray(i).concat(r):Ember.makeArray(r)}function l(t,r,i,o){var a=o[r]||t[r];if(!a)return i;var u=Ember.merge({},a),l=!1;for(var c in i)if(i.hasOwnProperty(c)){var h=i[c];n(h)?(l=!0,u[c]=s(t,c,h,a,{})):u[c]=h}return l&&(u._super=e),u}function c(e,t,r,i,o,c,h,m){if(r instanceof Ember.Descriptor){if(r===w&&o[t])return D;r.func&&(r=a(i,t,r,c,o)),o[t]=r,c[t]=void 0}else h&&P.call(h,t)>=0||"concatenatedProperties"===t||"mergedProperties"===t?r=u(e,t,r,c):m&&P.call(m,t)>=0?r=l(e,t,r,c):n(r)&&(r=s(e,t,r,c,o)),o[t]=void 0,c[t]=r}function h(e,t,r,n,a,s){function u(e){delete r[e],delete n[e]}for(var l,m,p,f,d,b,v=0,E=e.length;E>v;v++)if(l=e[v],m=i(t,l),m!==D)if(m){b=N(a),a.willMergeMixin&&a.willMergeMixin(m),f=o("concatenatedProperties",m,n,a),d=o("mergedProperties",m,n,a);for(p in m)m.hasOwnProperty(p)&&(s.push(p),c(a,p,m[p],b,r,n,f,d));m.hasOwnProperty("toString")&&(a.toString=m.toString)}else l.mixins&&(h(l.mixins,t,r,n,a,s),l._without&&A.call(l._without,u))}function m(e,t,r,n){if(M.test(t)){var i=n.bindings;i?n.hasOwnProperty("bindings")||(i=n.bindings=x(n.bindings)):i=n.bindings={},i[t]=r}}function p(e,t){var r,n,i,o=t.bindings;if(o){for(r in o)n=o[r],n&&(i=r.slice(0,-7),n instanceof Ember.Binding?(n=n.copy(),n.to(i)):n=new Ember.Binding(i,n),n.connect(e),e[r]=n);t.bindings={}}}function f(e,t){return p(e,t||N(e)),e}function d(e,t,r,n,i){var o,a=t.methodName;return n[a]||i[a]?(o=i[a],t=n[a]):r.descs[a]?(t=r.descs[a],o=void 0):(t=void 0,o=e[a]),{desc:t,value:o}}function b(e,t,r,n,i){var o=r[n];if(o)for(var a=0,s=o.length;s>a;a++)Ember[i](e,o[a],null,t)}function v(e,t,r){var n=e[t];"function"==typeof n&&(b(e,t,n,"__ember_observesBefore__","removeBeforeObserver"),b(e,t,n,"__ember_observes__","removeObserver"),b(e,t,n,"__ember_listens__","removeListener")),"function"==typeof r&&(b(e,t,r,"__ember_observesBefore__","addBeforeObserver"),b(e,t,r,"__ember_observes__","addObserver"),b(e,t,r,"__ember_listens__","addListener"))}function E(r,n,i){var o,a,s,u={},l={},c=N(r),p=[];r._super=e,h(n,t(r),u,l,r,p);for(var b=0,E=p.length;E>b;b++)if(o=p[b],"constructor"!==o&&l.hasOwnProperty(o)&&(s=u[o],a=l[o],s!==w)){for(;s&&s instanceof C;){var g=d(r,s,c,u,l);s=g.desc,a=g.value}(void 0!==s||void 0!==a)&&(v(r,o,a),m(r,o,a,c),S(r,o,s,a,c))}return i||f(r,c),r}function g(e,t,r){var n=V(e);if(r[n])return!1;if(r[n]=!0,e===t)return!0;for(var i=e.mixins,o=i?i.length:0;--o>=0;)if(g(i[o],t,r))return!0;return!1}function y(e,t,r){if(!r[V(t)])if(r[V(t)]=!0,t.properties){var n=t.properties;for(var i in n)n.hasOwnProperty(i)&&(e[i]=!0)}else t.mixins&&A.call(t.mixins,function(t){y(e,t,r)})}var _,w,C,O=Ember.ArrayPolyfills.map,P=Ember.ArrayPolyfills.indexOf,A=Ember.ArrayPolyfills.forEach,T=[].slice,x=Ember.create,S=Ember.defineProperty,V=Ember.guidFor,N=Ember.meta,R=Ember.META_KEY,I=Ember.expandProperties,D={},M=Ember.IS_BINDING=/^.+Binding$/;Ember.mixin=function(e){var t=T.call(arguments,1);return E(e,t,!1),e},Ember.Mixin=function(){return r(this,arguments)},_=Ember.Mixin,_.prototype={properties:null,mixins:null,ownerConstructor:null},_._apply=E,_.applyPartial=function(e){var t=T.call(arguments,1);return E(e,t,!0)},_.finishPartial=f,Ember.anyUnprocessedMixins=!1,_.create=function(){Ember.anyUnprocessedMixins=!0;var e=this;return r(new e,arguments)};var k=_.prototype;k.reopen=function(){var e,t;this.properties?(e=_.create(),e.properties=this.properties,delete this.properties,this.mixins=[e]):this.mixins||(this.mixins=[]);var r,n=arguments.length,i=this.mixins;for(r=0;n>r;r++)e=arguments[r],e instanceof _?i.push(e):(t=_.create(),t.properties=e,i.push(t));return this},k.apply=function(e){return E(e,[this],!1)},k.applyPartial=function(e){return E(e,[this],!0)},k.detect=function(e){if(!e)return!1;if(e instanceof _)return g(e,this,{});var t=e[R],r=t&&t.mixins;return r?!!r[V(this)]:!1},k.without=function(){var e=new _(this);return e._without=T.call(arguments),e},k.keys=function(){var e={},t={},r=[];y(e,this,t);for(var n in e)e.hasOwnProperty(n)&&r.push(n);return r},_.mixins=function(e){var t=e[R],r=t&&t.mixins,n=[];if(!r)return n;for(var i in r){var o=r[i];o.properties||n.push(o)}return n},w=new Ember.Descriptor,w.toString=function(){return"(Required Property)"},Ember.required=function(){return w},C=function(e){this.methodName=e},C.prototype=new Ember.Descriptor,Ember.aliasMethod=function(e){return new C(e)},Ember.observer=function(){var e,t=T.call(arguments,-1)[0],r=function(t){e.push(t)},n=T.call(arguments,0,-1);"function"!=typeof t&&(t=arguments[0],n=T.call(arguments,1)),e=[];for(var i=0;ie;e++){arguments[e]}return Ember.observer.apply(this,arguments)},Ember.beforeObserver=function(){var e,t=T.call(arguments,-1)[0],r=function(t){e.push(t)},n=T.call(arguments,0,-1);"function"!=typeof t&&(t=arguments[0],n=T.call(arguments,1)),e=[];for(var i=0;ir;r++)if(e[r]===t)return r;return-1},r=function(e){var t=e._promiseCallbacks;return t||(t=e._promiseCallbacks={}),t};e["default"]={mixin:function(e){return e.on=this.on,e.off=this.off,e.trigger=this.trigger,e._promiseCallbacks=void 0,e},on:function(e,n){var i,o=r(this);i=o[e],i||(i=o[e]=[]),-1===t(i,n)&&i.push(n)},off:function(e,n){var i,o,a=r(this);return n?(i=a[e],o=t(i,n),-1!==o&&i.splice(o,1),void 0):(a[e]=[],void 0)},trigger:function(e,t){var n,i,o=r(this);if(n=o[e])for(var a=0;at;t++)e[t]&&i.push(n[t]);return i})})}var o=e["default"],a=t["default"],s=r.isFunction,u=r.isArray;n["default"]=i}),e("rsvp/hash",["./promise","./utils","exports"],function(e,t,r){"use strict";var n=e["default"],i=t.isNonThenable,o=t.keysOf;r["default"]=function(e){return new n(function(t,r){function a(e){return function(r){c[e]=r,0===--m&&t(c)}}function s(e){m=0,r(e)}var u,l,c={},h=o(e),m=h.length;if(0===m)return t(c),void 0;for(var p=0;ps;s++)l.push(t(n[s]));return i(l,r)})}}),e("rsvp/node",["./promise","exports"],function(e,t){"use strict";function r(e,t){return function(r,n){r?t(r):arguments.length>2?e(i.call(arguments,1)):e(n)}}var n=e["default"],i=Array.prototype.slice;t["default"]=function(e,t){return function(){var o=i.call(arguments),a=this||t;return new n(function(t,i){n.all(o).then(function(n){try{n.push(r(t,i)),e.apply(a,n)}catch(o){i(o)}})})}}}),e("rsvp/promise",["./config","./events","./instrument","./utils","./promise/cast","./promise/all","./promise/race","./promise/resolve","./promise/reject","exports"],function(e,t,r,n,i,o,a,s,u,l){"use strict";function c(){}function h(e,t){if(!P(e))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof h))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._id=I++,this._label=t,this._subscribers=[],w.instrument&&C("created",this),c!==e&&m(e,this)}function m(e,t){function r(e){v(t,e)}function n(e){g(t,e)}try{e(r,n)}catch(i){n(i)}}function p(e,t,r,n){var i=e._subscribers,o=i.length;i[o]=t,i[o+k]=r,i[o+j]=n}function f(e,t){var r,n,i=e._subscribers,o=e._detail;w.instrument&&C(t===k?"fulfilled":"rejected",e);for(var a=0;aa;a++){if(n=t[a],o=i(e,n.fullName),void 0===o)throw new Error("Attempting to inject an unknown injection: `"+n.fullName+"`");r[n.property]=o}return r}function u(e,t,r){var n=e._options.get(t);if(n&&void 0!==n[r])return n[r];var i=t.split(":")[0]; +return n=e._typeOptions.get(i),n?n[r]:void 0}function l(e,t){var r,n=t,i=e.resolve(n),o=e.factoryCache,a=t.split(":")[0];if(void 0!==i){if(o.has(t))return o.get(t);if(!i||"function"!=typeof i.extend||!Ember.MODEL_FACTORY_INJECTIONS&&"model"===a)return i;var s=c(e,t),u=h(e,t);return u._toString=e.makeToString(i,t),r=i.extend(s),r.reopenClass(u),o.set(t,r),r}}function c(e,t){var r=t.split(":"),n=r[0],i=[];return i=i.concat(e.typeInjections.get(n)||[]),i=i.concat(e.injections[t]||[]),i=s(e,i),i._debugContainerKey=t,i.container=e,i}function h(e,t){var r=t.split(":"),n=r[0],i=[];return i=i.concat(e.factoryTypeInjections.get(n)||[]),i=i.concat(e.factoryInjections[t]||[]),i=s(e,i),i._debugContainerKey=t,i}function m(e,t){var r=l(e,t);return u(e,t,"instantiate")===!1?r:r?"function"==typeof r.extend?r.create():r.create(c(e,t)):void 0}function p(e,t){e.cache.eachLocal(function(r,n){u(e,r,"instantiate")!==!1&&t(n)})}function f(e){e.cache.eachLocal(function(t,r){u(e,t,"instantiate")!==!1&&r.destroy()}),e.cache.dict={}}function d(e,t,r,n){var i=e.get(t);i||(i=[],e.set(t,i)),i.push({property:r,fullName:n})}function b(e){if(!g.test(e))throw new TypeError("Invalid Fullname, expected: `type:name` got: "+e)}function v(e,t,r,n){var i=e[t]=e[t]||[];i.push({property:r,fullName:n})}var E=e["default"];r.prototype={parent:null,children:null,resolver:null,registry:null,cache:null,typeInjections:null,injections:null,_options:null,_typeOptions:null,child:function(){var e=new r(this);return this.children.push(e),e},set:function(e,t,r){e[t]=r},register:function(e,t,r){if(b(e),void 0===t)throw new TypeError("Attempting to register an unknown factory: `"+e+"`");var n=this.normalize(e);if(this.cache.has(n))throw new Error("Cannot re-register: `"+e+"`, as it has already been looked up.");this.registry.set(n,t),this._options.set(n,r||{})},unregister:function(e){b(e);var t=this.normalize(e);this.registry.remove(t),this.cache.remove(t),this.factoryCache.remove(t),this.resolveCache.remove(t),this._options.remove(t)},resolve:function(e){b(e);var t=this.normalize(e),r=this.resolveCache.get(t);if(r)return r;var n=this.resolver(t)||this.registry.get(t);return this.resolveCache.set(t,n),n},describe:function(e){return e},normalize:function(e){return e},makeToString:function(e){return e.toString()},lookup:function(e,t){return b(e),i(this,this.normalize(e),t)},lookupFactory:function(e){return b(e),l(this,this.normalize(e))},has:function(e){return b(e),n(this,this.normalize(e))},optionsForType:function(e,t){this.parent&&o("optionsForType"),this._typeOptions.set(e,t)},options:function(e,t){this.optionsForType(e,t)},typeInjection:function(e,t,r){b(r),this.parent&&o("typeInjection"),d(this.typeInjections,e,t,r)},injection:function(e,t,r){this.parent&&o("injection"),b(r);var n=this.normalize(r);if(-1===e.indexOf(":"))return this.typeInjection(e,t,n);b(e);var i=this.normalize(e);v(this.injections,i,t,n)},factoryTypeInjection:function(e,t,r){this.parent&&o("factoryTypeInjection"),d(this.factoryTypeInjections,e,t,this.normalize(r))},factoryInjection:function(e,t,r){this.parent&&o("injection");var n=this.normalize(e),i=this.normalize(r);return b(r),-1===e.indexOf(":")?this.factoryTypeInjection(n,t,i):(b(e),v(this.factoryInjections,n,t,i),void 0)},destroy:function(){for(var e=0,t=this.children.length;t>e;e++)this.children[e].destroy();this.children=[],p(this,function(e){e.destroy()}),this.parent=void 0,this.isDestroyed=!0},reset:function(){for(var e=0,t=this.children.length;t>e;e++)f(this.children[e]);f(this)}};var g=/^[^:]+.+:[^:]+$/;t["default"]=r}),e("container/inheriting_dict",["exports"],function(e){"use strict";function t(e){this.parent=e,this.dict={}}t.prototype={parent:null,dict:null,get:function(e){var t=this.dict;return t.hasOwnProperty(e)?t[e]:this.parent?this.parent.get(e):void 0},set:function(e,t){this.dict[e]=t},remove:function(e){delete this.dict[e]},has:function(e){var t=this.dict;return t.hasOwnProperty(e)?!0:this.parent?this.parent.has(e):!1},eachLocal:function(e,t){var r=this.dict;for(var n in r)r.hasOwnProperty(n)&&e.call(t,n,r[n])}},e["default"]=t}),e("container",["container/container","exports"],function(e,t){"use strict";Ember.MODEL_FACTORY_INJECTIONS=!1||!!Ember.ENV.MODEL_FACTORY_INJECTIONS;var r=e["default"];t["default"]=r})}(),function(){function e(r,n,i,o){var a,s,u;if("object"!=typeof r||null===r)return r;if(n&&(s=t(i,r))>=0)return o[s];if("array"===Ember.typeOf(r)){if(a=r.slice(),n)for(s=a.length;--s>=0;)a[s]=e(a[s],n,i,o)}else if(Ember.Copyable&&Ember.Copyable.detect(r))a=r.copy(n,i,o);else{a={};for(u in r)r.hasOwnProperty(u)&&"__"!==u.substring(0,2)&&(a[u]=n?e(r[u],n,i,o):r[u])}return n&&(i.push(r),o.push(a)),a}var t=Ember.EnumerableUtils.indexOf;if(Ember.compare=function i(e,t){if(e===t)return 0;var r=Ember.typeOf(e),n=Ember.typeOf(t),o=Ember.Comparable;if(o){if("instance"===r&&o.detect(e.constructor))return e.constructor.compare(e,t);if("instance"===n&&o.detect(t.constructor))return 1-t.constructor.compare(t,e)}var a=Ember.ORDER_DEFINITION_MAPPING;if(!a){var s=Ember.ORDER_DEFINITION;a=Ember.ORDER_DEFINITION_MAPPING={};var u,l;for(u=0,l=s.length;l>u;++u)a[s[u]]=u;delete Ember.ORDER_DEFINITION}var c=a[r],h=a[n];if(h>c)return-1;if(c>h)return 1;switch(r){case"boolean":case"number":return t>e?-1:e>t?1:0;case"string":var m=e.localeCompare(t);return 0>m?-1:m>0?1:0;case"array":for(var p=e.length,f=t.length,d=Math.min(p,f),b=0,v=0;0===b&&d>v;)b=i(e[v],t[v]),v++;return 0!==b?b:f>p?-1:p>f?1:0;case"instance":return Ember.Comparable&&Ember.Comparable.detect(e)?e.compare(e,t):0;case"date":var E=e.getTime(),g=t.getTime();return g>E?-1:E>g?1:0;default:return 0}},Ember.copy=function(t,r){return"object"!=typeof t||null===t?t:Ember.Copyable&&Ember.Copyable.detect(t)?t.copy(r):e(t,r,r?[]:null,r?[]:null)},Ember.isEqual=function(e,t){return e&&"function"==typeof e.isEqual?e.isEqual(t):e===t},Ember.ORDER_DEFINITION=Ember.ENV.ORDER_DEFINITION||["undefined","null","boolean","number","string","array","object","instance","function","class","date"],Ember.keys=Object.keys,!Ember.keys||Ember.create.isSimulated){var r=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","valueOf","toLocaleString","toString"],n=function(e,r,n){"__"!==n.substring(0,2)&&"_super"!==n&&(t(r,n)>=0||e.hasOwnProperty(n)&&r.push(n))};Ember.keys=function(e){var t,i=[];for(t in e)n(e,i,t);for(var o=0,a=r.length;a>o;o++)t=r[o],n(e,i,t);return i}}}(),function(){var e=/[ _]/g,t={},r=/([a-z\d])([A-Z])/g,n=/(\-|_|\.|\s)+(.)?/g,i=/([a-z\d])([A-Z]+)/g,o=/\-|\s+/g,a=/[_|\/|\s]+/g,s=/[^a-z0-9\-]+/gi,u=/[\-]+/g,l=/^-+|-+$/g;Ember.STRINGS={},Ember.String={fmt:function(e,t){var r=0;return e.replace(/%@([0-9]+)?/g,function(e,n){return n=n?parseInt(n,10)-1:r++,e=t[n],null===e?"(null)":void 0===e?"":Ember.inspect(e)})},loc:function(e,t){return e=Ember.STRINGS[e]||e,Ember.String.fmt(e,t)},w:function(e){return e.split(/\s+/)},decamelize:function(e){return e.replace(r,"$1_$2").toLowerCase()},dasherize:function(r){var n,i=t,o=i.hasOwnProperty(r);return o?i[r]:(n=Ember.String.decamelize(r).replace(e,"-"),i[r]=n,n)},camelize:function(e){return e.replace(n,function(e,t,r){return r?r.toUpperCase():""}).replace(/^([A-Z])/,function(e){return e.toLowerCase()})},classify:function(e){for(var t=e.split("."),r=[],n=0,i=t.length;i>n;n++){var o=Ember.String.camelize(t[n]);r.push(o.charAt(0).toUpperCase()+o.substr(1))}return r.join(".")},underscore:function(e){return e.replace(i,"$1_$2").replace(o,"_").toLowerCase()},capitalize:function(e){return e.charAt(0).toUpperCase()+e.substr(1)}},Ember.FEATURES.isEnabled("string-parameterize")&&(Ember.String.parameterize=function(e){return e.replace(a,"-").replace(s,"").replace(u,"-").replace(l,"").toLowerCase()})}(),function(){var e=Ember.String.fmt,t=Ember.String.w,r=Ember.String.loc,n=Ember.String.camelize,i=Ember.String.decamelize,o=Ember.String.dasherize,a=Ember.String.underscore,s=Ember.String.capitalize,u=Ember.String.classify;if(Ember.FEATURES.isEnabled("string-parameterize"))var l=Ember.String.parameterize;(Ember.EXTEND_PROTOTYPES===!0||Ember.EXTEND_PROTOTYPES.String)&&(String.prototype.fmt=function(){return e(this,arguments)},String.prototype.w=function(){return t(this)},String.prototype.loc=function(){return r(this,arguments)},String.prototype.camelize=function(){return n(this)},String.prototype.decamelize=function(){return i(this)},String.prototype.dasherize=function(){return o(this)},String.prototype.underscore=function(){return a(this)},String.prototype.classify=function(){return u(this)},String.prototype.capitalize=function(){return s(this)},Ember.FEATURES.isEnabled("string-parameterize")&&(String.prototype.parameterize=function(){return l(this)}))}(),function(){var e=Ember.get,t=Ember.set,r=Array.prototype.slice,n=Ember.getProperties;Ember.Observable=Ember.Mixin.create({get:function(t){return e(this,t)},getProperties:function(){return n.apply(null,[this].concat(r.call(arguments)))},set:function(e,r){return t(this,e,r),this},setProperties:function(e){return Ember.setProperties(this,e)},beginPropertyChanges:function(){return Ember.beginPropertyChanges(),this},endPropertyChanges:function(){return Ember.endPropertyChanges(),this},propertyWillChange:function(e){return Ember.propertyWillChange(this,e),this},propertyDidChange:function(e){return Ember.propertyDidChange(this,e),this},notifyPropertyChange:function(e){return this.propertyWillChange(e),this.propertyDidChange(e),this},addBeforeObserver:function(e,t,r){Ember.addBeforeObserver(this,e,t,r)},addObserver:function(e,t,r){Ember.addObserver(this,e,t,r)},removeObserver:function(e,t,r){Ember.removeObserver(this,e,t,r)},hasObserverFor:function(e){return Ember.hasListeners(this,e+":change")},getWithDefault:function(e,t){return Ember.getWithDefault(this,e,t)},incrementProperty:function(r,n){return Ember.isNone(n)&&(n=1),t(this,r,(e(this,r)||0)+n),e(this,r)},decrementProperty:function(r,n){return Ember.isNone(n)&&(n=1),t(this,r,(e(this,r)||0)-n),e(this,r)},toggleProperty:function(r){return t(this,r,!e(this,r)),e(this,r)},cacheFor:function(e){return Ember.cacheFor(this,e)},observersForKey:function(e){return Ember.observersFor(this,e)}})}(),function(){function e(){var e,t,o=!1,a=function(){o||a.proto(),n(this,i,_),n(this,"__nextSuper",y);var u=s(this),l=u.proto;if(u.proto=this,e){var m=e;e=null,this.reopen.apply(this,m)}if(t){var p=t;t=null;for(var f=this.concatenatedProperties,d=0,v=p.length;v>d;d++){var w=p[d];if("object"!=typeof w&&void 0!==w)throw new Ember.Error("Ember.Object.create only accepts objects.");if(w)for(var C=Ember.keys(w),O=0,P=C.length;P>O;O++){var A=C[O];if(w.hasOwnProperty(A)){var T=w[A],x=Ember.IS_BINDING;if(x.test(A)){var S=u.bindings;S?u.hasOwnProperty("bindings")||(S=u.bindings=r(u.bindings)):S=u.bindings={},S[A]=T}var V=u.descs[A];if(f&&g(f,A)>=0){var N=this[A];T=N?"function"==typeof N.concat?N.concat(T):Ember.makeArray(N).concat(T):Ember.makeArray(T)}V?V.set(this,A,T):"function"!=typeof this.setUnknownProperty||A in this?E?Ember.defineProperty(this,A,null,T):this[A]=T:this.setUnknownProperty(A,T)}}}}b(this,u),this.init.apply(this,arguments),u.proto=l,c(this),h(this,"init")};return a.toString=f.prototype.toString,a.willReopen=function(){o&&(a.PrototypeMixin=f.create(a.PrototypeMixin)),o=!1},a._initMixins=function(t){e=t},a._initProperties=function(e){t=e},a.proto=function(){var e=a.superclass;return e&&e.proto(),o||(o=!0,a.PrototypeMixin.applyPartial(a.prototype),l(a.prototype)),this.prototype},a}function t(e){return function(){return e}}var r=(Ember.set,Ember.get,Ember.create),n=Ember.platform.defineProperty,i=Ember.GUID_KEY,o=Ember.guidFor,a=Ember.generateGuid,s=Ember.meta,u=Ember.META_KEY,l=Ember.rewatch,c=Ember.finishChains,h=Ember.sendEvent,m=Ember.destroy,p=Ember.run.schedule,f=Ember.Mixin,d=f._apply,b=f.finishPartial,v=f.prototype.reopen,E=Ember.ENV.MANDATORY_SETTER,g=Ember.EnumerableUtils.indexOf,y={configurable:!0,writable:!0,enumerable:!1,value:void 0},_={configurable:!0,writable:!0,enumerable:!1,value:null},w=e();w.toString=function(){return"Ember.CoreObject"},w.PrototypeMixin=f.create({reopen:function(){return d(this,arguments,!0),this},init:function(){},concatenatedProperties:null,isDestroyed:!1,isDestroying:!1,destroy:function(){return this.isDestroying?void 0:(this.isDestroying=!0,p("actions",this,this.willDestroy),p("destroy",this,this._scheduledDestroy),this)},willDestroy:Ember.K,_scheduledDestroy:function(){this.isDestroyed||(m(this),this.isDestroyed=!0)},bind:function(e,t){return t instanceof Ember.Binding||(t=Ember.Binding.from(t)),t.to(e).connect(this),t},toString:function(){var e="function"==typeof this.toStringExtension,r=e?":"+this.toStringExtension():"",n="<"+this.constructor.toString()+":"+o(this)+r+">";return this.toString=t(n),n}}),w.PrototypeMixin.ownerConstructor=w,Ember.config.overridePrototypeMixin&&Ember.config.overridePrototypeMixin(w.PrototypeMixin),w.__super__=null;var C=f.create({ClassMixin:Ember.required(),PrototypeMixin:Ember.required(),isClass:!0,isMethod:!1,extend:function(){var t,n=e();return n.ClassMixin=f.create(this.ClassMixin),n.PrototypeMixin=f.create(this.PrototypeMixin),n.ClassMixin.ownerConstructor=n,n.PrototypeMixin.ownerConstructor=n,v.apply(n.PrototypeMixin,arguments),n.superclass=this,n.__super__=this.prototype,t=n.prototype=r(this.prototype),t.constructor=n,a(t),s(t).proto=t,n.ClassMixin.apply(n),n},createWithMixins:function(){var e=this;return arguments.length>0&&this._initMixins(arguments),new e},create:function(){var e=this;return arguments.length>0&&this._initProperties(arguments),new e},reopen:function(){return this.willReopen(),v.apply(this.PrototypeMixin,arguments),this},reopenClass:function(){return v.apply(this.ClassMixin,arguments),d(this,arguments,!1),this},detect:function(e){if("function"!=typeof e)return!1;for(;e;){if(e===this)return!0;e=e.superclass}return!1},detectInstance:function(e){return e instanceof this},metaForProperty:function(e){var t=this.proto()[u],r=t&&t.descs[e];return r._meta||{}},eachComputedProperty:function(e,t){var r,n=this.proto(),i=s(n).descs,o={};for(var a in i)r=i[a],r instanceof Ember.ComputedProperty&&e.call(t||this,a,r._meta||o)}});C.ownerConstructor=w,Ember.config.overrideClassMixin&&Ember.config.overrideClassMixin(C),w.ClassMixin=C,C.apply(w),Ember.CoreObject=w}(),function(){Ember.Object=Ember.CoreObject.extend(Ember.Observable),Ember.Object.toString=function(){return"Ember.Object"}}(),function(){function e(t,r,i){var a=t.length;l[t.join(".")]=r;for(var s in r)if(c.call(r,s)){var u=r[s];if(t[a]=s,u&&u.toString===n)u.toString=o(t.join(".")),u[m]=t.join(".");else if(u&&u.isNamespace){if(i[h(u)])continue;i[h(u)]=!0,e(t,u,i)}}t.length=a}function t(){var e,t,r=Ember.Namespace,n=Ember.lookup;if(!r.PROCESSED)for(var i in n)if("parent"!==i&&"top"!==i&&"frameElement"!==i&&"webkitStorageInfo"!==i&&!("globalStorage"===i&&n.StorageList&&n.globalStorage instanceof n.StorageList||n.hasOwnProperty&&!n.hasOwnProperty(i))){try{e=Ember.lookup[i],t=e&&e.isNamespace}catch(o){continue}t&&(e[m]=i)}}function r(e){var t=e.superclass;return t?t[m]?t[m]:r(t):void 0}function n(){Ember.BOOTED||this[m]||i();var e;if(this[m])e=this[m];else if(this._toString)e=this._toString;else{var t=r(this);e=t?"(subclass of "+t+")":"(unknown mixin)",this.toString=o(e)}return e}function i(){var r=!u.PROCESSED,n=Ember.anyUnprocessedMixins;if(r&&(t(),u.PROCESSED=!0),r||n){for(var i,o=u.NAMESPACES,a=0,s=o.length;s>a;a++)i=o[a],e([i.toString()],i,{});Ember.anyUnprocessedMixins=!1}}function o(e){return function(){return e}}var a=Ember.get,s=Ember.ArrayPolyfills.indexOf,u=Ember.Namespace=Ember.Object.extend({isNamespace:!0,init:function(){Ember.Namespace.NAMESPACES.push(this),Ember.Namespace.PROCESSED=!1},toString:function(){var e=a(this,"name");return e?e:(t(),this[Ember.GUID_KEY+"_name"])},nameClasses:function(){e([this.toString()],this,{})},destroy:function(){var e=Ember.Namespace.NAMESPACES;Ember.lookup[this.toString()]=void 0,e.splice(s.call(e,this),1),this._super()}});u.reopenClass({NAMESPACES:[Ember],NAMESPACES_BY_ID:{},PROCESSED:!1,processAll:i,byName:function(e){return Ember.BOOTED||i(),l[e]}});var l=u.NAMESPACES_BY_ID,c={}.hasOwnProperty,h=Ember.guidFor,m=Ember.NAME_KEY=Ember.GUID_KEY+"_name";Ember.Mixin.prototype.toString=n}(),function(){function e(e,t){var r=t.slice(8);r in this||u(this,r)}function t(e,t){var r=t.slice(8);r in this||l(this,r)}var r=Ember.get,n=Ember.set,i=(Ember.String.fmt,Ember.addBeforeObserver),o=Ember.addObserver,a=Ember.removeBeforeObserver,s=Ember.removeObserver,u=Ember.propertyWillChange,l=Ember.propertyDidChange,c=Ember.meta,h=Ember.defineProperty;Ember.ObjectProxy=Ember.Object.extend({content:null,_contentDidChange:Ember.observer("content",function(){}),isTruthy:Ember.computed.bool("content"),_debugContainerKey:null,willWatchProperty:function(r){var n="content."+r;i(this,n,null,e),o(this,n,null,t)},didUnwatchProperty:function(r){var n="content."+r;a(this,n,null,e),s(this,n,null,t)},unknownProperty:function(e){var t=r(this,"content");return t?r(t,e):void 0},setUnknownProperty:function(e,t){var i=c(this);if(i.proto===this)return h(this,e,null,t),t;var o=r(this,"content");return n(o,e,t)}})}(),function(){function e(){return 0===s.length?{}:s.pop()}function t(e){return s.push(e),null}function r(e,t){function r(r){var o=n(r,e);return i?t===o:!!o}var i=2===arguments.length;return r}var n=Ember.get,i=Ember.set,o=Array.prototype.slice,a=Ember.EnumerableUtils.indexOf,s=[];Ember.Enumerable=Ember.Mixin.create({nextObject:Ember.required(Function),firstObject:Ember.computed(function(){if(0===n(this,"length"))return void 0;var r,i=e();return r=this.nextObject(0,null,i),t(i),r}).property("[]"),lastObject:Ember.computed(function(){var r=n(this,"length");if(0===r)return void 0;var i,o=e(),a=0,s=null;do s=i,i=this.nextObject(a++,s,o);while(void 0!==i);return t(o),s}).property("[]"),contains:function(e){return void 0!==this.find(function(t){return t===e})},forEach:function(r,i){if("function"!=typeof r)throw new TypeError;var o=n(this,"length"),a=null,s=e();void 0===i&&(i=null);for(var u=0;o>u;u++){var l=this.nextObject(u,a,s);r.call(i,l,u,this),a=l}return a=null,s=t(s),this},getEach:function(e){return this.mapBy(e)},setEach:function(e,t){return this.forEach(function(r){i(r,e,t)})},map:function(e,t){var r=Ember.A();return this.forEach(function(n,i,o){r[i]=e.call(t,n,i,o)}),r},mapBy:function(e){return this.map(function(t){return n(t,e)})},mapProperty:Ember.aliasMethod("mapBy"),filter:function(e,t){var r=Ember.A();return this.forEach(function(n,i,o){e.call(t,n,i,o)&&r.push(n)}),r},reject:function(e,t){return this.filter(function(){return!e.apply(t,arguments)})},filterBy:function(){return this.filter(r.apply(this,arguments))},filterProperty:Ember.aliasMethod("filterBy"),rejectBy:function(e,t){var r=function(r){return n(r,e)===t},i=function(t){return!!n(t,e)},o=2===arguments.length?r:i;return this.reject(o)},rejectProperty:Ember.aliasMethod("rejectBy"),find:function(r,i){var o=n(this,"length");void 0===i&&(i=null);for(var a,s,u=null,l=!1,c=e(),h=0;o>h&&!l;h++)a=this.nextObject(h,u,c),(l=r.call(i,a,h,this))&&(s=a),u=a;return a=u=null,c=t(c),s},findBy:function(){return this.find(r.apply(this,arguments))},findProperty:Ember.aliasMethod("findBy"),every:function(e,t){return!this.find(function(r,n,i){return!e.call(t,r,n,i)})},everyBy:Ember.aliasMethod("isEvery"),everyProperty:Ember.aliasMethod("isEvery"),isEvery:function(){return this.every(r.apply(this,arguments))},any:function(r,i){var o,a,s=n(this,"length"),u=e(),l=!1,c=null;for(void 0===i&&(i=null),a=0;s>a&&!l;a++)o=this.nextObject(a,c,u),l=r.call(i,o,a,this),c=o;return o=c=null,u=t(u),l},some:Ember.aliasMethod("any"),isAny:function(){return this.any(r.apply(this,arguments))},anyBy:Ember.aliasMethod("isAny"),someProperty:Ember.aliasMethod("isAny"),reduce:function(e,t,r){if("function"!=typeof e)throw new TypeError;var n=t;return this.forEach(function(t,i){n=e(n,t,i,this,r)},this),n},invoke:function(e){var t,r=Ember.A();return arguments.length>1&&(t=o.call(arguments,1)),this.forEach(function(n,i){var o=n&&n[e];"function"==typeof o&&(r[i]=t?o.apply(n,t):n[e]())},this),r},toArray:function(){var e=Ember.A();return this.forEach(function(t,r){e[r]=t}),e},compact:function(){return this.filter(function(e){return null!=e})},without:function(e){if(!this.contains(e))return this;var t=Ember.A();return this.forEach(function(r){r!==e&&(t[t.length]=r)}),t},uniq:function(){var e=Ember.A();return this.forEach(function(t){a(e,t)<0&&e.push(t)}),e},"[]":Ember.computed(function(){return this}),addEnumerableObserver:function(e,t){var r=t&&t.willChange||"enumerableWillChange",i=t&&t.didChange||"enumerableDidChange",o=n(this,"hasEnumerableObservers");return o||Ember.propertyWillChange(this,"hasEnumerableObservers"),Ember.addListener(this,"@enumerable:before",e,r),Ember.addListener(this,"@enumerable:change",e,i),o||Ember.propertyDidChange(this,"hasEnumerableObservers"),this},removeEnumerableObserver:function(e,t){var r=t&&t.willChange||"enumerableWillChange",i=t&&t.didChange||"enumerableDidChange",o=n(this,"hasEnumerableObservers");return o&&Ember.propertyWillChange(this,"hasEnumerableObservers"),Ember.removeListener(this,"@enumerable:before",e,r),Ember.removeListener(this,"@enumerable:change",e,i),o&&Ember.propertyDidChange(this,"hasEnumerableObservers"),this},hasEnumerableObservers:Ember.computed(function(){return Ember.hasListeners(this,"@enumerable:change")||Ember.hasListeners(this,"@enumerable:before")}),enumerableContentWillChange:function(e,t){var r,i,o;return r="number"==typeof e?e:e?n(e,"length"):e=-1,i="number"==typeof t?t:t?n(t,"length"):t=-1,o=0>i||0>r||i-r!==0,-1===e&&(e=null),-1===t&&(t=null),Ember.propertyWillChange(this,"[]"),o&&Ember.propertyWillChange(this,"length"),Ember.sendEvent(this,"@enumerable:before",[this,e,t]),this},enumerableContentDidChange:function(e,t){var r,i,o;return r="number"==typeof e?e:e?n(e,"length"):e=-1,i="number"==typeof t?t:t?n(t,"length"):t=-1,o=0>i||0>r||i-r!==0,-1===e&&(e=null),-1===t&&(t=null),Ember.sendEvent(this,"@enumerable:change",[this,e,t]),o&&Ember.propertyDidChange(this,"length"),Ember.propertyDidChange(this,"[]"),this},sortBy:function(){var e=arguments;return this.toArray().sort(function(t,r){for(var i=0;it||t>=e(this,"length")?void 0:e(this,t)},objectsAt:function(e){var t=this;return r(e,function(e){return t.objectAt(e)})},nextObject:function(e){return this.objectAt(e)},"[]":Ember.computed(function(t,r){return void 0!==r&&this.replace(0,e(this,"length"),r),this}),firstObject:Ember.computed(function(){return this.objectAt(0)}),lastObject:Ember.computed(function(){return this.objectAt(e(this,"length")-1)}),contains:function(e){return this.indexOf(e)>=0},slice:function(r,n){var i=Ember.A(),o=e(this,"length");for(t(r)&&(r=0),(t(n)||n>o)&&(n=o),0>r&&(r=o+r),0>n&&(n=o+n);n>r;)i[i.length]=this.objectAt(r++);return i},indexOf:function(t,r){var n,i=e(this,"length");for(void 0===r&&(r=0),0>r&&(r+=i),n=r;i>n;n++)if(this.objectAt(n)===t)return n;return-1},lastIndexOf:function(t,r){var n,i=e(this,"length");for((void 0===r||r>=i)&&(r=i-1),0>r&&(r+=i),n=r;n>=0;n--)if(this.objectAt(n)===t)return n;return-1},addArrayObserver:function(t,r){var n=r&&r.willChange||"arrayWillChange",i=r&&r.didChange||"arrayDidChange",o=e(this,"hasArrayObservers");return o||Ember.propertyWillChange(this,"hasArrayObservers"),Ember.addListener(this,"@array:before",t,n),Ember.addListener(this,"@array:change",t,i),o||Ember.propertyDidChange(this,"hasArrayObservers"),this},removeArrayObserver:function(t,r){var n=r&&r.willChange||"arrayWillChange",i=r&&r.didChange||"arrayDidChange",o=e(this,"hasArrayObservers");return o&&Ember.propertyWillChange(this,"hasArrayObservers"),Ember.removeListener(this,"@array:before",t,n),Ember.removeListener(this,"@array:change",t,i),o&&Ember.propertyDidChange(this,"hasArrayObservers"),this},hasArrayObservers:Ember.computed(function(){return Ember.hasListeners(this,"@array:change")||Ember.hasListeners(this,"@array:before")}),arrayContentWillChange:function(t,r,n){void 0===t?(t=0,r=n=-1):(void 0===r&&(r=-1),void 0===n&&(n=-1)),Ember.isWatching(this,"@each")&&e(this,"@each"),Ember.sendEvent(this,"@array:before",[this,t,r,n]);var i,o;if(t>=0&&r>=0&&e(this,"hasEnumerableObservers")){i=[],o=t+r;for(var a=t;o>a;a++)i.push(this.objectAt(a))}else i=r;return this.enumerableContentWillChange(i,n),this},arrayContentDidChange:function(t,r,i){void 0===t?(t=0,r=i=-1):(void 0===r&&(r=-1),void 0===i&&(i=-1));var o,a;if(t>=0&&i>=0&&e(this,"hasEnumerableObservers")){o=[],a=t+i;for(var s=t;a>s;s++)o.push(this.objectAt(s))}else o=i;this.enumerableContentDidChange(r,o),Ember.sendEvent(this,"@array:change",[this,t,r,i]);var u=e(this,"length"),l=n(this,"firstObject"),c=n(this,"lastObject");return this.objectAt(0)!==l&&(Ember.propertyWillChange(this,"firstObject"),Ember.propertyDidChange(this,"firstObject")),this.objectAt(u-1)!==c&&(Ember.propertyWillChange(this,"lastObject"),Ember.propertyDidChange(this,"lastObject")),this},"@each":Ember.computed(function(){return this.__each||(this.__each=new Ember.EachProxy(this)),this.__each})})}(),function(){function e(e,t){return"@this"===t?e:m(e,t)}function t(e,t,r){this.callbacks=e,this.cp=t,this.instanceMeta=r,this.dependentKeysByGuid={},this.trackedArraysByGuid={},this.suspended=!1,this.changedItems={}}function r(e,t,r){this.dependentArray=e,this.index=t,this.item=e.objectAt(t),this.trackedArray=r,this.beforeObserver=null,this.observer=null,this.destroyed=!1}function n(e,t,r){return 0>e?Math.max(0,t+e):t>e?e:Math.min(t-r,e)}function i(e,t,r){return Math.min(r,t-e)}function o(e,t,r,n,i,o){var a={arrayChanged:e,index:r,item:t,propertyName:n,property:i};return o&&(a.previousValues=o),a}function a(e,t,r,n,i){O(e,function(a,s){i.setValue(t.addedItem.call(this,i.getValue(),a,o(e,a,s,n,r),i.sugarMeta))},this)}function s(e,t){{var r;e._callbacks()}e._hasInstanceMeta(this,t)?(r=e._instanceMeta(this,t),r.setValue(e.resetValue(r.getValue()))):r=e._instanceMeta(this,t),e.options.initialize&&e.options.initialize.call(this,r.getValue(),{property:e,propertyName:t},r.sugarMeta)}function u(t,r){if(T.test(r))return!1;var n=e(t,r);return Ember.Array.detect(n)}function l(e,t,r){this.context=e,this.propertyName=t,this.cache=f(e).cache,this.dependentArrays={},this.sugarMeta={},this.initialValue=r}function c(t){var r=this;this.options=t,this._instanceMetas={},this._dependentKeys=null,this._itemPropertyKeys={},this._previousItemPropertyKeys={},this.readOnly(),this.cacheable(),this.recomputeOnce=function(e){Ember.run.once(this,n,e)};var n=function(t){var n=(r._dependentKeys,r._instanceMeta(this,t)),i=r._callbacks();s.call(this,r,t),n.dependentArraysObserver.suspendArrayObservers(function(){O(r._dependentKeys,function(t){if(u(this,t)){var i=e(this,t),o=n.dependentArrays[t];i===o?r._previousItemPropertyKeys[t]&&(delete r._previousItemPropertyKeys[t],n.dependentArraysObserver.setupPropertyObservers(t,r._itemPropertyKeys[t])):(n.dependentArrays[t]=i,o&&n.dependentArraysObserver.teardownObservers(o,t),i&&n.dependentArraysObserver.setupObservers(i,t))}},this)},this),O(r._dependentKeys,function(o){if(u(this,o)){var s=e(this,o);s&&a.call(this,s,i,r,t,n)}},this)};this.func=function(e){return n.call(this,e),r._instanceMeta(this,e).getValue()}}function h(e){return e}var m=Ember.get,p=(Ember.set,Ember.guidFor),f=Ember.meta,d=Ember.propertyWillChange,b=Ember.propertyDidChange,v=Ember.addBeforeObserver,E=Ember.removeBeforeObserver,g=Ember.addObserver,y=Ember.removeObserver,_=Ember.ComputedProperty,w=[].slice,C=Ember.create,O=Ember.EnumerableUtils.forEach,P=/^(.*)\.@each\.(.*)/,A=/(.*\.@each){2,}/,T=/\.\[\]$/,x=Ember.expandProperties;t.prototype={setValue:function(e){this.instanceMeta.setValue(e,!0)},getValue:function(){return this.instanceMeta.getValue()},setupObservers:function(e,t){this.dependentKeysByGuid[p(e)]=t,e.addArrayObserver(this,{willChange:"dependentArrayWillChange",didChange:"dependentArrayDidChange"}),this.cp._itemPropertyKeys[t]&&this.setupPropertyObservers(t,this.cp._itemPropertyKeys[t])},teardownObservers:function(e,t){var r=this.cp._itemPropertyKeys[t]||[];delete this.dependentKeysByGuid[p(e)],this.teardownPropertyObservers(t,r),e.removeArrayObserver(this,{willChange:"dependentArrayWillChange",didChange:"dependentArrayDidChange"})},suspendArrayObservers:function(e,t){var r=this.suspended;this.suspended=!0,e.call(t),this.suspended=r},setupPropertyObservers:function(t,r){var n=e(this.instanceMeta.context,t),i=e(n,"length"),o=new Array(i);this.resetTransformations(t,o),O(n,function(e,i){var a=this.createPropertyObserverContext(n,i,this.trackedArraysByGuid[t]);o[i]=a,O(r,function(t){v(e,t,this,a.beforeObserver),g(e,t,this,a.observer)},this)},this)},teardownPropertyObservers:function(e,t){var r,n,i,o=this,a=this.trackedArraysByGuid[e];a&&a.apply(function(e,a,s){s!==Ember.TrackedArray.DELETE&&O(e,function(e){e.destroyed=!0,r=e.beforeObserver,n=e.observer,i=e.item,O(t,function(e){E(i,e,o,r),y(i,e,o,n)})})})},createPropertyObserverContext:function(e,t,n){var i=new r(e,t,n);return this.createPropertyObserver(i),i},createPropertyObserver:function(e){var t=this;e.beforeObserver=function(r,n){return t.itemPropertyWillChange(r,n,e.dependentArray,e)},e.observer=function(r,n){return t.itemPropertyDidChange(r,n,e.dependentArray,e)}},resetTransformations:function(e,t){this.trackedArraysByGuid[e]=new Ember.TrackedArray(t)},trackAdd:function(e,t,r){var n=this.trackedArraysByGuid[e];n&&n.addItems(t,r)},trackRemove:function(e,t,r){var n=this.trackedArraysByGuid[e];return n?n.removeItems(t,r):[]},updateIndexes:function(t,r){var n=e(r,"length");t.apply(function(e,t,r){r!==Ember.TrackedArray.DELETE&&(r!==Ember.TrackedArray.RETAIN||e.length!==n||0!==t)&&O(e,function(e,r){e.index=r+t})})},dependentArrayWillChange:function(t,r,a){function s(e){m[h].destroyed=!0,E(l,e,this,m[h].beforeObserver),y(l,e,this,m[h].observer)}if(!this.suspended){var u,l,c,h,m,f=this.callbacks.removedItem,d=p(t),b=this.dependentKeysByGuid[d],v=this.cp._itemPropertyKeys[b]||[],g=e(t,"length"),_=n(r,g,0),w=i(_,g,a);for(m=this.trackRemove(b,_,w),h=w-1;h>=0&&(c=_+h,!(c>=g));--h)l=t.objectAt(c),O(v,s,this),u=o(t,l,c,this.instanceMeta.propertyName,this.cp),this.setValue(f.call(this.instanceMeta.context,this.getValue(),l,u,this.instanceMeta.sugarMeta))}},dependentArrayDidChange:function(t,r,i,a){if(!this.suspended){var s,u,l=this.callbacks.addedItem,c=p(t),h=this.dependentKeysByGuid[c],m=new Array(a),f=this.cp._itemPropertyKeys[h],d=e(t,"length"),b=n(r,d,a);O(t.slice(b,b+a),function(e,r){f&&(u=m[r]=this.createPropertyObserverContext(t,b+r,this.trackedArraysByGuid[h]),O(f,function(t){v(e,t,this,u.beforeObserver),g(e,t,this,u.observer)},this)),s=o(t,e,b+r,this.instanceMeta.propertyName,this.cp),this.setValue(l.call(this.instanceMeta.context,this.getValue(),e,s,this.instanceMeta.sugarMeta))},this),this.trackAdd(h,b,m)}},itemPropertyWillChange:function(t,r,n,i){var o=p(t);this.changedItems[o]||(this.changedItems[o]={array:n,observerContext:i,obj:t,previousValues:{}}),this.changedItems[o].previousValues[r]=e(t,r)},itemPropertyDidChange:function(){this.flushChanges()},flushChanges:function(){var e,t,r,n=this.changedItems;for(e in n)t=n[e],t.observerContext.destroyed||(this.updateIndexes(t.observerContext.trackedArray,t.observerContext.dependentArray),r=o(t.array,t.obj,t.observerContext.index,this.instanceMeta.propertyName,this.cp,t.previousValues),this.setValue(this.callbacks.removedItem.call(this.instanceMeta.context,this.getValue(),t.obj,r,this.instanceMeta.sugarMeta)),this.setValue(this.callbacks.addedItem.call(this.instanceMeta.context,this.getValue(),t.obj,r,this.instanceMeta.sugarMeta)));this.changedItems={}}},l.prototype={getValue:function(){return this.propertyName in this.cache?this.cache[this.propertyName]:this.initialValue},setValue:function(e,t){e!==this.cache[this.propertyName]&&(t&&d(this.context,this.propertyName),void 0===e?delete this.cache[this.propertyName]:this.cache[this.propertyName]=e,t&&b(this.context,this.propertyName))}},Ember.ReduceComputedProperty=c,c.prototype=C(_.prototype),c.prototype._callbacks=function(){if(!this.callbacks){var e=this.options;this.callbacks={removedItem:e.removedItem||h,addedItem:e.addedItem||h}}return this.callbacks},c.prototype._hasInstanceMeta=function(e,t){var r=p(e),n=r+":"+t;return!!this._instanceMetas[n]},c.prototype._instanceMeta=function(e,r){var n=p(e),i=n+":"+r,o=this._instanceMetas[i];return o||(o=this._instanceMetas[i]=new l(e,r,this.initialValue()),o.dependentArraysObserver=new t(this._callbacks(),this,o,e,r,o.sugarMeta)),o +},c.prototype.initialValue=function(){return"function"==typeof this.options.initialValue?this.options.initialValue():this.options.initialValue},c.prototype.resetValue=function(){return this.initialValue()},c.prototype.itemPropertyKey=function(e,t){this._itemPropertyKeys[e]=this._itemPropertyKeys[e]||[],this._itemPropertyKeys[e].push(t)},c.prototype.clearItemPropertyKeys=function(e){this._itemPropertyKeys[e]&&(this._previousItemPropertyKeys[e]=this._itemPropertyKeys[e],this._itemPropertyKeys[e]=[])},c.prototype.property=function(){var e,t,r=this,n=(w.call(arguments),new Ember.Set);return O(w.call(arguments),function(i){if(A.test(i))throw new Ember.Error("Nested @each properties not supported: "+i);if(e=P.exec(i)){t=e[1];var o=e[2],a=function(e){r.itemPropertyKey(t,e)};x(o,a),n.add(t)}else n.add(i)}),_.prototype.property.apply(this,n.toArray())},Ember.reduceComputed=function(e){var t;if(arguments.length>1&&(t=w.call(arguments,0,-1),e=w.call(arguments,-1)[0]),"object"!=typeof e)throw new Ember.Error("Reduce Computed Property declared without an options hash");if(!("initialValue"in e))throw new Ember.Error("Reduce Computed Property declared without an initial value");var r=new c(e);return t&&r.property.apply(r,t),r}}(),function(){function e(){var e=this;return t.apply(this,arguments),this.func=function(t){return function(r){return e._hasInstanceMeta(this,r)||i(e._dependentKeys,function(t){Ember.addObserver(this,t,function(){e.recomputeOnce.call(this,r)})},this),t.apply(this,arguments)}}(this.func),this}var t=Ember.ReduceComputedProperty,r=[].slice,n=Ember.create,i=Ember.EnumerableUtils.forEach;Ember.ArrayComputedProperty=e,e.prototype=n(t.prototype),e.prototype.initialValue=function(){return Ember.A()},e.prototype.resetValue=function(e){return e.clear(),e},e.prototype.didChange=function(){},Ember.arrayComputed=function(t){var n;if(arguments.length>1&&(n=r.call(arguments,0,-1),t=r.call(arguments,-1)[0]),"object"!=typeof t)throw new Ember.Error("Array Computed Property declared without an options hash");var i=new e(t);return n&&i.property.apply(i,n),i}}(),function(){function e(e,i,o,a){function s(e){return t.detectInstance(e)?n(r(e,"content")):n(e)}var u,l,c,h,m;return arguments.length<4&&(a=r(e,"length")),arguments.length<3&&(o=0),o===a?o:(u=o+Math.floor((a-o)/2),l=e.objectAt(u),h=s(l),m=s(i),h===m?u:(c=this.order(l,i),0===c&&(c=m>h?-1:1),0>c?this.binarySearch(e,i,u+1,a):c>0?this.binarySearch(e,i,o,u):u))}var t,r=Ember.get,n=(Ember.set,Ember.guidFor),i=Ember.merge,o=[].slice,a=Ember.EnumerableUtils.forEach,s=Ember.EnumerableUtils.map;Ember.computed.sum=function(e){return Ember.reduceComputed(e,{initialValue:0,addedItem:function(e,t){return e+t},removedItem:function(e,t){return e-t}})},Ember.computed.max=function(e){return Ember.reduceComputed(e,{initialValue:-1/0,addedItem:function(e,t){return Math.max(e,t)},removedItem:function(e,t){return e>t?e:void 0}})},Ember.computed.min=function(e){return Ember.reduceComputed(e,{initialValue:1/0,addedItem:function(e,t){return Math.min(e,t)},removedItem:function(e,t){return t>e?e:void 0}})},Ember.computed.map=function(e,t){var r={addedItem:function(e,r,n){var i=t.call(this,r);return e.insertAt(n.index,i),e},removedItem:function(e,t,r){return e.removeAt(r.index,1),e}};return Ember.arrayComputed(e,r)},Ember.computed.mapBy=function(e,t){var n=function(e){return r(e,t)};return Ember.computed.map(e+".@each."+t,n)},Ember.computed.mapProperty=Ember.computed.mapBy,Ember.computed.filter=function(e,t){var r={initialize:function(e,t,r){r.filteredArrayIndexes=new Ember.SubArray},addedItem:function(e,r,n,i){var o=!!t.call(this,r),a=i.filteredArrayIndexes.addItem(n.index,o);return o&&e.insertAt(a,r),e},removedItem:function(e,t,r,n){var i=n.filteredArrayIndexes.removeItem(r.index);return i>-1&&e.removeAt(i),e}};return Ember.arrayComputed(e,r)},Ember.computed.filterBy=function(e,t,n){var i;return i=2===arguments.length?function(e){return r(e,t)}:function(e){return r(e,t)===n},Ember.computed.filter(e+".@each."+t,i)},Ember.computed.filterProperty=Ember.computed.filterBy,Ember.computed.uniq=function(){var e=o.call(arguments);return e.push({initialize:function(e,t,r){r.itemCounts={}},addedItem:function(e,t,r,i){var o=n(t);return i.itemCounts[o]?++i.itemCounts[o]:i.itemCounts[o]=1,e.addObject(t),e},removedItem:function(e,t,r,i){var o=n(t),a=i.itemCounts;return 0===--a[o]&&e.removeObject(t),e}}),Ember.arrayComputed.apply(null,e)},Ember.computed.union=Ember.computed.uniq,Ember.computed.intersect=function(){var e=function(e){return s(e.property._dependentKeys,function(e){return n(e)})},t=o.call(arguments);return t.push({initialize:function(e,t,r){r.itemCounts={}},addedItem:function(t,r,i,o){var a=n(r),s=(e(i),n(i.arrayChanged)),u=i.property._dependentKeys.length,l=o.itemCounts;return l[a]||(l[a]={}),void 0===l[a][s]&&(l[a][s]=0),1===++l[a][s]&&u===Ember.keys(l[a]).length&&t.addObject(r),t},removedItem:function(t,r,i,o){var a,s=n(r),u=(e(i),n(i.arrayChanged)),l=(i.property._dependentKeys.length,o.itemCounts);return void 0===l[s][u]&&(l[s][u]=0),0===--l[s][u]&&(delete l[s][u],a=Ember.keys(l[s]).length,0===a&&delete l[s],t.removeObject(r)),t}}),Ember.arrayComputed.apply(null,t)},Ember.computed.setDiff=function(e,t){if(2!==arguments.length)throw new Ember.Error("setDiff requires exactly two dependent arrays.");return Ember.arrayComputed(e,t,{addedItem:function(n,i,o){var a=r(this,e),s=r(this,t);return o.arrayChanged===a?s.contains(i)||n.addObject(i):n.removeObject(i),n},removedItem:function(n,i,o){var a=r(this,e),s=r(this,t);return o.arrayChanged===s?a.contains(i)&&n.addObject(i):n.removeObject(i),n}})},t=Ember.ObjectProxy.extend(),Ember.computed.sort=function(n,o){var s,u;return"function"==typeof o?s=function(t,r,n){n.order=o,n.binarySearch=e}:(u=o,s=function(i,o,s){function l(){var e,t,i,l=r(this,u),h=s.sortProperties=[],m=s.sortPropertyAscending={};o.property.clearItemPropertyKeys(n),a(l,function(r){-1!==(t=r.indexOf(":"))?(e=r.substring(0,t),i="desc"!==r.substring(t+1).toLowerCase()):(e=r,i=!0),h.push(e),m[e]=i,o.property.itemPropertyKey(n,e)}),l.addObserver("@each",this,c)}function c(){Ember.run.once(this,h,o.propertyName)}function h(e){l.call(this),o.property.recomputeOnce.call(this,e)}Ember.addObserver(this,u,c),l.call(this),s.order=function(e,n){for(var i,o,a,s=n instanceof t,u=0;ue;e++){arguments[e]}return this.observes.apply(this,arguments)},Function.prototype.observesBefore=function(){for(var e=function(e){r.push(e)},r=[],n=0;nr(this,"length"))throw new Ember.Error(e);return this.replace(t,0,[n]),this},removeAt:function(n,i){if("number"==typeof n){if(0>n||n>=r(this,"length"))throw new Ember.Error(e);void 0===i&&(i=1),this.replace(n,i,t)}return this},pushObject:function(e){return this.insertAt(r(this,"length"),e),e},pushObjects:function(e){if(!Ember.Enumerable.detect(e)&&!Ember.isArray(e))throw new TypeError("Must pass Ember.Enumerable to Ember.MutableArray#pushObjects");return this.replace(r(this,"length"),0,e),this},popObject:function(){var e=r(this,"length");if(0===e)return null;var t=this.objectAt(e-1);return this.removeAt(e-1,1),t},shiftObject:function(){if(0===r(this,"length"))return null;var e=this.objectAt(0);return this.removeAt(0),e},unshiftObject:function(e){return this.insertAt(0,e),e},unshiftObjects:function(e){return this.replace(0,0,e),this},reverseObjects:function(){var e=r(this,"length");if(0===e)return this;var t=this.toArray().reverse();return this.replace(0,e,t),this},setObjects:function(e){if(0===e.length)return this.clear();var t=r(this,"length");return this.replace(0,t,e),this},removeObject:function(e){for(var t=r(this,"length")||0;--t>=0;){var n=this.objectAt(t);n===e&&this.removeAt(t)}return this},addObject:function(e){return this.contains(e)||this.pushObject(e),this}})}(),function(){{var e=Ember.get;Ember.set}Ember.TargetActionSupport=Ember.Mixin.create({target:null,action:null,actionContext:null,targetObject:Ember.computed(function(){var t=e(this,"target");if("string"===Ember.typeOf(t)){var r=e(this,t);return void 0===r&&(r=e(Ember.lookup,t)),r}return t}).property("target"),actionContextObject:Ember.computed(function(){var t=e(this,"actionContext");if("string"===Ember.typeOf(t)){var r=e(this,t);return void 0===r&&(r=e(Ember.lookup,t)),r}return t}).property("actionContext"),triggerAction:function(t){function r(e,t){var r=[];return t&&r.push(t),r.concat(e)}t=t||{};var n=t.action||e(this,"action"),i=t.target||e(this,"targetObject"),o=t.actionContext;if("undefined"==typeof o&&(o=e(this,"actionContextObject")||this),i&&n){var a;return a=i.send?i.send.apply(i,r(o,n)):i[n].apply(i,r(o)),a!==!1&&(a=!0),a}return!1}})}(),function(){Ember.Evented=Ember.Mixin.create({on:function(e,t,r){return Ember.addListener(this,e,t,r),this},one:function(e,t,r){return r||(r=t,t=null),Ember.addListener(this,e,t,r,!0),this},trigger:function(e){var t,r,n=[];for(t=1,r=arguments.length;r>t;t++)n.push(arguments[t]);Ember.sendEvent(this,e,n)},off:function(e,t,r){return Ember.removeListener(this,e,t,r),this},has:function(e){return Ember.hasListeners(this,e)}})}(),function(){var e=t("rsvp");if(Ember.FEATURES["ember-runtime-test-friendly-promises"]){var r=function(){Ember.Test&&Ember.Test.adapter&&Ember.Test.adapter.asyncStart()},n=function(){Ember.Test&&Ember.Test.adapter&&Ember.Test.adapter.asyncEnd()};e.configure("async",function(e,t){var i=!Ember.run.currentRunLoop;Ember.testing&&i&&r(),Ember.run.backburner.schedule("actions",function(){Ember.testing&&i&&n(),e(t)})})}else e.configure("async",function(e,t){Ember.run.backburner.schedule("actions",function(){e(t)})});e.Promise.prototype.fail=function(e,t){return this["catch"](e,t)};var i=Ember.get;Ember.DeferredMixin=Ember.Mixin.create({then:function(e,t,r){function n(t){return t===a?e(s):e(t)}var o,a,s;return s=this,o=i(this,"_deferred"),a=o.promise,a.then(e&&n,t,r)},resolve:function(e){var t,r;t=i(this,"_deferred"),r=t.promise,e===this?t.resolve(r):t.resolve(e)},reject:function(e){i(this,"_deferred").reject(e)},_deferred:Ember.computed(function(){return e.defer("Ember: DeferredMixin - "+this)})})}(),function(){var e=Ember.get,t=Ember.typeOf;Ember.ActionHandler=Ember.Mixin.create({mergedProperties:["_actions"],willMergeMixin:function(e){var r;e._actions||("object"===t(e.actions)?r="actions":"object"===t(e.events)&&(r="events"),r&&(e._actions=Ember.merge(e._actions||{},e[r])),delete e[r])},send:function(t){var r,n=[].slice.call(arguments,1);if(this._actions&&this._actions[t]){if(this._actions[t].apply(this,n)!==!0)return}else if(!Ember.FEATURES.isEnabled("ember-routing-drop-deprecated-action-style")&&this.deprecatedSend&&this.deprecatedSendHandles&&this.deprecatedSendHandles(t)&&this.deprecatedSend.apply(this,[].slice.call(arguments))!==!0)return;(r=e(this,"target"))&&r.send.apply(r,arguments)}})}(),function(){function e(e,t){return t.then(function(t){return r(e,"isFulfilled",!0),r(e,"content",t),t},function(t){throw r(e,"isRejected",!0),r(e,"reason",t),t},"Ember: PromiseProxy")}function t(e){return function(){var t=n(this,"promise");return t[e].apply(t,arguments)}}var r=Ember.set,n=Ember.get,i=Ember.computed.not,o=Ember.computed.or;Ember.PromiseProxyMixin=Ember.Mixin.create({reason:null,isPending:i("isSettled").readOnly(),isSettled:o("isRejected","isFulfilled").readOnly(),isRejected:!1,isFulfilled:!1,promise:Ember.computed(function(t,r){if(2===arguments.length)return e(this,r);throw new Ember.Error("PromiseProxy's promise must be set")}),then:t("then"),"catch":t("catch"),"finally":t("finally")})}(),function(){function e(e,t,r){this.type=e,this.count=t,this.items=r}function t(e,t,r,n){this.operation=e,this.index=t,this.split=r,this.rangeStart=n}var r=Ember.get,n=Ember.EnumerableUtils.forEach,i="r",o="i",a="d";Ember.TrackedArray=function(t){arguments.length<1&&(t=[]);var n=r(t,"length");this._operations=n?[new e(i,n,t)]:[]},Ember.TrackedArray.RETAIN=i,Ember.TrackedArray.INSERT=o,Ember.TrackedArray.DELETE=a,Ember.TrackedArray.prototype={addItems:function(t,n){var i=r(n,"length");if(!(1>i)){var a,s,u=this._findArrayOperation(t),l=u.operation,c=u.index,h=u.rangeStart;s=new e(o,i,n),l?u.split?(this._split(c,t-h,s),a=c+1):(this._operations.splice(c,0,s),a=c):(this._operations.push(s),a=c),this._composeInsert(a)}},removeItems:function(t,r){if(!(1>r)){var n,i,o=this._findArrayOperation(t),s=(o.operation,o.index),u=o.rangeStart;return n=new e(a,r),o.split?(this._split(s,t-u,n),i=s+1):(this._operations.splice(s,0,n),i=s),this._composeDelete(i)}},apply:function(t){var r=[],o=0;n(this._operations,function(e){t(e.items,o,e.type),e.type!==a&&(o+=e.count,r=r.concat(e.items))}),this._operations=[new e(i,r.length,r)]},_findArrayOperation:function(e){var r,n,i,o,s,u=!1;for(r=o=0,n=this._operations.length;n>r;++r)if(i=this._operations[r],i.type!==a){if(s=o+i.count-1,e===o)break;if(e>o&&s>=e){u=!0;break}o=s+1}return new t(i,r,u,o)},_split:function(t,r,n){var i=this._operations[t],o=i.items.slice(r),a=new e(i.type,o.length,o);i.count=r,i.items=i.items.slice(0,r),this._operations.splice(t+1,0,n,a)},_composeInsert:function(e){var t=this._operations[e],r=this._operations[e-1],n=this._operations[e+1],i=r&&r.type,a=n&&n.type;i===o?(r.count+=t.count,r.items=r.items.concat(t.items),a===o?(r.count+=n.count,r.items=r.items.concat(n.items),this._operations.splice(e,2)):this._operations.splice(e,1)):a===o&&(t.count+=n.count,t.items=t.items.concat(n.items),this._operations.splice(e+1,1))},_composeDelete:function(e){var t,r,n,i=this._operations[e],s=i.count,u=this._operations[e-1],l=u&&u.type,c=!1,h=[];l===a&&(i=u,e-=1);for(var m=e+1;s>0;++m)t=this._operations[m],r=t.type,n=t.count,r!==a?(n>s?(h=h.concat(t.items.splice(0,s)),t.count-=s,m-=1,n=s,s=0):(n===s&&(c=!0),h=h.concat(t.items),s-=n),r===o&&(i.count-=n)):i.count+=n;return i.count>0?this._operations.splice(e+1,m-1-e):this._operations.splice(e,c?2:1),h},toString:function(){var e="";return n(this._operations,function(t){e+=" "+t.type+":"+t.count}),e.substring(1)}}}(),function(){function e(e,t){this.type=e,this.count=t}var t=(Ember.get,Ember.EnumerableUtils.forEach),r="r",n="f";Ember.SubArray=function(t){arguments.length<1&&(t=0),this._operations=t>0?[new e(r,t)]:[]},Ember.SubArray.prototype={addItem:function(t,i){var o=-1,a=i?r:n,s=this;return this._findOperation(t,function(n,u,l,c,h){var m,p;a===n.type?++n.count:t===l?s._operations.splice(u,0,new e(a,1)):(m=new e(a,1),p=new e(n.type,c-t+1),n.count=t-l,s._operations.splice(u+1,0,m,p)),i&&(o=n.type===r?h+(t-l):h),s._composeAt(u)},function(t){s._operations.push(new e(a,1)),i&&(o=t),s._composeAt(s._operations.length-1)}),o},removeItem:function(e){var t=-1,n=this;return this._findOperation(e,function(i,o,a,s,u){i.type===r&&(t=u+(e-a)),i.count>1?--i.count:(n._operations.splice(o,1),n._composeAt(o))},function(){throw new Ember.Error("Can't remove an item that has never been added.")}),t},_findOperation:function(e,t,n){var i,o,a,s,u,l=0;for(i=s=0,o=this._operations.length;o>i;s=u+1,++i){if(a=this._operations[i],u=s+a.count-1,e>=s&&u>=e)return t(a,i,s,u,l),void 0;a.type===r&&(l+=a.count)}n(l)},_composeAt:function(e){var t,r=this._operations[e];r&&(e>0&&(t=this._operations[e-1],t.type===r.type&&(r.count+=t.count,this._operations.splice(e-1,1),--e)),er(this,"content.length"))throw new Ember.Error(e);return this._replace(t,0,[n]),this},insertAt:function(e,t){if(r(this,"arrangedContent")===r(this,"content"))return this._insertAt(e,t);throw new Ember.Error("Using insertAt on an arranged ArrayProxy is not allowed.")},removeAt:function(n,i){if("number"==typeof n){var o,a=r(this,"content"),s=r(this,"arrangedContent"),u=[];if(0>n||n>=r(this,"length"))throw new Ember.Error(e);for(void 0===i&&(i=1),o=n;n+i>o;o++)u.push(a.indexOf(s.objectAt(o)));for(u.sort(function(e,t){return t-e}),Ember.beginPropertyChanges(),o=0;o=i;){var u=e.objectAt(o);u&&(Ember.addBeforeObserver(u,t,r,"contentKeyWillChange"),Ember.addObserver(u,t,r,"contentKeyDidChange"),a=n(u),s[a]||(s[a]=[]),s[a].push(o))}}function t(e,t,r,i,a){var s=r._objects;s||(s=r._objects={});for(var u,l;--a>=i;){var c=e.objectAt(a);c&&(Ember.removeBeforeObserver(c,t,r,"contentKeyWillChange"),Ember.removeObserver(c,t,r,"contentKeyDidChange"),l=n(c),u=s[l],u[o.call(u,a)]=null)}}var r=(Ember.set,Ember.get),n=Ember.guidFor,i=Ember.EnumerableUtils.forEach,o=Ember.ArrayPolyfills.indexOf,a=Ember.Object.extend(Ember.Array,{init:function(e,t,r){this._super(),this._keyName=t,this._owner=r,this._content=e},objectAt:function(e){var t=this._content.objectAt(e);return t&&r(t,this._keyName)},length:Ember.computed(function(){var e=this._content;return e?r(e,"length"):0})}),s=/^.+:(before|change)$/;Ember.EachProxy=Ember.Object.extend({init:function(e){this._super(),this._content=e,e.addArrayObserver(this),i(Ember.watchedEvents(this),function(e){this.didAddListener(e)},this)},unknownProperty:function(e){var t;return t=new a(this._content,e,this),Ember.defineProperty(this,e,null,t),this.beginObservingContentKey(e),t},arrayWillChange:function(e,r,n){var i,o,a=this._keys;o=n>0?r+n:-1,Ember.beginPropertyChanges(this);for(i in a)a.hasOwnProperty(i)&&(o>0&&t(e,i,this,r,o),Ember.propertyWillChange(this,i));Ember.propertyWillChange(this._content,"@each"),Ember.endPropertyChanges(this)},arrayDidChange:function(t,r,n,i){var o,a=this._keys;o=i>0?r+i:-1,Ember.changeProperties(function(){for(var n in a)a.hasOwnProperty(n)&&(o>0&&e(t,n,this,r,o),Ember.propertyDidChange(this,n));Ember.propertyDidChange(this._content,"@each")},this)},didAddListener:function(e){s.test(e)&&this.beginObservingContentKey(e.slice(0,-7))},didRemoveListener:function(e){s.test(e)&&this.stopObservingContentKey(e.slice(0,-7))},beginObservingContentKey:function(t){var n=this._keys;if(n||(n=this._keys={}),n[t])n[t]++;else{n[t]=1;var i=this._content,o=r(i,"length");e(i,t,this,0,o)}},stopObservingContentKey:function(e){var n=this._keys;if(n&&n[e]>0&&--n[e]<=0){var i=this._content,o=r(i,"length");t(i,e,this,0,o)}},contentKeyWillChange:function(e,t){Ember.propertyWillChange(this,t)},contentKeyDidChange:function(e,t){Ember.propertyDidChange(this,t)}})}(),function(){var e=Ember.get,t=(Ember.set,Ember.EnumerableUtils._replace),r=Ember.Mixin.create(Ember.MutableArray,Ember.Observable,Ember.Copyable,{get:function(e){return"length"===e?this.length:"number"==typeof e?this[e]:this._super(e)},objectAt:function(e){return this[e]},replace:function(r,n,i){if(this.isFrozen)throw Ember.FROZEN_ERROR;var o=i?e(i,"length"):0;return this.arrayContentWillChange(r,n,o),0===o?this.splice(r,n):t(this,r,n,i),this.arrayContentDidChange(r,n,o),this},unknownProperty:function(e,t){var r;return void 0!==t&&void 0===r&&(r=this[e]=t),r},indexOf:function(e,t){var r,n=this.length;for(t=void 0===t?0:0>t?Math.ceil(t):Math.floor(t),0>t&&(t+=n),r=t;n>r;r++)if(this[r]===e)return r;return-1},lastIndexOf:function(e,t){var r,n=this.length;for(t=void 0===t?n-1:0>t?Math.ceil(t):Math.floor(t),0>t&&(t+=n),r=t;r>=0;r--)if(this[r]===e)return r;return-1},copy:function(e){return e?this.map(function(e){return Ember.copy(e,!0)}):this.slice()}}),n=["length"];Ember.EnumerableUtils.forEach(r.keys(),function(e){Array.prototype[e]&&n.push(e)}),n.length>0&&(r=r.without.apply(r,n)),Ember.NativeArray=r,Ember.A=function(e){return void 0===e&&(e=[]),Ember.Array.detect(e)?e:Ember.NativeArray.apply(e)},Ember.NativeArray.activate=function(){r.apply(Array.prototype),Ember.A=function(e){return e||[]}},(Ember.EXTEND_PROTOTYPES===!0||Ember.EXTEND_PROTOTYPES.Array)&&Ember.NativeArray.activate()}(),function(){var e=Ember.get,t=Ember.set,r=Ember.guidFor,n=Ember.isNone,i=Ember.String.fmt;Ember.Set=Ember.CoreObject.extend(Ember.MutableEnumerable,Ember.Copyable,Ember.Freezable,{length:0,clear:function(){if(this.isFrozen)throw new Ember.Error(Ember.FROZEN_ERROR);var n=e(this,"length");if(0===n)return this;var i;this.enumerableContentWillChange(n,0),Ember.propertyWillChange(this,"firstObject"),Ember.propertyWillChange(this,"lastObject");for(var o=0;n>o;o++)i=r(this[o]),delete this[i],delete this[o];return t(this,"length",0),Ember.propertyDidChange(this,"firstObject"),Ember.propertyDidChange(this,"lastObject"),this.enumerableContentDidChange(n,0),this},isEqual:function(t){if(!Ember.Enumerable.detect(t))return!1;var r=e(this,"length");if(e(t,"length")!==r)return!1;for(;--r>=0;)if(!t.contains(this[r]))return!1;return!0},add:Ember.aliasMethod("addObject"),remove:Ember.aliasMethod("removeObject"),pop:function(){if(e(this,"isFrozen"))throw new Ember.Error(Ember.FROZEN_ERROR);var t=this.length>0?this[this.length-1]:null;return this.remove(t),t},push:Ember.aliasMethod("addObject"),shift:Ember.aliasMethod("pop"),unshift:Ember.aliasMethod("push"),addEach:Ember.aliasMethod("addObjects"),removeEach:Ember.aliasMethod("removeObjects"),init:function(e){this._super(),e&&this.addObjects(e)},nextObject:function(e){return this[e]},firstObject:Ember.computed(function(){return this.length>0?this[0]:void 0}),lastObject:Ember.computed(function(){return this.length>0?this[this.length-1]:void 0}),addObject:function(i){if(e(this,"isFrozen"))throw new Ember.Error(Ember.FROZEN_ERROR);if(n(i))return this;var o,a=r(i),s=this[a],u=e(this,"length");return s>=0&&u>s&&this[s]===i?this:(o=[i],this.enumerableContentWillChange(null,o),Ember.propertyWillChange(this,"lastObject"),u=e(this,"length"),this[a]=u,this[u]=i,t(this,"length",u+1),Ember.propertyDidChange(this,"lastObject"),this.enumerableContentDidChange(null,o),this)},removeObject:function(i){if(e(this,"isFrozen"))throw new Ember.Error(Ember.FROZEN_ERROR);if(n(i))return this;var o,a,s=r(i),u=this[s],l=e(this,"length"),c=0===u,h=u===l-1;return u>=0&&l>u&&this[u]===i&&(a=[i],this.enumerableContentWillChange(a,null),c&&Ember.propertyWillChange(this,"firstObject"),h&&Ember.propertyWillChange(this,"lastObject"),l-1>u&&(o=this[l-1],this[u]=o,this[r(o)]=u),delete this[s],delete this[l-1],t(this,"length",l-1),c&&Ember.propertyDidChange(this,"firstObject"),h&&Ember.propertyDidChange(this,"lastObject"),this.enumerableContentDidChange(a,null)),this},contains:function(e){return this[r(e)]>=0},copy:function(){var n=this.constructor,i=new n,o=e(this,"length");for(t(i,"length",o);--o>=0;)i[o]=this[o],i[r(this[o])]=o;return i},toString:function(){var e,t=this.length,r=[];for(e=0;t>e;e++)r[e]=this[e];return i("Ember.Set<%@>",[r.join(",")])}})}(),function(){var e=Ember.DeferredMixin,t=(Ember.get,Ember.Object.extend(e));t.reopenClass({promise:function(e,r){var n=t.create();return e.call(r,n),n}}),Ember.Deferred=t}(),function(){var e=Ember.ArrayPolyfills.forEach,t=Ember.ENV.EMBER_LOAD_HOOKS||{},r={};Ember.onLoad=function(e,n){var i;t[e]=t[e]||Ember.A(),t[e].pushObject(n),(i=r[e])&&n(i)},Ember.runLoadHooks=function(n,i){r[n]=i,t[n]&&e.call(t[n],function(e){e(i)})}}(),function(){Ember.get;Ember.ControllerMixin=Ember.Mixin.create(Ember.ActionHandler,{isController:!0,target:null,container:null,parentController:null,store:null,model:Ember.computed.alias("content"),deprecatedSendHandles:function(e){return!!this[e]},deprecatedSend:function(e){var t=[].slice.call(arguments,1);this[e].apply(this,t)}}),Ember.Controller=Ember.Object.extend(Ember.ControllerMixin)}(),function(){var e=Ember.get,t=(Ember.set,Ember.EnumerableUtils.forEach);Ember.SortableMixin=Ember.Mixin.create(Ember.MutableEnumerable,{sortProperties:null,sortAscending:!0,sortFunction:Ember.compare,orderBy:function(r,n){var i=0,o=e(this,"sortProperties"),a=e(this,"sortAscending"),s=e(this,"sortFunction");return t(o,function(t){0===i&&(i=s(e(r,t),e(n,t)),0===i||a||(i=-1*i))}),i},destroy:function(){var r=e(this,"content"),n=e(this,"sortProperties");return r&&n&&t(r,function(e){t(n,function(t){Ember.removeObserver(e,t,this,"contentItemSortPropertyDidChange")},this)},this),this._super()},isSorted:Ember.computed.bool("sortProperties"),arrangedContent:Ember.computed("content","sortProperties.@each",function(){var r=e(this,"content"),n=e(this,"isSorted"),i=e(this,"sortProperties"),o=this;return r&&n?(r=r.slice(),r.sort(function(e,t){return o.orderBy(e,t)}),t(r,function(e){t(i,function(t){Ember.addObserver(e,t,this,"contentItemSortPropertyDidChange")},this)},this),Ember.A(r)):r}),_contentWillChange:Ember.beforeObserver("content",function(){var r=e(this,"content"),n=e(this,"sortProperties");r&&n&&t(r,function(e){t(n,function(t){Ember.removeObserver(e,t,this,"contentItemSortPropertyDidChange")},this)},this),this._super()}),sortAscendingWillChange:Ember.beforeObserver("sortAscending",function(){this._lastSortAscending=e(this,"sortAscending")}),sortAscendingDidChange:Ember.observer("sortAscending",function(){if(e(this,"sortAscending")!==this._lastSortAscending){var t=e(this,"arrangedContent");t.reverseObjects()}}),contentArrayWillChange:function(r,n,i,o){var a=e(this,"isSorted");if(a){var s=e(this,"arrangedContent"),u=r.slice(n,n+i),l=e(this,"sortProperties");t(u,function(e){s.removeObject(e),t(l,function(t){Ember.removeObserver(e,t,this,"contentItemSortPropertyDidChange")},this)},this)}return this._super(r,n,i,o)},contentArrayDidChange:function(r,n,i,o){var a=e(this,"isSorted"),s=e(this,"sortProperties");if(a){var u=r.slice(n,n+o);t(u,function(e){this.insertItemSorted(e),t(s,function(t){Ember.addObserver(e,t,this,"contentItemSortPropertyDidChange")},this)},this)}return this._super(r,n,i,o)},insertItemSorted:function(t){var r=e(this,"arrangedContent"),n=e(r,"length"),i=this._binarySearch(t,0,n);r.insertAt(i,t)},contentItemSortPropertyDidChange:function(t){var r=e(this,"arrangedContent"),n=r.indexOf(t),i=r.objectAt(n-1),o=r.objectAt(n+1),a=i&&this.orderBy(t,i),s=o&&this.orderBy(t,o);(0>a||s>0)&&(r.removeObject(t),this.insertItemSorted(t))},_binarySearch:function(t,r,n){var i,o,a,s;return r===n?r:(s=e(this,"arrangedContent"),i=r+Math.floor((n-r)/2),o=s.objectAt(i),a=this.orderBy(o,t),0>a?this._binarySearch(t,i+1,n):a>0?this._binarySearch(t,r,i):i)}})}(),function(){var e=Ember.get,t=(Ember.set,Ember.EnumerableUtils.forEach),r=Ember.EnumerableUtils.replace;Ember.ArrayController=Ember.ArrayProxy.extend(Ember.ControllerMixin,Ember.SortableMixin,{itemController:null,lookupItemController:function(){return e(this,"itemController")},objectAtContent:function(t){var r=e(this,"length"),n=e(this,"arrangedContent"),i=n&&n.objectAt(t);if(t>=0&&r>t){var o=this.lookupItemController(i);if(o)return this.controllerAt(t,i,o)}return i},arrangedContentDidChange:function(){this._super(),this._resetSubControllers()},arrayContentDidChange:function(n,i,o){var a=e(this,"_subControllers"),s=a.slice(n,n+i); +t(s,function(e){e&&e.destroy()}),r(a,n,i,new Array(o)),this._super(n,i,o)},init:function(){this._super(),this.set("_subControllers",Ember.A())},content:Ember.computed(function(){return Ember.A()}),_isVirtual:!1,controllerAt:function(t,r,n){var i,o=e(this,"container"),a=e(this,"_subControllers"),s=a[t];if(s)return s;if(i="controller:"+n,!o.has(i))throw new Ember.Error('Could not resolve itemController: "'+n+'"');var u;return this._isVirtual&&(u=e(this,"parentController")),u=u||this,s=o.lookupFactory(i).create({target:this,parentController:u,content:r}),a[t]=s,s},_subControllers:null,_resetSubControllers:function(){var r=e(this,"_subControllers");r&&t(r,function(e){e&&e.destroy()}),this.set("_subControllers",Ember.A())}})}(),function(){Ember.ObjectController=Ember.ObjectProxy.extend(Ember.ControllerMixin)}(),function(){var e=this&&this.jQuery||Ember.imports&&Ember.imports.jQuery;e||"function"!=typeof r||(e=r("jquery")),Ember.$=e}(),function(){if(Ember.$){var e=Ember.String.w("dragstart drag dragenter dragleave dragover drop dragend");Ember.EnumerableUtils.forEach(e,function(e){Ember.$.event.fixHooks[e]={props:["dataTransfer"]}})}}(),function(){function e(e){var t=e.shiftKey||e.metaKey||e.altKey||e.ctrlKey,r=e.which>1;return!t&&!r}var t="undefined"!=typeof document&&function(){var e=document.createElement("div");return e.innerHTML="
",e.firstChild.innerHTML="",""===e.firstChild.innerHTML}(),r="undefined"!=typeof document&&function(){var e=document.createElement("div");return e.innerHTML="Test: Value","Test:"===e.childNodes[0].nodeValue&&" Value"===e.childNodes[2].nodeValue}(),n=function(e,t){if(e.getAttribute("id")===t)return e;var r,i,o,a=e.childNodes.length;for(r=0;a>r;r++)if(i=e.childNodes[r],o=1===i.nodeType&&n(i,t))return o},i=function(e,i){t&&(i="­"+i);var o=[];if(r&&(i=i.replace(/(\s+)(",""===e.firstChild.innerHTML}(),o=document&&function(){var e=document.createElement("div");return e.innerHTML="Test: Value","Test:"===e.childNodes[0].nodeValue&&" Value"===e.childNodes[2].nodeValue}(),a=function(r){var n;n=this instanceof a?this:new e,n.innerHTML=r;var i="metamorph-"+t++;return n.start=i+"-start",n.end=i+"-end",n};e.prototype=a.prototype;var s,u,l,c,h,m,p,f,d;if(c=function(){return this.startTag()+this.innerHTML+this.endTag()},f=function(){return""},d=function(){return""},n)s=function(e,t){var r=document.createRange(),n=document.getElementById(e.start),i=document.getElementById(e.end);return t?(r.setStartBefore(n),r.setEndAfter(i)):(r.setStartAfter(n),r.setEndBefore(i)),r},u=function(e,t){var r=s(this,t);r.deleteContents();var n=r.createContextualFragment(e);r.insertNode(n)},l=function(){var e=s(this,!0);e.deleteContents()},h=function(e){var t=document.createRange();t.setStart(e),t.collapse(!1);var r=t.createContextualFragment(this.outerHTML());e.appendChild(r)},m=function(e){var t=document.createRange(),r=document.getElementById(this.end);t.setStartAfter(r),t.setEndAfter(r);var n=t.createContextualFragment(e);t.insertNode(n)},p=function(e){var t=document.createRange(),r=document.getElementById(this.start);t.setStartAfter(r),t.setEndAfter(r);var n=t.createContextualFragment(e);t.insertNode(n)};else{var b={select:[1,""],fieldset:[1,"
","
"],table:[1,"","
"],tbody:[2,"","
"],tr:[3,"","
"],colgroup:[2,"","
"],map:[1,"",""],_default:[0,"",""]},v=function(e,t){if(e.getAttribute("id")===t)return e;var r,n,i,o=e.childNodes.length;for(r=0;o>r;r++)if(n=e.childNodes[r],i=1===n.nodeType&&v(n,t))return i},E=function(e,t){var r=[];if(o&&(t=t.replace(/(\s+)("; - return testEl.firstChild.innerHTML === ''; -})(); - -// IE 8 (and likely earlier) likes to move whitespace preceeding -// a script tag to appear after it. This means that we can -// accidentally remove whitespace when updating a morph. -var movesWhitespace = this.document && (function() { - var testEl = document.createElement('div'); - testEl.innerHTML = "Test: Value"; - return testEl.childNodes[0].nodeValue === 'Test:' && - testEl.childNodes[2].nodeValue === ' Value'; -})(); - -// Use this to find children by ID instead of using jQuery -var findChildById = function(element, id) { - if (element.getAttribute('id') === id) { return element; } - - var len = element.childNodes.length, idx, node, found; - for (idx=0; idx 0) { - var len = matches.length, idx; - for (idx=0; idxTest'); - canSet = el.options.length === 1; - } - - innerHTMLTags[tagName] = canSet; - - return canSet; -}; - -var setInnerHTML = function(element, html) { - var tagName = element.tagName; - - if (canSetInnerHTML(tagName)) { - setInnerHTMLWithoutFix(element, html); - } else { - // Firefox versions < 11 do not have support for element.outerHTML. - var outerHTML = element.outerHTML || new XMLSerializer().serializeToString(element); - - var startTag = outerHTML.match(new RegExp("<"+tagName+"([^>]*)>", 'i'))[0], - endTag = ''; - - var wrapper = document.createElement('div'); - setInnerHTMLWithoutFix(wrapper, startTag + html + endTag); - element = wrapper.firstChild; - while (element.tagName !== tagName) { - element = element.nextSibling; - } - } - - return element; -}; - -function isSimpleClick(event) { - var modifier = event.shiftKey || event.metaKey || event.altKey || event.ctrlKey, - secondaryClick = event.which > 1; // IE9 may return undefined - - return !modifier && !secondaryClick; -} - -Ember.ViewUtils = { - setInnerHTML: setInnerHTML, - isSimpleClick: isSimpleClick -}; - -})(); - - - -(function() { -/** -@module ember -@submodule ember-views -*/ - -var get = Ember.get, set = Ember.set; - -var ClassSet = function() { - this.seen = {}; - this.list = []; -}; - -ClassSet.prototype = { - add: function(string) { - if (string in this.seen) { return; } - this.seen[string] = true; - - this.list.push(string); - }, - - toDOM: function() { - return this.list.join(" "); - } -}; - -var BAD_TAG_NAME_TEST_REGEXP = /[^a-zA-Z0-9\-]/; -var BAD_TAG_NAME_REPLACE_REGEXP = /[^a-zA-Z0-9\-]/g; - -function stripTagName(tagName) { - if (!tagName) { - return tagName; - } - - if (!BAD_TAG_NAME_TEST_REGEXP.test(tagName)) { - return tagName; - } - - return tagName.replace(BAD_TAG_NAME_REPLACE_REGEXP, ''); -} - -var BAD_CHARS_REGEXP = /&(?!\w+;)|[<>"'`]/g; -var POSSIBLE_CHARS_REGEXP = /[&<>"'`]/; - -function escapeAttribute(value) { - // Stolen shamelessly from Handlebars - - var escape = { - "<": "<", - ">": ">", - '"': """, - "'": "'", - "`": "`" - }; - - var escapeChar = function(chr) { - return escape[chr] || "&"; - }; - - var string = value.toString(); - - if(!POSSIBLE_CHARS_REGEXP.test(string)) { return string; } - return string.replace(BAD_CHARS_REGEXP, escapeChar); -} - -// IE 6/7 have bugs arond setting names on inputs during creation. -// From http://msdn.microsoft.com/en-us/library/ie/ms536389(v=vs.85).aspx: -// "To include the NAME attribute at run time on objects created with the createElement method, use the eTag." -var canSetNameOnInputs = (function() { - var div = document.createElement('div'), - el = document.createElement('input'); - - el.setAttribute('name', 'foo'); - div.appendChild(el); - - return !!div.innerHTML.match('foo'); -})(); - -/** - `Ember.RenderBuffer` gathers information regarding the a view and generates the - final representation. `Ember.RenderBuffer` will generate HTML which can be pushed - to the DOM. - - ```javascript - var buffer = Ember.RenderBuffer('div'); - ``` - - @class RenderBuffer - @namespace Ember - @constructor - @param {String} tagName tag name (such as 'div' or 'p') used for the buffer -*/ -Ember.RenderBuffer = function(tagName) { - return new Ember._RenderBuffer(tagName); -}; - -Ember._RenderBuffer = function(tagName) { - this.tagNames = [tagName || null]; - this.buffer = ""; -}; - -Ember._RenderBuffer.prototype = { - - // The root view's element - _element: null, - - _hasElement: true, - - /** - An internal set used to de-dupe class names when `addClass()` is - used. After each call to `addClass()`, the `classes` property - will be updated. - - @private - @property elementClasses - @type Array - @default [] - */ - elementClasses: null, - - /** - Array of class names which will be applied in the class attribute. - - You can use `setClasses()` to set this property directly. If you - use `addClass()`, it will be maintained for you. - - @property classes - @type Array - @default [] - */ - classes: null, - - /** - The id in of the element, to be applied in the id attribute. - - You should not set this property yourself, rather, you should use - the `id()` method of `Ember.RenderBuffer`. - - @property elementId - @type String - @default null - */ - elementId: null, - - /** - A hash keyed on the name of the attribute and whose value will be - applied to that attribute. For example, if you wanted to apply a - `data-view="Foo.bar"` property to an element, you would set the - elementAttributes hash to `{'data-view':'Foo.bar'}`. - - You should not maintain this hash yourself, rather, you should use - the `attr()` method of `Ember.RenderBuffer`. - - @property elementAttributes - @type Hash - @default {} - */ - elementAttributes: null, - - /** - A hash keyed on the name of the properties and whose value will be - applied to that property. For example, if you wanted to apply a - `checked=true` property to an element, you would set the - elementProperties hash to `{'checked':true}`. - - You should not maintain this hash yourself, rather, you should use - the `prop()` method of `Ember.RenderBuffer`. - - @property elementProperties - @type Hash - @default {} - */ - elementProperties: null, - - /** - The tagname of the element an instance of `Ember.RenderBuffer` represents. - - Usually, this gets set as the first parameter to `Ember.RenderBuffer`. For - example, if you wanted to create a `p` tag, then you would call - - ```javascript - Ember.RenderBuffer('p') - ``` - - @property elementTag - @type String - @default null - */ - elementTag: null, - - /** - A hash keyed on the name of the style attribute and whose value will - be applied to that attribute. For example, if you wanted to apply a - `background-color:black;` style to an element, you would set the - elementStyle hash to `{'background-color':'black'}`. - - You should not maintain this hash yourself, rather, you should use - the `style()` method of `Ember.RenderBuffer`. - - @property elementStyle - @type Hash - @default {} - */ - elementStyle: null, - - /** - Nested `RenderBuffers` will set this to their parent `RenderBuffer` - instance. - - @property parentBuffer - @type Ember._RenderBuffer - */ - parentBuffer: null, - - /** - Adds a string of HTML to the `RenderBuffer`. - - @method push - @param {String} string HTML to push into the buffer - @chainable - */ - push: function(string) { - this.buffer += string; - return this; - }, - - /** - Adds a class to the buffer, which will be rendered to the class attribute. - - @method addClass - @param {String} className Class name to add to the buffer - @chainable - */ - addClass: function(className) { - // lazily create elementClasses - this.elementClasses = (this.elementClasses || new ClassSet()); - this.elementClasses.add(className); - this.classes = this.elementClasses.list; - - return this; - }, - - setClasses: function(classNames) { - this.classes = classNames; - }, - - /** - Sets the elementID to be used for the element. - - @method id - @param {String} id - @chainable - */ - id: function(id) { - this.elementId = id; - return this; - }, - - // duck type attribute functionality like jQuery so a render buffer - // can be used like a jQuery object in attribute binding scenarios. - - /** - Adds an attribute which will be rendered to the element. - - @method attr - @param {String} name The name of the attribute - @param {String} value The value to add to the attribute - @chainable - @return {Ember.RenderBuffer|String} this or the current attribute value - */ - attr: function(name, value) { - var attributes = this.elementAttributes = (this.elementAttributes || {}); - - if (arguments.length === 1) { - return attributes[name]; - } else { - attributes[name] = value; - } - - return this; - }, - - /** - Remove an attribute from the list of attributes to render. - - @method removeAttr - @param {String} name The name of the attribute - @chainable - */ - removeAttr: function(name) { - var attributes = this.elementAttributes; - if (attributes) { delete attributes[name]; } - - return this; - }, - - /** - Adds an property which will be rendered to the element. - - @method prop - @param {String} name The name of the property - @param {String} value The value to add to the property - @chainable - @return {Ember.RenderBuffer|String} this or the current property value - */ - prop: function(name, value) { - var properties = this.elementProperties = (this.elementProperties || {}); - - if (arguments.length === 1) { - return properties[name]; - } else { - properties[name] = value; - } - - return this; - }, - - /** - Remove an property from the list of properties to render. - - @method removeProp - @param {String} name The name of the property - @chainable - */ - removeProp: function(name) { - var properties = this.elementProperties; - if (properties) { delete properties[name]; } - - return this; - }, - - /** - Adds a style to the style attribute which will be rendered to the element. - - @method style - @param {String} name Name of the style - @param {String} value - @chainable - */ - style: function(name, value) { - this.elementStyle = (this.elementStyle || {}); - - this.elementStyle[name] = value; - return this; - }, - - begin: function(tagName) { - this.tagNames.push(tagName || null); - return this; - }, - - pushOpeningTag: function() { - var tagName = this.currentTagName(); - if (!tagName) { return; } - - if (this._hasElement && !this._element && this.buffer.length === 0) { - this._element = this.generateElement(); - return; - } - - var buffer = this.buffer, - id = this.elementId, - classes = this.classes, - attrs = this.elementAttributes, - props = this.elementProperties, - style = this.elementStyle, - attr, prop; - - buffer += '<' + stripTagName(tagName); - - if (id) { - buffer += ' id="' + escapeAttribute(id) + '"'; - this.elementId = null; - } - if (classes) { - buffer += ' class="' + escapeAttribute(classes.join(' ')) + '"'; - this.classes = null; - } - - if (style) { - buffer += ' style="'; - - for (prop in style) { - if (style.hasOwnProperty(prop)) { - buffer += prop + ':' + escapeAttribute(style[prop]) + ';'; - } - } - - buffer += '"'; - - this.elementStyle = null; - } - - if (attrs) { - for (attr in attrs) { - if (attrs.hasOwnProperty(attr)) { - buffer += ' ' + attr + '="' + escapeAttribute(attrs[attr]) + '"'; - } - } - - this.elementAttributes = null; - } - - if (props) { - for (prop in props) { - if (props.hasOwnProperty(prop)) { - var value = props[prop]; - if (value || typeof(value) === 'number') { - if (value === true) { - buffer += ' ' + prop + '="' + prop + '"'; - } else { - buffer += ' ' + prop + '="' + escapeAttribute(props[prop]) + '"'; - } - } - } - } - - this.elementProperties = null; - } - - buffer += '>'; - this.buffer = buffer; - }, - - pushClosingTag: function() { - var tagName = this.tagNames.pop(); - if (tagName) { this.buffer += ''; } - }, - - currentTagName: function() { - return this.tagNames[this.tagNames.length-1]; - }, - - generateElement: function() { - var tagName = this.tagNames.pop(), // pop since we don't need to close - id = this.elementId, - classes = this.classes, - attrs = this.elementAttributes, - props = this.elementProperties, - style = this.elementStyle, - styleBuffer = '', attr, prop, tagString; - - if (attrs && attrs.name && !canSetNameOnInputs) { - // IE allows passing a tag to createElement. See note on `canSetNameOnInputs` above as well. - tagString = '<'+stripTagName(tagName)+' name="'+escapeAttribute(attrs.name)+'">'; - } else { - tagString = tagName; - } - - var element = document.createElement(tagString), - $element = Ember.$(element); - - if (id) { - $element.attr('id', id); - this.elementId = null; - } - if (classes) { - $element.attr('class', classes.join(' ')); - this.classes = null; - } - - if (style) { - for (prop in style) { - if (style.hasOwnProperty(prop)) { - styleBuffer += (prop + ':' + style[prop] + ';'); - } - } - - $element.attr('style', styleBuffer); - - this.elementStyle = null; - } - - if (attrs) { - for (attr in attrs) { - if (attrs.hasOwnProperty(attr)) { - $element.attr(attr, attrs[attr]); - } - } - - this.elementAttributes = null; - } - - if (props) { - for (prop in props) { - if (props.hasOwnProperty(prop)) { - $element.prop(prop, props[prop]); - } - } - - this.elementProperties = null; - } - - return element; - }, - - /** - @method element - @return {DOMElement} The element corresponding to the generated HTML - of this buffer - */ - element: function() { - var html = this.innerString(); - - if (html) { - this._element = Ember.ViewUtils.setInnerHTML(this._element, html); - } - - return this._element; - }, - - /** - Generates the HTML content for this buffer. - - @method string - @return {String} The generated HTML - */ - string: function() { - if (this._hasElement && this._element) { - // Firefox versions < 11 do not have support for element.outerHTML. - var thisElement = this.element(), outerHTML = thisElement.outerHTML; - if (typeof outerHTML === 'undefined') { - return Ember.$('
').append(thisElement).html(); - } - return outerHTML; - } else { - return this.innerString(); - } - }, - - innerString: function() { - return this.buffer; - } -}; - -})(); - - - -(function() { -/** -@module ember -@submodule ember-views -*/ - -var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt; - -/** - `Ember.EventDispatcher` handles delegating browser events to their - corresponding `Ember.Views.` For example, when you click on a view, - `Ember.EventDispatcher` ensures that that view's `mouseDown` method gets - called. - - @class EventDispatcher - @namespace Ember - @private - @extends Ember.Object -*/ -Ember.EventDispatcher = Ember.Object.extend({ - - /** - The set of events names (and associated handler function names) to be setup - and dispatched by the `EventDispatcher`. Custom events can added to this list at setup - time, generally via the `Ember.Application.customEvents` hash. Only override this - default set to prevent the EventDispatcher from listening on some events all together. - - This set will be modified by `setup` to also include any events added at that time. - - @property events - @type Object - */ - events: { - touchstart : 'touchStart', - touchmove : 'touchMove', - touchend : 'touchEnd', - touchcancel : 'touchCancel', - keydown : 'keyDown', - keyup : 'keyUp', - keypress : 'keyPress', - mousedown : 'mouseDown', - mouseup : 'mouseUp', - contextmenu : 'contextMenu', - click : 'click', - dblclick : 'doubleClick', - mousemove : 'mouseMove', - focusin : 'focusIn', - focusout : 'focusOut', - mouseenter : 'mouseEnter', - mouseleave : 'mouseLeave', - submit : 'submit', - input : 'input', - change : 'change', - dragstart : 'dragStart', - drag : 'drag', - dragenter : 'dragEnter', - dragleave : 'dragLeave', - dragover : 'dragOver', - drop : 'drop', - dragend : 'dragEnd' - }, - - /** - The root DOM element to which event listeners should be attached. Event - listeners will be attached to the document unless this is overridden. - - Can be specified as a DOMElement or a selector string. - - The default body is a string since this may be evaluated before document.body - exists in the DOM. - - @private - @property rootElement - @type DOMElement - @default 'body' - */ - rootElement: 'body', - - /** - Sets up event listeners for standard browser events. - - This will be called after the browser sends a `DOMContentReady` event. By - default, it will set up all of the listeners on the document body. If you - would like to register the listeners on a different element, set the event - dispatcher's `root` property. - - @private - @method setup - @param addedEvents {Hash} - */ - setup: function(addedEvents, rootElement) { - var event, events = get(this, 'events'); - - Ember.$.extend(events, addedEvents || {}); - - - if (!Ember.isNone(rootElement)) { - set(this, 'rootElement', rootElement); - } - - rootElement = Ember.$(get(this, 'rootElement')); - - - rootElement.addClass('ember-application'); - - - for (event in events) { - if (events.hasOwnProperty(event)) { - this.setupHandler(rootElement, event, events[event]); - } - } - }, - - /** - Registers an event listener on the document. If the given event is - triggered, the provided event handler will be triggered on the target view. - - If the target view does not implement the event handler, or if the handler - returns `false`, the parent view will be called. The event will continue to - bubble to each successive parent view until it reaches the top. - - For example, to have the `mouseDown` method called on the target view when - a `mousedown` event is received from the browser, do the following: - - ```javascript - setupHandler('mousedown', 'mouseDown'); - ``` - - @private - @method setupHandler - @param {Element} rootElement - @param {String} event the browser-originated event to listen to - @param {String} eventName the name of the method to call on the view - */ - setupHandler: function(rootElement, event, eventName) { - var self = this; - - rootElement.on(event + '.ember', '.ember-view', function(evt, triggeringManager) { - return Ember.handleErrors(function handleViewEvent() { - var view = Ember.View.views[this.id], - result = true, manager = null; - - manager = self._findNearestEventManager(view,eventName); - - if (manager && manager !== triggeringManager) { - result = self._dispatchEvent(manager, evt, eventName, view); - } else if (view) { - result = self._bubbleEvent(view,evt,eventName); - } else { - evt.stopPropagation(); - } - - return result; - }, this); - }); - - rootElement.on(event + '.ember', '[data-ember-action]', function(evt) { - return Ember.handleErrors(function handleActionEvent() { - var actionId = Ember.$(evt.currentTarget).attr('data-ember-action'), - action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; - - // We have to check for action here since in some cases, jQuery will trigger - // an event on `removeChild` (i.e. focusout) after we've already torn down the - // action handlers for the view. - if (action && action.eventName === eventName) { - return action.handler(evt); - } - }, this); - }); - }, - - _findNearestEventManager: function(view, eventName) { - var manager = null; - - while (view) { - manager = get(view, 'eventManager'); - if (manager && manager[eventName]) { break; } - - view = get(view, 'parentView'); - } - - return manager; - }, - - _dispatchEvent: function(object, evt, eventName, view) { - var result = true; - - var handler = object[eventName]; - if (Ember.typeOf(handler) === 'function') { - result = Ember.run(function() { - return handler.call(object, evt, view); - }); - // Do not preventDefault in eventManagers. - evt.stopPropagation(); - } - else { - result = this._bubbleEvent(view, evt, eventName); - } - - return result; - }, - - _bubbleEvent: function(view, evt, eventName) { - return Ember.run(function bubbleEvent() { - return view.handleEvent(eventName, evt); - }); - }, - - destroy: function() { - var rootElement = get(this, 'rootElement'); - Ember.$(rootElement).off('.ember', '**').removeClass('ember-application'); - return this._super(); - } -}); - -})(); - - - -(function() { -/** -@module ember -@submodule ember-views -*/ - -// Add a new named queue for rendering views that happens -// after bindings have synced, and a queue for scheduling actions -// that that should occur after view rendering. -var queues = Ember.run.queues, - indexOf = Ember.ArrayPolyfills.indexOf; -queues.splice(indexOf.call(queues, 'actions')+1, 0, 'render', 'afterRender'); - -})(); - - - -(function() { -/** -@module ember -@submodule ember-views -*/ - -var get = Ember.get, set = Ember.set; - -// Original class declaration and documentation in runtime/lib/controllers/controller.js -// NOTE: It may be possible with YUIDoc to combine docs in two locations - -/** -Additional methods for the ControllerMixin - -@class ControllerMixin -@namespace Ember -*/ -Ember.ControllerMixin.reopen({ - target: null, - namespace: null, - view: null, - container: null, - _childContainers: null, - - init: function() { - this._super(); - set(this, '_childContainers', {}); - }, - - _modelDidChange: Ember.observer('model', function() { - var containers = get(this, '_childContainers'); - - for (var prop in containers) { - if (!containers.hasOwnProperty(prop)) { continue; } - containers[prop].destroy(); - } - - set(this, '_childContainers', {}); - }) -}); - -})(); - - - -(function() { - -})(); - - - -(function() { -var states = {}; - -/** -@module ember -@submodule ember-views -*/ - -var get = Ember.get, set = Ember.set; -var guidFor = Ember.guidFor; -var a_forEach = Ember.EnumerableUtils.forEach; -var a_addObject = Ember.EnumerableUtils.addObject; -var meta = Ember.meta; - -var childViewsProperty = Ember.computed(function() { - var childViews = this._childViews, ret = Ember.A(), view = this; - - a_forEach(childViews, function(view) { - var currentChildViews; - if (view.isVirtual) { - if (currentChildViews = get(view, 'childViews')) { - ret.pushObjects(currentChildViews); - } - } else { - ret.push(view); - } - }); - - ret.replace = function (idx, removedCount, addedViews) { - if (view instanceof Ember.ContainerView) { - return view.replace(idx, removedCount, addedViews); - } - throw new Ember.Error("childViews is immutable"); - }; - - return ret; -}); - - -/** - Global hash of shared templates. This will automatically be populated - by the build tools so that you can store your Handlebars templates in - separate files that get loaded into JavaScript at buildtime. - - @property TEMPLATES - @for Ember - @type Hash -*/ -Ember.TEMPLATES = {}; - -/** - `Ember.CoreView` is an abstract class that exists to give view-like behavior - to both Ember's main view class `Ember.View` and other classes like - `Ember._SimpleMetamorphView` that don't need the fully functionaltiy of - `Ember.View`. - - Unless you have specific needs for `CoreView`, you will use `Ember.View` - in your applications. - - @class CoreView - @namespace Ember - @extends Ember.Object - @uses Ember.Evented - @uses Ember.ActionHandler -*/ - -Ember.CoreView = Ember.Object.extend(Ember.Evented, Ember.ActionHandler, { - isView: true, - - states: states, - - init: function() { - this._super(); - this.transitionTo('preRender'); - }, - - /** - If the view is currently inserted into the DOM of a parent view, this - property will point to the parent of the view. - - @property parentView - @type Ember.View - @default null - */ - parentView: Ember.computed(function() { - var parent = this._parentView; - - if (parent && parent.isVirtual) { - return get(parent, 'parentView'); - } else { - return parent; - } - }).property('_parentView'), - - state: null, - - _parentView: null, - - // return the current view, not including virtual views - concreteView: Ember.computed(function() { - if (!this.isVirtual) { return this; } - else { return get(this, 'parentView'); } - }).property('parentView'), - - instrumentName: 'core_view', - - instrumentDetails: function(hash) { - hash.object = this.toString(); - }, - - /** - Invoked by the view system when this view needs to produce an HTML - representation. This method will create a new render buffer, if needed, - then apply any default attributes, such as class names and visibility. - Finally, the `render()` method is invoked, which is responsible for - doing the bulk of the rendering. - - You should not need to override this method; instead, implement the - `template` property, or if you need more control, override the `render` - method. - - @method renderToBuffer - @param {Ember.RenderBuffer} buffer the render buffer. If no buffer is - passed, a default buffer, using the current view's `tagName`, will - be used. - @private - */ - renderToBuffer: function(parentBuffer, bufferOperation) { - var name = 'render.' + this.instrumentName, - details = {}; - - this.instrumentDetails(details); - - return Ember.instrument(name, details, function instrumentRenderToBuffer() { - return this._renderToBuffer(parentBuffer, bufferOperation); - }, this); - }, - - _renderToBuffer: function(parentBuffer, bufferOperation) { - // If this is the top-most view, start a new buffer. Otherwise, - // create a new buffer relative to the original using the - // provided buffer operation (for example, `insertAfter` will - // insert a new buffer after the "parent buffer"). - var tagName = this.tagName; - - if (tagName === null || tagName === undefined) { - tagName = 'div'; - } - - var buffer = this.buffer = parentBuffer && parentBuffer.begin(tagName) || Ember.RenderBuffer(tagName); - this.transitionTo('inBuffer', false); - - this.beforeRender(buffer); - this.render(buffer); - this.afterRender(buffer); - - return buffer; - }, - - /** - Override the default event firing from `Ember.Evented` to - also call methods with the given name. - - @method trigger - @param name {String} - @private - */ - trigger: function(name) { - this._super.apply(this, arguments); - var method = this[name]; - if (method) { - var args = [], i, l; - for (i = 1, l = arguments.length; i < l; i++) { - args.push(arguments[i]); - } - return method.apply(this, args); - } - }, - - deprecatedSendHandles: function(actionName) { - return !!this[actionName]; - }, - - deprecatedSend: function(actionName) { - var args = [].slice.call(arguments, 1); - this[actionName].apply(this, args); - return; - }, - - has: function(name) { - return Ember.typeOf(this[name]) === 'function' || this._super(name); - }, - - destroy: function() { - var parent = this._parentView; - - if (!this._super()) { return; } - - // destroy the element -- this will avoid each child view destroying - // the element over and over again... - if (!this.removedFromDOM) { this.destroyElement(); } - - // 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.transitionTo('destroying', false); - - return this; - }, - - clearRenderedChildren: Ember.K, - triggerRecursively: Ember.K, - invokeRecursively: Ember.K, - transitionTo: Ember.K, - destroyElement: Ember.K -}); - -var ViewCollection = Ember._ViewCollection = function(initialViews) { - var views = this.views = initialViews || []; - this.length = views.length; -}; - -ViewCollection.prototype = { - length: 0, - - trigger: function(eventName) { - var views = this.views, view; - for (var i = 0, l = views.length; i < l; i++) { - view = views[i]; - if (view.trigger) { view.trigger(eventName); } - } - }, - - triggerRecursively: function(eventName) { - var views = this.views; - for (var i = 0, l = views.length; i < l; i++) { - views[i].triggerRecursively(eventName); - } - }, - - invokeRecursively: function(fn) { - var views = this.views, view; - - for (var i = 0, l = views.length; i < l; i++) { - view = views[i]; - fn(view); - } - }, - - transitionTo: function(state, children) { - var views = this.views; - for (var i = 0, l = views.length; i < l; i++) { - views[i].transitionTo(state, children); - } - }, - - push: function() { - this.length += arguments.length; - var views = this.views; - return views.push.apply(views, arguments); - }, - - objectAt: function(idx) { - return this.views[idx]; - }, - - forEach: function(callback) { - var views = this.views; - return a_forEach(views, callback); - }, - - clear: function() { - this.length = 0; - this.views.length = 0; - } -}; - -var EMPTY_ARRAY = []; - -/** - `Ember.View` is the class in Ember responsible for encapsulating templates of - HTML content, combining templates with data to render as sections of a page's - DOM, and registering and responding to user-initiated events. - - ## HTML Tag - - The default HTML tag name used for a view's DOM representation is `div`. This - can be customized by setting the `tagName` property. The following view - class: - - ```javascript - ParagraphView = Ember.View.extend({ - tagName: 'em' - }); - ``` - - Would result in instances with the following HTML: - - ```html - - ``` - - ## HTML `class` Attribute - - The HTML `class` attribute of a view's tag can be set by providing a - `classNames` property that is set to an array of strings: - - ```javascript - MyView = Ember.View.extend({ - classNames: ['my-class', 'my-other-class'] - }); - ``` - - Will result in view instances with an HTML representation of: - - ```html -
- ``` - - `class` attribute values can also be set by providing a `classNameBindings` - property set to an array of properties names for the view. The return value - of these properties will be added as part of the value for the view's `class` - attribute. These properties can be computed properties: - - ```javascript - MyView = Ember.View.extend({ - classNameBindings: ['propertyA', 'propertyB'], - propertyA: 'from-a', - propertyB: function() { - if (someLogic) { return 'from-b'; } - }.property() - }); - ``` - - Will result in view instances with an HTML representation of: - - ```html -
- ``` - - If the value of a class name binding returns a boolean the property name - itself will be used as the class name if the property is true. The class name - will not be added if the value is `false` or `undefined`. - - ```javascript - MyView = Ember.View.extend({ - classNameBindings: ['hovered'], - hovered: true - }); - ``` - - Will result in view instances with an HTML representation of: - - ```html -
- ``` - - When using boolean class name bindings you can supply a string value other - than the property name for use as the `class` HTML attribute by appending the - preferred value after a ":" character when defining the binding: - - ```javascript - MyView = Ember.View.extend({ - classNameBindings: ['awesome:so-very-cool'], - awesome: true - }); - ``` - - Will result in view instances with an HTML representation of: - - ```html -
- ``` - - Boolean value class name bindings whose property names are in a - camelCase-style format will be converted to a dasherized format: - - ```javascript - MyView = Ember.View.extend({ - classNameBindings: ['isUrgent'], - isUrgent: true - }); - ``` - - Will result in view instances with an HTML representation of: - - ```html -
- ``` - - Class name bindings can also refer to object values that are found by - traversing a path relative to the view itself: - - ```javascript - MyView = Ember.View.extend({ - classNameBindings: ['messages.empty'] - messages: Ember.Object.create({ - empty: true - }) - }); - ``` - - Will result in view instances with an HTML representation of: - - ```html -
- ``` - - If you want to add a class name for a property which evaluates to true and - and a different class name if it evaluates to false, you can pass a binding - like this: - - ```javascript - // Applies 'enabled' class when isEnabled is true and 'disabled' when isEnabled is false - Ember.View.extend({ - classNameBindings: ['isEnabled:enabled:disabled'] - isEnabled: true - }); - ``` - - Will result in view instances with an HTML representation of: - - ```html -
- ``` - - When isEnabled is `false`, the resulting HTML reprensentation looks like - this: - - ```html -
- ``` - - This syntax offers the convenience to add a class if a property is `false`: - - ```javascript - // Applies no class when isEnabled is true and class 'disabled' when isEnabled is false - Ember.View.extend({ - classNameBindings: ['isEnabled::disabled'] - isEnabled: true - }); - ``` - - Will result in view instances with an HTML representation of: - - ```html -
- ``` - - When the `isEnabled` property on the view is set to `false`, it will result - in view instances with an HTML representation of: - - ```html -
- ``` - - Updates to the the value of a class name binding will result in automatic - update of the HTML `class` attribute in the view's rendered HTML - representation. If the value becomes `false` or `undefined` the class name - will be removed. - - Both `classNames` and `classNameBindings` are concatenated properties. See - [Ember.Object](/api/classes/Ember.Object.html) documentation for more - information about concatenated properties. - - ## HTML Attributes - - The HTML attribute section of a view's tag can be set by providing an - `attributeBindings` property set to an array of property names on the view. - The return value of these properties will be used as the value of the view's - HTML associated attribute: - - ```javascript - AnchorView = Ember.View.extend({ - tagName: 'a', - attributeBindings: ['href'], - href: 'http://google.com' - }); - ``` - - Will result in view instances with an HTML representation of: - - ```html - - ``` - - If the return value of an `attributeBindings` monitored property is a boolean - the property will follow HTML's pattern of repeating the attribute's name as - its value: - - ```javascript - MyTextInput = Ember.View.extend({ - tagName: 'input', - attributeBindings: ['disabled'], - disabled: true - }); - ``` - - Will result in view instances with an HTML representation of: - - ```html - - ``` - - `attributeBindings` can refer to computed properties: - - ```javascript - MyTextInput = Ember.View.extend({ - tagName: 'input', - attributeBindings: ['disabled'], - disabled: function() { - if (someLogic) { - return true; - } else { - return false; - } - }.property() - }); - ``` - - Updates to the the property of an attribute binding will result in automatic - update of the HTML attribute in the view's rendered HTML representation. - - `attributeBindings` is a concatenated property. See [Ember.Object](/api/classes/Ember.Object.html) - documentation for more information about concatenated properties. - - ## Templates - - The HTML contents of a view's rendered representation are determined by its - template. Templates can be any function that accepts an optional context - parameter and returns a string of HTML that will be inserted within the - view's tag. Most typically in Ember this function will be a compiled - `Ember.Handlebars` template. - - ```javascript - AView = Ember.View.extend({ - template: Ember.Handlebars.compile('I am the template') - }); - ``` - - Will result in view instances with an HTML representation of: - - ```html -
I am the template
- ``` - - Within an Ember application is more common to define a Handlebars templates as - part of a page: - - ```html - - ``` - - And associate it by name using a view's `templateName` property: - - ```javascript - AView = Ember.View.extend({ - templateName: 'some-template' - }); - ``` - - If you have nested resources, your Handlebars template will look like this: - - ```html - - ``` - - And `templateName` property: - - ```javascript - AView = Ember.View.extend({ - templateName: 'posts/new' - }); - ``` - - Using a value for `templateName` that does not have a Handlebars template - with a matching `data-template-name` attribute 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
- ``` - - ## View Context - - The default context of the compiled template is the view's controller: - - ```javascript - AView = Ember.View.extend({ - template: Ember.Handlebars.compile('Hello {{excitedGreeting}}') - }); - - aController = Ember.Object.create({ - firstName: 'Barry', - excitedGreeting: function() { - return this.get("content.firstName") + "!!!" - }.property() - }); - - aView = AView.create({ - controller: aController, - }); - ``` - - Will result in an HTML representation of: - - ```html -
Hello Barry!!!
- ``` - - A context can also be explicitly supplied through the view's `context` - property. If the view has neither `context` nor `controller` properties, the - `parentView`'s context will be used. - - ## 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 [Ember.Handlebars.helpers.yield](/api/classes/Ember.Handlebars.helpers.html#method_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 precedence 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 - // OuterView 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](/api/classes/Ember.Handlebars.helpers.html#method_action). - - ### Event Names - - All of the event handling approaches described above respond to the same set - of events. The names of the built-in events are listed below. (The hash of - built-in events exists in `Ember.EventDispatcher`.) Additional, custom events - can be registered by using `Ember.Application.customEvents`. - - 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 [Ember.Handlebars.helpers.view](/api/classes/Ember.Handlebars.helpers.html#method_view) - for additional information. - - @class View - @namespace Ember - @extends Ember.CoreView -*/ -Ember.View = Ember.CoreView.extend({ - - concatenatedProperties: ['classNames', 'classNameBindings', 'attributeBindings'], - - /** - @property isView - @type Boolean - @default true - @static - */ - isView: true, - - // .......................................................... - // TEMPLATE SUPPORT - // - - /** - The name of the template to lookup if no template is provided. - - By default `Ember.View` will lookup a template with this name in - `Ember.TEMPLATES` (a shared global object). - - @property templateName - @type String - @default null - */ - templateName: null, - - /** - The name of the layout to lookup if no layout is provided. - - By default `Ember.View` will lookup a template with this name in - `Ember.TEMPLATES` (a shared global object). - - @property layoutName - @type String - @default null - */ - layoutName: null, - - /** - 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) { - var parentView = get(this, '_parentView'); - return parentView ? get(parentView, 'controller') : null; - }).property('_parentView'), - - /** - 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) { - var layoutName = get(this, 'layoutName'), - layout = this.templateForName(layoutName, 'layout'); - - - return layout || get(this, 'defaultLayout'); - }).property('layoutName'), - - _yield: function(context, options) { - var template = get(this, 'template'); - if (template) { template(context, options); } - }, - - templateForName: function(name, type) { - if (!name) { return; } - - // the defaultContainer is deprecated - var container = this.container || (Ember.Container && Ember.Container.defaultContainer); - return container && container.lookup('template:' + name); - }, - - /** - 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's controller. - - @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 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 - @private - */ - _context: Ember.computed(function(key) { - var parentView, controller; - - if (controller = get(this, 'controller')) { - return controller; - } - - parentView = this._parentView; - if (parentView) { - return get(parentView, '_context'); - } - - return null; - }), - - /** - If a value that affects template rendering changes, the view should be - re-rendered to reflect the new value. - - @method _contextDidChange - @private - */ - _contextDidChange: Ember.observer('context', function() { - this.rerender(); - }), - - /** - If `false`, the view will appear hidden in DOM. - - @property isVisible - @type Boolean - @default null - */ - isVisible: true, - - /** - Array of child views. You should never edit this array directly. - Instead, use `appendChild` and `removeFromParent`. - - @property childViews - @type Array - @default [] - @private - */ - childViews: childViewsProperty, - - _childViews: EMPTY_ARRAY, - - // When it's a virtual view, we need to notify the parent that their - // childViews will change. - _childViewsWillChange: Ember.beforeObserver('childViews', function() { - if (this.isVirtual) { - var parentView = get(this, 'parentView'); - if (parentView) { Ember.propertyWillChange(parentView, 'childViews'); } - } - }), - - // When it's a virtual view, we need to notify the parent that their - // childViews did change. - _childViewsDidChange: Ember.observer('childViews', function() { - if (this.isVirtual) { - var parentView = get(this, 'parentView'); - if (parentView) { Ember.propertyDidChange(parentView, '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) { - 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. - - @property 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. - - @function 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`. - - @method 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'); - } - }, - - /** - When the parent view changes, recursively invalidate `controller` - - @method _parentViewDidChange - @private - */ - _parentViewDidChange: Ember.observer('_parentView', function() { - if (this.isDestroying) { return; } - - this.trigger('parentViewDidChange'); - - if (get(this, 'parentView.controller') && !get(this, 'controller')) { - this.notifyPropertyChange('controller'); - } - }), - - _controllerDidChange: Ember.observer('controller', function() { - if (this.isDestroying) { return; } - - this.rerender(); - - this.forEachChildView(function(view) { - view.propertyDidChange('controller'); - }); - }), - - cloneKeywords: function() { - var templateData = get(this, 'templateData'); - - var keywords = templateData ? Ember.copy(templateData.keywords) : {}; - set(keywords, 'view', get(this, 'concreteView')); - set(keywords, '_view', this); - 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 output; - - var data = { - view: this, - buffer: buffer, - isRenderData: true, - keywords: keywords, - insideGroup: get(this, 'templateData.insideGroup') - }; - - // Invoke the template with the provided template context, which - // is the view's controller by default. A hash of data is also passed that provides - // the template with access to the view and render buffer. - - // The template should write directly to the render buffer instead - // of returning a string. - 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); } - } - }, - - /** - 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.currentState.rerender(this); - }, - - 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(); } - } - }, - - /** - 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 - @private - */ - _applyClassNameBindings: function(classBindings) { - var classNames = this.classNames, - elem, newClass, dasherizedClass; - - // 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 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. - a_addObject(classNames, 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; - } - - this.registerObserver(this, parsedPath.path, observer); - // Remove className so when the view is rerendered, - // the className is added based on binding reevaluation - this.one('willClearRender', function() { - if (oldClass) { - classNames.removeObject(oldClass); - oldClass = null; - } - }); - - }, this); - }, - - /** - 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 - @private - */ - _applyAttributeBindings: function(buffer, attributeBindings) { - var attributeValue, elem; - - 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.$(); - - attributeValue = get(this, property); - - Ember.View.applyAttributeBindings(elem, attributeName, attributeValue); - }; - - this.registerObserver(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); - }, - - /** - 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 - @private - */ - _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.currentState.setElement(this, value); - } else { - return this.currentState.getElement(this); - } - }).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. - - @method $ - @param {String} [selector] a jQuery-compatible selector string - @return {jQuery} the jQuery object for the DOM node - */ - $: function(sel) { - return this.currentState.$(this, sel); - }, - - mutateChildViews: function(callback) { - var childViews = this._childViews, - idx = childViews.length, - view; - - while(--idx >= 0) { - view = childViews[idx]; - callback(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(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() { - 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} target A selector, element, HTML string, or jQuery object - @return {Ember.View} received - */ - replaceIn: function(target) { - - this._insertElementLater(function() { - Ember.$(target).empty(); - this.$().appendTo(target); - }); - - return this; - }, - - /** - 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. - - ```javascript - view._insertElementLater(function() { - this.createElement(); - this.$().appendTo('body'); - }); - ``` - - @method _insertElementLater - @param {Function} fn the function that inserts the element into the DOM - @private - */ - _insertElementLater: function(fn) { - this._scheduledInsert = Ember.run.scheduleOnce('render', this, '_insertElement', fn); - }, - - _insertElement: function (fn) { - this._scheduledInsert = null; - this.currentState.insertElement(this, 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. - - If your application uses the `rootElement` property, you must append - the view within that element. Rendering views outside of the `rootElement` - is not supported. - - 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. - if (!this.removedFromDOM) { this.destroyElement(); } - this.invokeRecursively(function(view) { - if (view.clearRenderedChildren) { view.clearRenderedChildren(); } - }); - }, - - elementId: null, - - /** - 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 = "#" + 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 - or after the view was re-rendered. 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, - - /** - Run this callback on the current view (unless includeSelf is false) and recursively on child views. - - @method invokeRecursively - @param fn {Function} - @param includeSelf {Boolean} Includes itself if true. - @private - */ - invokeRecursively: function(fn, includeSelf) { - var childViews = (includeSelf === false) ? this._childViews : [this]; - var currentViews, view, currentChildViews; - - while (childViews.length) { - currentViews = childViews.slice(); - childViews = []; - - for (var i=0, l=currentViews.length; i` 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](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. - - ```javascript - // Applies the 'high' class to the view element - Ember.View.extend({ - 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. - - ```javascript - // Applies the 'is-urgent' class to the view element - Ember.View.extend({ - 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: - - ```javascript - // Applies the 'urgent' class to the view element - Ember.View.extend({ - classNameBindings: ['isUrgent:urgent'] - isUrgent: true - }); - ``` - - This list of properties is inherited from the view's superclasses as well. - - @property classNameBindings - @type Array - @default [] - */ - classNameBindings: EMPTY_ARRAY, - - /** - 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. - - ```javascript - // Applies the type attribute to the element - // with the value "button", like
- Ember.View.extend({ - attributeBindings: ['type'], - type: 'button' - }); - ``` - - If the value of the property is a Boolean, the name of that property is - added as an attribute. - - ```javascript - // Renders something like
- Ember.View.extend({ - attributeBindings: ['enabled'], - enabled: true - }); - ``` - - @property attributeBindings - */ - attributeBindings: EMPTY_ARRAY, - - // ....................................................... - // CORE DISPLAY METHODS - // - - /** - 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 - @private - */ - init: function() { - this.elementId = this.elementId || guidFor(this); - - this._super(); - - // setup child views. be sure to clone the child views array first - this._childViews = this._childViews.slice(); - - this.classNameBindings = Ember.A(this.classNameBindings.slice()); - - this.classNames = Ember.A(this.classNames.slice()); - }, - - appendChild: function(view, options) { - return this.currentState.appendChild(this, 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(parentView, view) { - parentView.removeChild(view); - }); - }, - - destroyAllChildren: function() { - return this.mutateChildViews(function(parentView, 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 = 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 destroy - */ - destroy: function() { - var childViews = this._childViews, - // get parentView before calling super because it'll be destroyed - nonVirtualParentView = get(this, 'parentView'), - viewName = this.viewName, - childLen, i; - - if (!this._super()) { return; } - - childLen = childViews.length; - for (i=childLen-1; i>=0; i--) { - childViews[i].removedFromDOM = true; - } - - // remove from non-virtual parent view if viewName was specified - if (viewName && nonVirtualParentView) { - nonVirtualParentView.set(viewName, null); - } - - childLen = childViews.length; - for (i=childLen-1; i>=0; i--) { - childViews[i].destroy(); - } - - return this; - }, - - /** - 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|String} viewClass - @param {Hash} [attrs] Attributes to add - @return {Ember.View} new instance - */ - createChildView: function(view, attrs) { - if (!view) { - throw new TypeError("createChildViews first argument must exist"); - } - - if (view.isView && view._parentView === this && view.container === this.container) { - return view; - } - - attrs = attrs || {}; - attrs._parentView = this; - - if (Ember.CoreView.detect(view)) { - attrs.templateData = attrs.templateData || get(this, 'templateData'); - - attrs.container = this.container; - 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 if ('string' === typeof view) { - var fullName = 'view:' + view; - var View = this.container.lookupFactory(fullName); - - - attrs.templateData = get(this, 'templateData'); - view = View.create(attrs); - } else { - attrs.container = this.container; - - if (!get(view, 'templateData')) { - attrs.templateData = get(this, 'templateData'); - } - - Ember.setProperties(view, attrs); - - } - - return view; - }, - - becameVisible: Ember.K, - becameHidden: Ember.K, - - /** - When the view's `isVisible` property changes, toggle the visibility - element of the actual DOM element. - - @method _isVisibleDidChange - @private - */ - _isVisibleDidChange: Ember.observer('isVisible', 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(); - } - }), - - _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) { - view.buffer = null; - }); - }, - - transitionTo: function(state, children) { - var priorState = this.currentState, - currentState = this.currentState = this.states[state]; - this.state = state; - - if (priorState && priorState.exit) { priorState.exit(this); } - if (currentState.enter) { currentState.enter(this); } - if (state === 'inDOM') { delete Ember.meta(this).cache.element; } - - if (children !== false) { - this.forEachChildView(function(view) { - view.transitionTo(state); - }); - } - }, - - // ....................................................... - // EVENT HANDLING - // - - /** - Handle events from `Ember.EventDispatcher` - - @method handleEvent - @param eventName {String} - @param evt {Event} - @private - */ - handleEvent: function(eventName, evt) { - return this.currentState.handleEvent(this, eventName, evt); - }, - - registerObserver: function(root, path, target, observer) { - if (!observer && 'function' === typeof target) { - observer = target; - target = null; - } - - if (!root || typeof root !== 'object') { - return; - } - - var view = this, - stateCheckedObserver = function() { - view.currentState.invokeObserver(this, observer); - }, - scheduledObserver = function() { - Ember.run.scheduleOnce('render', this, stateCheckedObserver); - }; - - Ember.addObserver(root, path, target, scheduledObserver); - - this.one('willClearRender', function() { - Ember.removeObserver(root, path, target, scheduledObserver); - }); - } - -}); - -/* - 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. - -function notifyMutationListeners() { - Ember.run.once(Ember.View, 'notifyMutationListeners'); -} - -var DOMManager = { - prepend: function(view, html) { - view.$().prepend(html); - notifyMutationListeners(); - }, - - after: function(view, html) { - view.$().after(html); - notifyMutationListeners(); - }, - - html: function(view, html) { - view.$().html(html); - notifyMutationListeners(); - }, - - replace: function(view) { - var element = get(view, 'element'); - - set(view, 'element', null); - - view._insertElementLater(function() { - Ember.$(element).replaceWith(get(view, 'element')); - notifyMutationListeners(); - }); - }, - - remove: function(view) { - view.$().remove(); - notifyMutationListeners(); - }, - - empty: function(view) { - view.$().empty(); - notifyMutationListeners(); - } -}; - -Ember.View.reopen({ - domManager: DOMManager -}); - -Ember.View.reopenClass({ - - /** - Parse a path and return an object which holds the parsed properties. - - For example a path like "content.isEnabled:enabled:disabled" will return the - following object: - - ```javascript - { - path: "content.isEnabled", - className: "enabled", - falsyClassName: "disabled", - classNames: ":enabled:disabled" - } - ``` - - @method _parsePropertyPath - @static - @private - */ - _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 - }; - }, - - /** - 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 - @private - */ - _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 != null) { - return val; - - // Nothing to display. Return null so that the old class is removed - // but no new class is added. - } else { - return null; - } - } -}); - -var mutation = Ember.Object.extend(Ember.Evented).create(); - -Ember.View.addMutationListener = function(callback) { - mutation.on('change', callback); -}; - -Ember.View.removeMutationListener = function(callback) { - mutation.off('change', callback); -}; - -Ember.View.notifyMutationListeners = function() { - mutation.trigger('change'); -}; - -/** - 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); - - // if this changes, also change the logic in ember-handlebars/lib/helpers/binding.js - if (name !== 'value' && (type === 'string' || (type === 'number' && !isNaN(value)))) { - if (value !== elem.attr(name)) { - elem.attr(name, value); - } - } else if (name === 'value' || type === 'boolean') { - // We can't set properties to undefined or null - if (Ember.isNone(value)) { value = ''; } - - if (!value) { - elem.removeAttr(name); - } - - if (value !== elem.prop(name)) { - // value and booleans should always be properties - elem.prop(name, value); - } - } else if (!value) { - elem.removeAttr(name); - } -}; - -Ember.View.states = states; - -})(); - - - -(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; - }, - - rerender: Ember.K, - invokeObserver: Ember.K -}; - -})(); - - - -(function() { -/** -@module ember -@submodule ember-views -*/ - -var preRender = Ember.View.states.preRender = Ember.create(Ember.View.states._default); - -Ember.merge(preRender, { - // a view leaves the preRender state once its element has been - // created (createElement). - insertElement: function(view, fn) { - view.createElement(); - var viewCollection = view.viewHierarchyCollection(); - - viewCollection.trigger('willInsertElement'); - - fn.call(view); - - // We transition to `inDOM` if the element exists in the DOM - var element = view.get('element'); - while (element = element.parentNode) { - if (element === document) { - viewCollection.transitionTo('inDOM', false); - viewCollection.trigger('didInsertElement'); - } - } - - }, - - renderToBufferIfNeeded: function(view, buffer) { - view.renderToBuffer(buffer); - return true; - }, - - 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; - -var inBuffer = Ember.View.states.inBuffer = Ember.create(Ember.View.states._default); - -Ember.merge(inBuffer, { - $: 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) { - throw new Ember.Error("Something you did caused a view to re-render after it rendered but before it was inserted into the DOM."); - }, - - // 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, _childViews = view._childViews; - - childView = view.createChildView(childView, options); - if (!_childViews.length) { _childViews = view._childViews = _childViews.slice(); } - _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(); - var viewCollection = view._notifyWillDestroyElement(); - viewCollection.transitionTo('preRender', false); - - return view; - }, - - empty: function() { - }, - - renderToBufferIfNeeded: function (view, buffer) { - return false; - }, - - // 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; - }, - - invokeObserver: function(target, observer) { - observer.call(target); - } -}); - - -})(); - - - -(function() { -/** -@module ember -@submodule ember-views -*/ - -var get = Ember.get, set = Ember.set; - -var hasElement = Ember.View.states.hasElement = Ember.create(Ember.View.states._default); - -Ember.merge(hasElement, { - $: 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.triggerRecursively('willClearRender'); - - 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 - } - }, - - invokeObserver: function(target, observer) { - observer.call(target); - } -}); - -var inDOM = Ember.View.states.inDOM = Ember.create(hasElement); - -Ember.merge(inDOM, { - enter: function(view) { - // Register the view for event handling. This hash is used by - // Ember.EventDispatcher to dispatch incoming events. - if (!view.isVirtual) { - Ember.View.views[view.elementId] = view; - } - - view.addBeforeObserver('elementId', function() { - throw new Ember.Error("Changing a view's elementId after creation is not allowed"); - }); - }, - - exit: function(view) { - if (!this.isVirtual) delete Ember.View.views[view.elementId]; - }, - - 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 destroyingError = "You can't call %@ on a view being destroyed", fmt = Ember.String.fmt; - -var destroying = Ember.View.states.destroying = Ember.create(Ember.View.states._default); - -Ember.merge(destroying, { - appendChild: function() { - throw fmt(destroyingError, ['appendChild']); - }, - rerender: function() { - throw fmt(destroyingError, ['rerender']); - }, - destroyElement: function() { - throw fmt(destroyingError, ['destroyElement']); - }, - empty: function() { - throw fmt(destroyingError, ['empty']); - }, - - setElement: function() { - throw fmt(destroyingError, ["set('element', ...)"]); - }, - - renderToBufferIfNeeded: function() { - return false; - }, - - // Since element insertion is scheduled, don't do anything if - // the view has been destroyed between scheduling and execution - insertElement: Ember.K -}); - - -})(); - - - -(function() { -Ember.View.cloneStates = function(from) { - var into = {}; - - into._default = {}; - into.preRender = Ember.create(into._default); - into.destroying = Ember.create(into._default); - into.inBuffer = Ember.create(into._default); - into.hasElement = Ember.create(into._default); - into.inDOM = Ember.create(into.hasElement); - - for (var stateName in from) { - if (!from.hasOwnProperty(stateName)) { continue; } - Ember.merge(into[stateName], from[stateName]); - } - - return into; -}; - -})(); - - - -(function() { -var states = Ember.View.cloneStates(Ember.View.states); - -/** -@module ember -@submodule ember-views -*/ - -var get = Ember.get, set = Ember.set; -var forEach = Ember.EnumerableUtils.forEach; -var ViewCollection = Ember._ViewCollection; - -/** - A `ContainerView` is an `Ember.View` subclass that implements `Ember.MutableArray` - allowing programmatic management of its child views. - - ## 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 container view implements `Ember.MutableArray` allowing programmatic management of its child views. - - To remove a view, pass that view into a `removeObject` call on the container view. - - 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.toArray(); // [aContainer.aView, aContainer.bView] - aContainer.removeObject(aContainer.get('bView')); - aContainer.toArray(); // [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 view. - - 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.toArray(); // [aContainer.aView, aContainer.bView] - aContainer.pushObject(AnotherViewClass.create()); - aContainer.toArray(); // [aContainer.aView, aContainer.bView, ] - ``` - - Will result in the following HTML - - ```html -
-
A
-
B
-
Another view
-
- ``` - - ## 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. - - @class ContainerView - @namespace Ember - @extends Ember.View -*/ -Ember.ContainerView = Ember.View.extend(Ember.MutableArray, { - states: states, - - init: function() { - this._super(); - - var childViews = get(this, 'childViews'); - - // redefine view's childViews property that was obliterated - Ember.defineProperty(this, 'childViews', Ember.View.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); - - var currentView = get(this, 'currentView'); - if (currentView) { - if (!_childViews.length) { _childViews = this._childViews = this._childViews.slice(); } - _childViews.push(this.createChildView(currentView)); - } - }, - - replace: function(idx, removedCount, addedViews) { - var addedCount = addedViews ? get(addedViews, 'length') : 0; - var self = this; - - this.arrayContentWillChange(idx, removedCount, addedCount); - this.childViewsWillChange(this._childViews, idx, removedCount); - - if (addedCount === 0) { - this._childViews.splice(idx, removedCount) ; - } else { - var args = [idx, removedCount].concat(addedViews); - if (addedViews.length && !this._childViews.length) { this._childViews = this._childViews.slice(); } - this._childViews.splice.apply(this._childViews, args); - } - - this.arrayContentDidChange(idx, removedCount, addedCount); - this.childViewsDidChange(this._childViews, idx, removedCount, addedCount); - - return this; - }, - - objectAt: function(idx) { - return this._childViews[idx]; - }, - - length: Ember.computed(function () { - return this._childViews.length; - }).volatile(), - - /** - Instructs each child view to render to the passed render buffer. - - @private - @method render - @param {Ember.RenderBuffer} buffer the buffer to render to - */ - render: function(buffer) { - this.forEachChildView(function(view) { - view.renderToBuffer(buffer); - }); - }, - - instrumentName: 'container', - - /** - 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. - - @private - @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) { - this.propertyWillChange('childViews'); - - if (removed > 0) { - var changedViews = views.slice(start, start+removed); - // transition to preRender before clearing parentView - this.currentState.childViewsWillChange(this, views, start, removed); - this.initializeViews(changedViews, null, null); - } - }, - - removeChild: function(child) { - this.removeObject(child); - return this; - }, - - /** - 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. - - @private - @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) { - if (added > 0) { - var changedViews = views.slice(start, start+added); - this.initializeViews(changedViews, this, get(this, 'templateData')); - this.currentState.childViewsDidChange(this, views, start, added); - } - this.propertyDidChange('childViews'); - }, - - initializeViews: function(views, parentView, templateData) { - forEach(views, function(view) { - set(view, '_parentView', parentView); - - if (!view.container && parentView) { - set(view, 'container', parentView.container); - } - - if (!get(view, 'templateData')) { - set(view, 'templateData', templateData); - } - }); - }, - - currentView: null, - - _currentViewWillChange: Ember.beforeObserver('currentView', function() { - var currentView = get(this, 'currentView'); - if (currentView) { - currentView.destroy(); - } - }), - - _currentViewDidChange: Ember.observer('currentView', function() { - var currentView = get(this, 'currentView'); - if (currentView) { - this.pushObject(currentView); - } - }), - - _ensureChildrenAreInDOM: function () { - this.currentState.ensureChildrenAreInDOM(this); - } -}); - -Ember.merge(states._default, { - childViewsWillChange: Ember.K, - childViewsDidChange: Ember.K, - ensureChildrenAreInDOM: Ember.K -}); - -Ember.merge(states.inBuffer, { - childViewsDidChange: function(parentView, views, start, added) { - throw new Ember.Error('You cannot modify child views while in the inBuffer state'); - } -}); - -Ember.merge(states.hasElement, { - childViewsWillChange: function(view, views, start, removed) { - for (var i=start; 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' - ``` - - ## Programmatic creation of child views - - For cases where additional customization beyond the use of a single - `itemViewClass` or `tagName` matching is required CollectionView's - `createChildView` method can be overidden: - - ```javascript - CustomCollectionView = Ember.CollectionView.extend({ - createChildView: function(viewClass, attrs) { - if (attrs.content.kind == 'album') { - viewClass = App.AlbumView; - } else { - viewClass = App.SongView; - } - return this._super(viewClass, attrs); - } - }); - ``` - - ## 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. - - - @class CollectionView - @namespace Ember - @extends Ember.ContainerView - @since Ember 0.9 -*/ -Ember.CollectionView = Ember.ContainerView.extend({ - - /** - A list of items to be displayed by the `Ember.CollectionView`. - - @property content - @type Ember.Array - @default null - */ - content: null, - - /** - This provides metadata about what kind of empty view class this - collection would like if it is being instantiated from another - system (like Handlebars) - - @private - @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, - - /** - Setup a CollectionView - - @method init - */ - init: function() { - var ret = this._super(); - this._contentDidChange(); - return ret; - }, - - /** - Invoked when the content property is about to change. Notifies observers that the - entire array content will change. - - @private - @method _contentWillChange - */ - _contentWillChange: Ember.beforeObserver('content', function() { - var content = this.get('content'); - - if (content) { content.removeArrayObserver(this); } - var len = content ? get(content, 'length') : 0; - this.arrayWillChange(content, 0, len); - }), - - /** - 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. - - @private - @method _contentDidChange - */ - _contentDidChange: Ember.observer('content', function() { - var content = get(this, 'content'); - - if (content) { - this._assertArrayLike(content); - content.addArrayObserver(this); - } - - var len = content ? get(content, 'length') : 0; - this.arrayDidChange(content, 0, null, len); - }), - - /** - Ensure that the content implements Ember.Array - - @private - @method _assertArrayLike - */ - _assertArrayLike: function(content) { - }, - - /** - Removes the content and content observers. - - @method destroy - */ - destroy: function() { - if (!this._super()) { return; } - - var content = get(this, 'content'); - if (content) { content.removeArrayObserver(this); } - - if (this._createdEmptyView) { - this._createdEmptyView.destroy(); - } - - return this; - }, - - /** - Called when a mutation to the underlying content array will occur. - - This method will remove any views that are no longer in the underlying - content array. - - Invokes whenever the content array itself will change. - - @method arrayWillChange - @param {Array} content the managed collection of objects - @param {Number} start the index at which the changes will occurr - @param {Number} removed number of object to be removed from content - */ - 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 = this._childViews, childView, idx, len; - - len = this._childViews.length; - - var removingAll = removedCount === len; - - if (removingAll) { - this.currentState.empty(this); - this.invokeRecursively(function(view) { - view.removedFromDOM = true; - }, false); - } - - for (idx = start + removedCount - 1; idx >= start; idx--) { - childView = childViews[idx]; - 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} content the managed collection of objects - @param {Number} start the index at which the changes occurred - @param {Number} removed number of object removed from content - @param {Number} added number of object added to content - */ - arrayDidChange: function(content, start, removed, added) { - var addedViews = [], view, item, idx, len, itemViewClass, - emptyView; - - len = content ? get(content, 'length') : 0; - - if (len) { - itemViewClass = get(this, 'itemViewClass'); - - if ('string' === typeof itemViewClass) { - itemViewClass = get(itemViewClass) || itemViewClass; - } - - - for (idx = start; idx < start+added; idx++) { - item = content.objectAt(idx); - - view = this.createChildView(itemViewClass, { - content: item, - contentIndex: idx - }); - - addedViews.push(view); - } - } else { - emptyView = get(this, 'emptyView'); - - if (!emptyView) { return; } - - if ('string' === typeof emptyView) { - emptyView = get(emptyView) || emptyView; - } - - emptyView = this.createChildView(emptyView); - addedViews.push(emptyView); - set(this, 'emptyView', emptyView); - - if (Ember.CoreView.detect(emptyView)) { - this._createdEmptyView = emptyView; - } - } - - this.replace(start, 0, addedViews); - }, - - /** - 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. - - The tag name for the view will be set to the tagName of the viewClass - passed in. - - @method createChildView - @param {Class} viewClass - @param {Hash} [attrs] Attributes to add - @return {Ember.View} new instance - */ - createChildView: function(view, attrs) { - view = this._super(view, attrs); - - var itemTagName = get(view, 'tagName'); - - if (itemTagName === null || itemTagName === undefined) { - itemTagName = Ember.CollectionView.CONTAINER_MAP[get(this, 'tagName')]; - set(view, 'tagName', itemTagName); - } - - 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() { -var get = Ember.get, set = Ember.set, isNone = Ember.isNone, - a_slice = Array.prototype.slice; - - -/** -@module ember -@submodule ember-views -*/ - -/** - An `Ember.Component` is a view that is completely - isolated. Property access in its templates go - to the view object and actions are targeted at - the view object. There is no access to the - surrounding context or outer controller; all - contextual information must be passed in. - - The easiest way to create an `Ember.Component` is via - a template. If you name a template - `components/my-foo`, you will be able to use - `{{my-foo}}` in other templates, which will make - an instance of the isolated component. - - ```html - {{app-profile person=currentUser}} - ``` - - ```html - -

{{person.title}}

- -

{{person.signature}}

- ``` - - You can use `yield` inside a template to - include the **contents** of any block attached to - the component. The block will be executed in the - context of the surrounding context or outer controller: - - ```handlebars - {{#app-profile person=currentUser}} -

Admin mode

- {{! Executed in the controllers context. }} - {{/app-profile}} - ``` - - ```handlebars - -

{{person.title}}

- {{! Executed in the components context. }} - {{yield}} {{! block contents }} - ``` - - If you want to customize the component, in order to - handle events or actions, you implement a subclass - of `Ember.Component` named after the name of the - component. Note that `Component` needs to be appended to the name of - your subclass like `AppProfileComponent`. - - For example, you could implement the action - `hello` for the `app-profile` component: - - ```javascript - App.AppProfileComponent = Ember.Component.extend({ - actions: { - hello: function(name) { - console.log("Hello", name); - } - } - }); - ``` - - And then use it in the component's template: - - ```html - - -

{{person.title}}

- {{yield}} - - - ``` - - Components must have a `-` in their name to avoid - conflicts with built-in controls that wrap HTML - elements. This is consistent with the same - requirement in web components. - - @class Component - @namespace Ember - @extends Ember.View -*/ -Ember.Component = Ember.View.extend(Ember.TargetActionSupport, { - init: function() { - this._super(); - set(this, 'context', this); - set(this, 'controller', this); - }, - - defaultLayout: function(options){ - options.data = {view: options._context}; - Ember.Handlebars.helpers['yield'].apply(this, [options]); - }, - - // during render, isolate keywords - cloneKeywords: function() { - return { - view: this, - controller: this - }; - }, - - _yield: function(context, options) { - var view = options.data.view, - parentView = this._parentView, - template = get(this, 'template'); - - if (template) { - - view.appendChild(Ember.View, { - isVirtual: true, - tagName: '', - _contextView: parentView, - template: template, - context: get(parentView, 'context'), - controller: get(parentView, 'controller'), - templateData: { keywords: parentView.cloneKeywords() } - }); - } - }, - - /** - If the component is currently inserted into the DOM of a parent view, this - property will point to the controller of the parent view. - - @property targetObject - @type Ember.Controller - @default null - */ - targetObject: Ember.computed(function(key) { - var parentView = get(this, '_parentView'); - return parentView ? get(parentView, 'controller') : null; - }).property('_parentView'), - - /** - Triggers a named action on the controller context where the component is used if - this controller has registered for notifications of the action. - - For example a component for playing or pausing music may translate click events - into action notifications of "play" or "stop" depending on some internal state - of the component: - - - ```javascript - App.PlayButtonComponent = Ember.Component.extend({ - click: function(){ - if (this.get('isPlaying')) { - this.triggerAction('play'); - } else { - this.triggerAction('stop'); - } - } - }); - ``` - - When used inside a template these component actions are configured to - trigger actions in the outer application context: - - ```handlebars - {{! application.hbs }} - {{play-button play="musicStarted" stop="musicStopped"}} - ``` - - When the component receives a browser `click` event it translate this - interaction into application-specific semantics ("play" or "stop") and - triggers the specified action name on the controller for the template - where the component is used: - - - ```javascript - App.ApplicationController = Ember.Controller.extend({ - actions: { - musicStarted: function(){ - // called when the play button is clicked - // and the music started playing - }, - musicStopped: function(){ - // called when the play button is clicked - // and the music stopped playing - } - } - }); - ``` - - If no action name is passed to `sendAction` a default name of "action" - is assumed. - - ```javascript - App.NextButtonComponent = Ember.Component.extend({ - click: function(){ - this.sendAction(); - } - }); - ``` - - ```handlebars - {{! application.hbs }} - {{next-button action="playNextSongInAlbum"}} - ``` - - ```javascript - App.ApplicationController = Ember.Controller.extend({ - actions: { - playNextSongInAlbum: function(){ - ... - } - } - }); - ``` - - @method sendAction - @param [action] {String} the action to trigger - @param [context] {*} a context to send with the action - */ - sendAction: function(action) { - var actionName, - contexts = a_slice.call(arguments, 1); - - // Send the default action - if (action === undefined) { - actionName = get(this, 'action'); - } else { - actionName = get(this, action); - } - - // If no action name for that action could be found, just abort. - if (actionName === undefined) { return; } - - this.triggerAction({ - action: actionName, - actionContext: contexts - }); - } -}); - -})(); - - - -(function() { - -})(); - - - -(function() { -/** -`Ember.ViewTargetActionSupport` is a mixin that can be included in a -view class to add a `triggerAction` method with semantics similar to -the Handlebars `{{action}}` helper. It provides intelligent defaults -for the action's target: the view's controller; and the context that is -sent with the action: the view's context. - -Note: In normal Ember usage, the `{{action}}` helper is usually the best -choice. This mixin is most often useful when you are doing more complex -event handling in custom View subclasses. - -For example: - -```javascript -App.SaveButtonView = Ember.View.extend(Ember.ViewTargetActionSupport, { - action: 'save', - click: function() { - this.triggerAction(); // Sends the `save` action, along with the current context - // to the current controller - } -}); -``` - -The `action` can be provided as properties of an optional object argument -to `triggerAction` as well. - -```javascript -App.SaveButtonView = Ember.View.extend(Ember.ViewTargetActionSupport, { - click: function() { - this.triggerAction({ - action: 'save' - }); // Sends the `save` action, along with the current context - // to the current controller - } -}); -``` - -@class ViewTargetActionSupport -@namespace Ember -@extends Ember.TargetActionSupport -*/ -Ember.ViewTargetActionSupport = Ember.Mixin.create(Ember.TargetActionSupport, { - /** - @property target - */ - target: Ember.computed.alias('controller'), - /** - @property actionContext - */ - actionContext: Ember.computed.alias('context') -}); - -})(); - - - -(function() { - -})(); - - - -(function() { -/** -Ember Views - -@module ember -@submodule ember-views -@requires ember-runtime -@main ember-views -*/ - -})(); - -(function() { -define("metamorph", - [], - function() { - "use strict"; - // ========================================================================== - // Project: metamorph - // Copyright: ©2014 Tilde, Inc. All rights reserved. - // ========================================================================== - - var K = function() {}, - guid = 0, - disableRange = (function(){ - if ('undefined' !== typeof MetamorphENV) { - return MetamorphENV.DISABLE_RANGE_API; - } else if ('undefined' !== ENV) { - return ENV.DISABLE_RANGE_API; - } else { - return false; - } - })(), - - // Feature-detect the W3C range API, the extended check is for IE9 which only partially supports ranges - supportsRange = (!disableRange) && document && ('createRange' in document) && (typeof Range !== 'undefined') && Range.prototype.createContextualFragment, - - // Internet Explorer prior to 9 does not allow setting innerHTML if the first element - // is a "zero-scope" element. This problem can be worked around by making - // the first node an invisible text node. We, like Modernizr, use ­ - needsShy = document && (function() { - var testEl = document.createElement('div'); - testEl.innerHTML = "
"; - testEl.firstChild.innerHTML = ""; - return testEl.firstChild.innerHTML === ''; - })(), - - - // IE 8 (and likely earlier) likes to move whitespace preceeding - // a script tag to appear after it. This means that we can - // accidentally remove whitespace when updating a morph. - movesWhitespace = document && (function() { - var testEl = document.createElement('div'); - testEl.innerHTML = "Test: Value"; - return testEl.childNodes[0].nodeValue === 'Test:' && - testEl.childNodes[2].nodeValue === ' Value'; - })(); - - // Constructor that supports either Metamorph('foo') or new - // Metamorph('foo'); - // - // Takes a string of HTML as the argument. - - var Metamorph = function(html) { - var self; - - if (this instanceof Metamorph) { - self = this; - } else { - self = new K(); - } - - self.innerHTML = html; - var myGuid = 'metamorph-'+(guid++); - self.start = myGuid + '-start'; - self.end = myGuid + '-end'; - - return self; - }; - - K.prototype = Metamorph.prototype; - - var rangeFor, htmlFunc, removeFunc, outerHTMLFunc, appendToFunc, afterFunc, prependFunc, startTagFunc, endTagFunc; - - outerHTMLFunc = function() { - return this.startTag() + this.innerHTML + this.endTag(); - }; - - startTagFunc = function() { - /* - * We replace chevron by its hex code in order to prevent escaping problems. - * Check this thread for more explaination: - * http://stackoverflow.com/questions/8231048/why-use-x3c-instead-of-when-generating-html-from-javascript - */ - return "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); - - if (outerToo) { - start.parentNode.removeChild(start); - } - - // 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()); - var nextSibling; - - 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."); - } - }; - - return Metamorph; - }); - -})(); - -(function() { -/** -@module ember -@submodule ember-handlebars-compiler -*/ - -// Eliminate dependency on any Ember to simplify precompilation workflow -var objectCreate = Object.create || function(parent) { - function F() {} - F.prototype = parent; - return new F(); -}; - -var Handlebars = (Ember.imports && Ember.imports.Handlebars) || (this && this.Handlebars); -if (!Handlebars && typeof require === 'function') { - Handlebars = require('handlebars'); -} - - - -/** - 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); - -/** - Register a bound helper or custom view helper. - - ## Simple bound helper example - - ```javascript - Ember.Handlebars.helper('capitalize', function(value) { - return value.toUpperCase(); - }); - ``` - - The above bound helper can be used inside of templates as follows: - - ```handlebars - {{capitalize name}} - ``` - - In this case, when the `name` property of the template's context changes, - the rendered value of the helper will update to reflect this change. - - For more examples of bound helpers, see documentation for - `Ember.Handlebars.registerBoundHelper`. - - ## Custom view helper example - - Assuming a view subclass named `App.CalendarView` were defined, a helper - for rendering instances of this view could be registered as follows: - - ```javascript - Ember.Handlebars.helper('calendar', App.CalendarView): - ``` - - The above bound helper can be used inside of templates as follows: - - ```handlebars - {{calendar}} - ``` - - Which is functionally equivalent to: - - ```handlebars - {{view App.CalendarView}} - ``` - - Options in the helper will be passed to the view in exactly the same - manner as with the `view` helper. - - @method helper - @for Ember.Handlebars - @param {String} name - @param {Function|Ember.View} function or view class constructor - @param {String} dependentKeys* -*/ -Ember.Handlebars.helper = function(name, value) { - - if (Ember.View.detect(value)) { - Ember.Handlebars.registerHelper(name, Ember.Handlebars.makeViewHelper(value)); - } else { - Ember.Handlebars.registerBoundHelper.apply(null, arguments); - } -}; - -/** - Returns a helper function that renders the provided ViewClass. - - Used internally by Ember.Handlebars.helper and other methods - involving helper/component registration. - - @private - @method helper - @for Ember.Handlebars - @param {Function} ViewClass view class constructor -*/ -Ember.Handlebars.makeViewHelper = function(ViewClass) { - return function(options) { - return Ember.Handlebars.helpers.view.call(this, ViewClass, options); - }; -}; - -/** -@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 "''"; -}; - -/** - 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. - - @private - @method appendToBuffer - @param string {String} -*/ -Ember.Handlebars.JavaScriptCompiler.prototype.appendToBuffer = function(string) { - return "data.buffer.push("+string+");"; -}; - -// Hacks ahead: -// Handlebars presently has a bug where the `blockHelperMissing` hook -// doesn't get passed the name of the missing helper name, but rather -// gets passed the value of that missing helper evaluated on the current -// context, which is most likely `undefined` and totally useless. -// -// So we alter the compiled template function to pass the name of the helper -// instead, as expected. -// -// This can go away once the following is closed: -// https://github.com/wycats/handlebars.js/issues/634 - -var DOT_LOOKUP_REGEX = /helpers\.(.*?)\)/, - BRACKET_STRING_LOOKUP_REGEX = /helpers\['(.*?)'/, - INVOCATION_SPLITTING_REGEX = /(.*blockHelperMissing\.call\(.*)(stack[0-9]+)(,.*)/; - -Ember.Handlebars.JavaScriptCompiler.stringifyLastBlockHelperMissingInvocation = function(source) { - var helperInvocation = source[source.length - 1], - helperName = (DOT_LOOKUP_REGEX.exec(helperInvocation) || BRACKET_STRING_LOOKUP_REGEX.exec(helperInvocation))[1], - matches = INVOCATION_SPLITTING_REGEX.exec(helperInvocation); - - source[source.length - 1] = matches[1] + "'" + helperName + "'" + matches[3]; -} -var stringifyBlockHelperMissing = Ember.Handlebars.JavaScriptCompiler.stringifyLastBlockHelperMissingInvocation; - -var originalBlockValue = Ember.Handlebars.JavaScriptCompiler.prototype.blockValue; -Ember.Handlebars.JavaScriptCompiler.prototype.blockValue = function() { - originalBlockValue.apply(this, arguments); - stringifyBlockHelperMissing(this.source); -}; - -var originalAmbiguousBlockValue = Ember.Handlebars.JavaScriptCompiler.prototype.ambiguousBlockValue; -Ember.Handlebars.JavaScriptCompiler.prototype.ambiguousBlockValue = function() { - originalAmbiguousBlockValue.apply(this, arguments); - stringifyBlockHelperMissing(this.source); -}; - -var prefix = "ember" + (+new Date()), incr = 1; - -/** - 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. - - @private - @method mustache - @for Ember.Handlebars.Compiler - @param mustache -*/ -Ember.Handlebars.Compiler.prototype.mustache = function(mustache) { - if (mustache.isHelper && mustache.id.string === 'control') { - mustache.hash = mustache.hash || new Handlebars.AST.HashNode([]); - mustache.hash.pairs.push(["controlID", new Handlebars.AST.StringNode(prefix + incr++)]); - } else if (mustache.params.length || mustache.hash) { - // no changes required - } else { - var id = new Handlebars.AST.IdNode([{ part: '_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, - 'bind-attr': 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); - - var template = Ember.Handlebars.template(templateSpec); - template.isMethod = false; //Make sure we don't wrap templates with ._super - - return template; - }; -} - - -})(); - -(function() { -var slice = Array.prototype.slice, - originalTemplate = Ember.Handlebars.template; - -/** - If a path starts with a reserved keyword, returns the root - that should be used. - - @private - @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 get - @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 -*/ -var handlebarsGet = Ember.Handlebars.get = function(root, path, options) { - var data = options && options.data, - normalizedPath = normalizePath(root, path, data), - value; - - - root = normalizedPath.root; - path = normalizedPath.path; - - value = Ember.get(root, path); - - if (value === undefined && root !== Ember.lookup && Ember.isGlobalPath(path)) { - value = Ember.get(Ember.lookup, path); - } - - - return value; -}; - -/** - This method uses `Ember.Handlebars.get` to lookup a value, then ensures - that the value is escaped properly. - - If `unescaped` is a truthy value then the escaping will not be performed. - - @method getEscaped - @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.getEscaped = function(root, path, options) { - var result = handlebarsGet(root, path, options); - - if (result === null || result === undefined) { - result = ""; - } else if (!(result instanceof Handlebars.SafeString)) { - result = String(result); - } - if (!options.hash.unescaped){ - result = Handlebars.Utils.escapeExpression(result); - } - - return result; -}; - -Ember.Handlebars.resolveParams = function(context, params, options) { - var resolvedParams = [], types = options.types, param, type; - - for (var i=0, l=params.length; isomeString
') - ``` - - @method htmlSafe - @for Ember.String - @static - @return {Handlebars.SafeString} a string that will not be html escaped by Handlebars -*/ -Ember.String.htmlSafe = function(str) { - return new Handlebars.SafeString(str); -}; - -var htmlSafe = Ember.String.htmlSafe; - -if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { - - /** - Mark a string as being safe for unescaped output with Handlebars. - - ```javascript - '
someString
'.htmlSafe() - ``` - - See [Ember.String.htmlSafe](/api/classes/Ember.String.html#method_htmlSafe). - - @method htmlSafe - @for String - @return {Handlebars.SafeString} a string that will not be html escaped by Handlebars - */ - String.prototype.htmlSafe = function() { - return htmlSafe(this); - }; -} - -})(); - - - -(function() { -Ember.Handlebars.resolvePaths = function(options) { - var ret = [], - contexts = options.contexts, - roots = options.roots, - data = options.data; - - for (var i=0, l=contexts.length; i{{user.name}} - -
-
{{user.role.label}}
- {{user.role.id}} - -

{{user.role.description}}

-
- ``` - - `{{with}}` can be our best friend in these cases, - instead of writing `user.role.*` over and over, we use `{{#with user.role}}`. - Now the context within the `{{#with}} .. {{/with}}` block is `user.role` so you can do the following: - - ```handlebars -
{{user.name}}
- -
- {{#with user.role}} -
{{label}}
- {{id}} - -

{{description}}

- {{/with}} -
- ``` - - ### `as` operator - - This operator aliases the scope to a new name. It's helpful for semantic clarity and to retain - default scope or to reference from another `{{with}}` block. - - ```handlebars - // posts might not be - {{#with user.posts as blogPosts}} -
- There are {{blogPosts.length}} blog posts written by {{user.name}}. -
- - {{#each post in blogPosts}} -
  • {{post.title}}
  • - {{/each}} - {{/with}} - ``` - - Without the `as` operator, it would be impossible to reference `user.name` in the example above. - - @method with - @for Ember.Handlebars.helpers - @param {Function} context - @param {Hash} options - @return {String} HTML string -*/ -EmberHandlebars.registerHelper('with', function withHelper(context, options) { - if (arguments.length === 4) { - var keywordName, path, rootPath, normalized, contextPath; - - options = arguments[3]; - keywordName = arguments[2]; - path = arguments[0]; - - - var localizedOptions = o_create(options); - localizedOptions.data = o_create(options.data); - localizedOptions.data.keywords = o_create(options.data.keywords || {}); - - if (Ember.isGlobalPath(path)) { - contextPath = 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); - localizedOptions.data.keywords[contextKey] = rootPath; - // if the path is '' ("this"), just bind directly to the current context - contextPath = path ? contextKey + '.' + path : contextKey; - } - - Ember.bind(localizedOptions.data.keywords, keywordName, contextPath); - - return bind.call(this, path, localizedOptions, true, exists); - } else { - return helpers.bind.call(options.contexts[0], context, options); - } -}); - - -/** - See [boundIf](/api/classes/Ember.Handlebars.helpers.html#method_boundIf) - - @method if - @for Ember.Handlebars.helpers - @param {Function} context - @param {Hash} options - @return {String} HTML string -*/ -EmberHandlebars.registerHelper('if', function ifHelper(context, options) { - - 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 unlessHelper(context, options) { - - var fn = options.fn, inverse = options.inverse; - - options.fn = inverse; - options.inverse = fn; - - return helpers.boundIf.call(options.contexts[0], context, options); -}); - -/** - `bind-attr` allows you to create a binding between DOM element attributes and - Ember objects. For example: - - ```handlebars - imageTitle - ``` - - The above handlebars template will fill the ``'s `src` attribute will - the value of the property referenced with `"imageUrl"` and its `alt` - attribute with the value of the property referenced with `"imageTitle"`. - - If the rendering context of this template is the following object: - - ```javascript - { - imageUrl: 'http://lolcats.info/haz-a-funny', - imageTitle: 'A humorous image of a cat' - } - ``` - - The resulting HTML output will be: - - ```html - A humorous image of a cat - ``` - - `bind-attr` cannot redeclare existing DOM element attributes. The use of `src` - in the following `bind-attr` example will be ignored and the hard coded value - of `src="/failwhale.gif"` will take precedence: - - ```handlebars - imageTitle - ``` - - ### `bind-attr` and the `class` attribute - - `bind-attr` supports a special syntax for handling a number of cases unique - to the `class` DOM element attribute. The `class` attribute combines - multiple discrete values into a single attribute as a space-delimited - list of strings. Each string can be: - - * a string return value of an object's property. - * a boolean return value of an object's property - * a hard-coded value - - A string return value works identically to other uses of `bind-attr`. The - return value of the property will become the value of the attribute. For - example, the following view and template: - - ```javascript - AView = Ember.View.extend({ - someProperty: function() { - return "aValue"; - }.property() - }) - ``` - - ```handlebars - - ``` - - A boolean return value will insert a specified class name if the property - returns `true` and remove the class name if the property returns `false`. - - A class name is provided via the syntax - `somePropertyName:class-name-if-true`. - - ```javascript - AView = Ember.View.extend({ - someBool: true - }) - ``` - - ```handlebars - - ``` - - Result in the following rendered output: - - ```html - - ``` - - An additional section of the binding can be provided if you want to - replace the existing class instead of removing it when the boolean - value changes: - - ```handlebars - - ``` - - A hard-coded value can be used by prepending `:` to the desired - class name: `:class-name-to-always-apply`. - - ```handlebars - - ``` - - Results in the following rendered output: - - ```html - - ``` - - All three strategies - string return value, boolean return value, and - hard-coded value – can be combined in a single declaration: - - ```handlebars - - ``` - - @method bind-attr - @for Ember.Handlebars.helpers - @param {Hash} options - @return {String} HTML string -*/ -EmberHandlebars.registerHelper('bind-attr', function bindAttrHelper(options) { - - var attrs = options.hash; - - - 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) { - 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], - normalized; - - - normalized = normalizePath(ctx, path, options.data); - - var value = (path === 'this') ? normalized.root : handlebarsGet(ctx, path, options), - type = Ember.typeOf(value); - - - var observer, invoker; - - observer = function observer() { - var result = handlebarsGet(ctx, path, options); - - - 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(normalized.root, normalized.path, invoker); - return; - } - - Ember.View.applyAttributeBindings(elem, attr, result); - }; - - // 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. - // Note: don't add observer when path is 'this' or path - // is whole keyword e.g. {{#each x in list}} ... {{bind-attr attr="x"}} - if (path !== 'this' && !(normalized.isKeyword && normalized.path === '' )) { - view.registerObserver(normalized.root, normalized.path, observer); - } - - // 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(' ')); -}); - -/** - See `bind-attr` - - @method bindAttr - @for Ember.Handlebars.helpers - @deprecated - @param {Function} context - @param {Hash} options - @return {String} HTML string -*/ -EmberHandlebars.registerHelper('bindAttr', function bindAttrHelper() { - return EmberHandlebars.helpers['bind-attr'].apply(this, arguments); -}); - -/** - 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. - - @private - @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 = handlebarsGet(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(context, 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; - } - } - }; - - if (path !== '' && path !== 'this') { - view.registerObserver(pathRoot, path, observer); - } - - // 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(context, 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 EmberHandlebars = Ember.Handlebars; -var LOWERCASE_A_Z = /^[a-z]/; -var VIEW_PREFIX = /^view\./; - -function makeBindings(thisContext, options) { - var hash = options.hash, - hashType = options.hashTypes; - - for (var prop in hash) { - if (hashType[prop] === 'ID') { - - var value = hash[prop]; - - if (Ember.IS_BINDING.test(prop)) { - } else { - hash[prop + 'Binding'] = value; - hashType[prop + 'Binding'] = 'STRING'; - delete hash[prop]; - delete hashType[prop]; - } - } - } - - if (hash.hasOwnProperty('idBinding')) { - // id can't be bound, so just perform one-time lookup. - hash.id = EmberHandlebars.get(thisContext, hash.idBinding, options); - hashType.id = 'STRING'; - delete hash.idBinding; - delete hashType.idBinding; - } -} - -EmberHandlebars.ViewHelper = Ember.Object.create({ - - propertiesFromHTMLOptions: function(options) { - var hash = options.hash, data = options.data; - var extensions = {}, - classes = hash['class'], - dup = false; - - if (hash.id) { - extensions.elementId = hash.id; - dup = true; - } - - if (hash.tag) { - extensions.tagName = hash.tag; - 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) { - extensions.attributeBindings = null; - dup = true; - } - - if (dup) { - hash = Ember.$.extend({}, hash); - delete hash.id; - delete hash.tag; - 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="_parentView.context.isGreen:green" - var parsedPath = Ember.View._parsePropertyPath(full); - path = this.contextualizeBindingPath(parsedPath.path, data); - if (path) { extensions.classNameBindings[b] = path + parsedPath.classNames; } - } - } - } - - 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' || path === '') { - return '_parentView.context'; - } else { - return '_parentView.context.' + path; - } - }, - - helper: function(thisContext, path, options) { - var data = options.data, - fn = options.fn, - newView; - - makeBindings(thisContext, options); - - if ('string' === typeof path) { - - // TODO: this is a lame conditional, this should likely change - // but something along these lines will likely need to be added - // as deprecation warnings - // - if (options.types[0] === 'STRING' && LOWERCASE_A_Z.test(path) && !VIEW_PREFIX.test(path)) { - newView = data.view.container.lookupFactory('view:' + path); - } else { - newView = EmberHandlebars.get(thisContext, path, options); - } - - } else { - newView = path; - } - - - var viewOptions = this.propertiesFromHTMLOptions(options, thisContext); - var currentView = data.view; - viewOptions.templateData = data; - var newViewProto = newView.proto ? newView.proto() : newView; - - if (fn) { - 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 (!newViewProto.controller && !newViewProto.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 - A span: - {{#view tagName="span"}} - hello. - {{/view}} - ``` - - 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 - {{#view tagName="span" id="a-custom-id"}} - hello. - {{/view}} - ``` - - 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 - {{#view tagName="span" class="a-custom-class"}} - hello. - {{/view}} - ``` - - 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 - {{#view "MyApp.CustomView"}} - hello. - {{/view}} - ``` - - The first argument can also be a relative path accessible from the current - context. - - ```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 "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 - {{view "MyApp.ViewWithATemplateDefined"}} - ``` - - ### `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 viewHelper(path, options) { - - // 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() { -// TODO: Don't require all of this module -/** -@module ember -@submodule ember-handlebars -*/ - -var get = Ember.get, handlebarsGet = Ember.Handlebars.get, fmt = Ember.String.fmt; - -/** - `{{collection}}` is a `Ember.Handlebars` helper for adding instances of - `Ember.CollectionView` to a template. See [Ember.CollectionView](/api/classes/Ember.CollectionView.html) - 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 - {{#collection contentBinding="App.items"}} - Hi {{view.content.name}} - {{/collection}} - ``` - - 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 - {{collection contentBinding="App.items" itemViewClass="App.AnItemView"}} - ``` - - 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 - {{#collection App.MyCustomCollectionClass contentBinding="App.items"}} - Hi {{view.content.name}} - {{/collection}} - ``` - - ### 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 - {{#collection contentBinding="App.items" - itemTagName="p" - itemClassNames="greeting"}} - Howdy {{view.content.name}} - {{/collection}} - ``` - - 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 - @deprecated Use `{{each}}` helper instead. -*/ -Ember.Handlebars.registerHelper('collection', function collectionHelper(path, options) { - - // If no path is provided, treat path param as options. - if (path && path.data && path.data.isRenderData) { - options = path; - path = undefined; - } else { - } - - var fn = options.fn; - var data = options.data; - var inverse = options.inverse; - var view = options.data.view; - - // If passed a path string, convert that into an object. - // Otherwise, just default to the standard class. - var collectionClass; - collectionClass = path ? handlebarsGet(this, path, options) : Ember.CollectionView; - - var hash = options.hash, itemHash = {}, match; - - // Extract item view class if provided else default to the standard class - var collectionPrototype = collectionClass.proto(), - itemViewClass; - - if (hash.itemView) { - var controller = data.keywords.controller; - var container = controller.container; - itemViewClass = container.resolve('view:' + hash.itemView); - } else if (hash.itemViewClass) { - itemViewClass = handlebarsGet(collectionPrototype, hash.itemViewClass, options); - } else { - itemViewClass = collectionPrototype.itemViewClass; - } - - - delete hash.itemViewClass; - delete hash.itemView; - - // 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 && prop !== 'itemController') { - // 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]; - } - } - } - - if (fn) { - itemHash.template = fn; - delete options.fn; - } - - var emptyViewClass; - if (inverse && inverse !== Ember.Handlebars.VM.noop) { - emptyViewClass = get(collectionPrototype, 'emptyViewClass'); - emptyViewClass = emptyViewClass.extend({ - template: inverse, - tagName: itemHash.tagName - }); - } else if (hash.emptyViewClass) { - emptyViewClass = handlebarsGet(this, hash.emptyViewClass, options); - } - if (emptyViewClass) { hash.emptyView = emptyViewClass; } - - if (!hash.keyword) { - itemHash._context = Ember.computed.alias('content'); - } - - 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 handlebarsGet = Ember.Handlebars.get; - -/** - `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}}
    - ``` - - `unbound` can also be used in conjunction with a bound helper to - render it in its unbound form: - - ```handlebars -
    {{unbound helperName somePropertyThatDoesntChange}}
    - ``` - - @method unbound - @for Ember.Handlebars.helpers - @param {String} property - @return {String} HTML string -*/ -Ember.Handlebars.registerHelper('unbound', function unboundHelper(property, fn) { - var options = arguments[arguments.length - 1], helper, context, out; - - if (arguments.length > 2) { - // Unbound helper call. - options.data.isUnbound = true; - helper = Ember.Handlebars.helpers[arguments[0]] || Ember.Handlebars.helpers.helperMissing; - out = helper.apply(this, Array.prototype.slice.call(arguments, 1)); - delete options.data.isUnbound; - return out; - } - - context = (fn.contexts && fn.contexts.length) ? fn.contexts[0] : this; - return handlebarsGet(context, property, fn); -}); - -})(); - - - -(function() { -/*jshint debug:true*/ -/** -@module ember -@submodule ember-handlebars -*/ - -var get = Ember.get, handlebarsGet = Ember.Handlebars.get, normalizePath = Ember.Handlebars.normalizePath; - -/** - `log` allows you to output the value of a variable in the current rendering - context. - - ```handlebars - {{log myVariable}} - ``` - - @method log - @for Ember.Handlebars.helpers - @param {String} property -*/ -Ember.Handlebars.registerHelper('log', function logHelper(property, options) { - var context = (options.contexts && options.contexts.length) ? options.contexts[0] : this, - normalized = normalizePath(context, property, options.data), - pathRoot = normalized.root, - path = normalized.path, - value = (path === 'this') ? pathRoot : handlebarsGet(pathRoot, path, options); - Ember.Logger.log(value); -}); - -/** - Execute the `debugger` statement in the current context. - - ```handlebars - {{debugger}} - ``` - - Before invoking the `debugger` statement, there - are a few helpful variables defined in the - body of this helper that you can inspect while - debugging that describe how and where this - helper was invoked: - - - templateContext: this is most likely a controller - from which this template looks up / displays properties - - typeOfTemplateContext: a string description of - what the templateContext is - - For example, if you're wondering why a value `{{foo}}` - isn't rendering as expected within a template, you - could place a `{{debugger}}` statement, and when - the `debugger;` breakpoint is hit, you can inspect - `templateContext`, determine if it's the object you - expect, and/or evaluate expressions in the console - to perform property lookups on the `templateContext`: - - ``` - > templateContext.get('foo') // -> "" - ``` - - @method debugger - @for Ember.Handlebars.helpers - @param {String} property -*/ -Ember.Handlebars.registerHelper('debugger', function debuggerHelper(options) { - - // These are helpful values you can inspect while debugging. - var templateContext = this; - var typeOfTemplateContext = Ember.inspect(templateContext); - - debugger; -}); - - - -})(); - - - -(function() { -/** -@module ember -@submodule ember-handlebars -*/ - -var get = Ember.get, set = Ember.set; - -Ember.Handlebars.EachView = Ember.CollectionView.extend(Ember._Metamorph, { - init: function() { - var itemController = get(this, 'itemController'); - var binding; - - if (itemController) { - var controller = get(this, 'controller.container').lookupFactory('controller:array').create({ - parentController: get(this, 'controller'), - itemController: itemController, - target: get(this, 'controller'), - _eachView: this - }); - - this.disableContentObservers(function() { - set(this, 'content', controller); - binding = new Ember.Binding('content', '_eachView.dataSource').oneWay(); - binding.connect(controller); - }); - - set(this, '_arrayController', controller); - } else { - this.disableContentObservers(function() { - binding = new Ember.Binding('content', 'dataSource').oneWay(); - binding.connect(this); - }); - } - - return this._super(); - }, - - _assertArrayLike: function(content) { - }, - - disableContentObservers: function(callback) { - Ember.removeBeforeObserver(this, 'content', null, '_contentWillChange'); - Ember.removeObserver(this, 'content', null, '_contentDidChange'); - - callback.call(this); - - Ember.addBeforeObserver(this, 'content', null, '_contentWillChange'); - Ember.addObserver(this, 'content', null, '_contentDidChange'); - }, - - 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'); - var content = get(view, 'content'); - - if (keyword) { - var data = get(view, 'templateData'); - - data = Ember.copy(data); - data.keywords = view.cloneKeywords(); - set(view, 'templateData', data); - - // In this case, we do not bind, because the `content` of - // a #each item cannot change. - data.keywords[keyword] = content; - } - - // If {{#each}} is looping over an array of controllers, - // point each child view at their respective controller. - if (content && get(content, 'isController')) { - set(view, 'controller', content); - } - - return view; - }, - - destroy: function() { - if (!this._super()) { return; } - - var arrayController = get(this, '_arrayController'); - - if (arrayController) { - arrayController.destroy(); - } - - return this; - } -}); - -var GroupedEach = Ember.Handlebars.GroupedEach = function(context, path, options) { - var self = this, - normalized = Ember.Handlebars.normalizePath(context, path, options.data); - - this.context = context; - this.path = path; - this.options = options; - this.template = options.fn; - this.containingView = options.data.view; - this.normalizedRoot = normalized.root; - this.normalizedPath = normalized.path; - this.content = this.lookupContent(); - - this.addContentObservers(); - this.addArrayObservers(); - - this.containingView.on('willClearRender', function() { - self.destroy(); - }); -}; - -GroupedEach.prototype = { - contentWillChange: function() { - this.removeArrayObservers(); - }, - - contentDidChange: function() { - this.content = this.lookupContent(); - this.addArrayObservers(); - this.rerenderContainingView(); - }, - - contentArrayWillChange: Ember.K, - - contentArrayDidChange: function() { - this.rerenderContainingView(); - }, - - lookupContent: function() { - return Ember.Handlebars.get(this.normalizedRoot, this.normalizedPath, this.options); - }, - - addArrayObservers: function() { - if (!this.content) { return; } - - this.content.addArrayObserver(this, { - willChange: 'contentArrayWillChange', - didChange: 'contentArrayDidChange' - }); - }, - - removeArrayObservers: function() { - if (!this.content) { return; } - - this.content.removeArrayObserver(this, { - willChange: 'contentArrayWillChange', - didChange: 'contentArrayDidChange' - }); - }, - - addContentObservers: function() { - Ember.addBeforeObserver(this.normalizedRoot, this.normalizedPath, this, this.contentWillChange); - Ember.addObserver(this.normalizedRoot, this.normalizedPath, this, this.contentDidChange); - }, - - removeContentObservers: function() { - Ember.removeBeforeObserver(this.normalizedRoot, this.normalizedPath, this.contentWillChange); - Ember.removeObserver(this.normalizedRoot, this.normalizedPath, this.contentDidChange); - }, - - render: function() { - if (!this.content) { return; } - - var content = this.content, - contentLength = get(content, 'length'), - data = this.options.data, - template = this.template; - - data.insideEach = true; - for (var i = 0; i < contentLength; i++) { - template(content.objectAt(i), { data: data }); - } - }, - - rerenderContainingView: function() { - var self = this; - Ember.run.scheduleOnce('render', this, function() { - // It's possible it's been destroyed after we enqueued a re-render call. - if (!self.destroyed) { - self.containingView.rerender(); - } - }); - }, - - destroy: function() { - this.removeContentObservers(); - if (this.content) { - this.removeArrayObservers(); - } - this.destroyed = true; - } -}; - -/** - The `{{#each}}` helper loops over elements in a collection, rendering its - block once for each item. It is an extension of the base Handlebars `{{#each}}` - helper: - - ```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}} - ``` - ### {{else}} condition - `{{#each}}` can have a matching `{{else}}`. The contents of this block will render - if the collection is empty. - - ``` - {{#each person in Developers}} - {{person.name}} - {{else}} -

    Sorry, nobody is available for this task.

    - {{/each}} - ``` - ### Specifying a View class for items - If you provide an `itemViewClass` option that references a view class - with its own `template` you can omit the block. - - The following template: - - ```handlebars - {{#view App.MyView }} - {{each view.items itemViewClass="App.AnItemView"}} - {{/view}} - ``` - - 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}}") - }); - ``` - - Will result in the HTML structure below - - ```html -
    -
    Greetings Dave
    -
    Greetings Mary
    -
    Greetings Sara
    -
    - ``` - - If an `itemViewClass` is defined on the helper, and therefore the helper is not - being used as a block, an `emptyViewClass` can also be provided optionally. - The `emptyViewClass` will match the behavior of the `{{else}}` condition - described above. That is, the `emptyViewClass` will render if the collection - is empty. - - ### Representing each item with a Controller. - By default the controller lookup within an `{{#each}}` block will be - the controller of the template where the `{{#each}}` was used. If each - item needs to be presented by a custom controller you can provide a - `itemController` option which references a controller by lookup name. - Each item in the loop will be wrapped in an instance of this controller - and the item itself will be set to the `content` property of that controller. - - This is useful in cases where properties of model objects need transformation - or synthesis for display: - - ```javascript - App.DeveloperController = Ember.ObjectController.extend({ - isAvailableForHire: function() { - return !this.get('content.isEmployed') && this.get('content.isSeekingWork'); - }.property('isEmployed', 'isSeekingWork') - }) - ``` - - ```handlebars - {{#each person in developers itemController="developer"}} - {{person.name}} {{#if person.isAvailableForHire}}Hire me!{{/if}} - {{/each}} - ``` - - Each itemController will receive a reference to the current controller as - a `parentController` property. - - ### (Experimental) Grouped Each - - When used in conjunction with the experimental [group helper](https://github.com/emberjs/group-helper), - you can inform Handlebars to re-render an entire group of items instead of - re-rendering them one at a time (in the event that they are changed en masse - or an item is added/removed). - - ```handlebars - {{#group}} - {{#each people}} - {{firstName}} {{lastName}} - {{/each}} - {{/group}} - ``` - - This can be faster than the normal way that Handlebars re-renders items - in some cases. - - If for some reason you have a group with more than one `#each`, you can make - one of the collections be updated in normal (non-grouped) fashion by setting - the option `groupedRows=true` (counter-intuitive, I know). - - For example, - - ```handlebars - {{dealershipName}} - - {{#group}} - {{#each dealers}} - {{firstName}} {{lastName}} - {{/each}} - - {{#each car in cars groupedRows=true}} - {{car.make}} {{car.model}} {{car.color}} - {{/each}} - {{/group}} - ``` - Any change to `dealershipName` or the `dealers` collection will cause the - entire group to be re-rendered. However, changes to the `cars` collection - will be re-rendered individually (as normal). - - Note that `group` behavior is also disabled by specifying an `itemViewClass`. - - @method each - @for Ember.Handlebars.helpers - @param [name] {String} name for item (used with `in`) - @param [path] {String} path - @param [options] {Object} Handlebars key/value pairs of options - @param [options.itemViewClass] {String} a path to a view class used for each item - @param [options.itemController] {String} name of a controller to be created for each item - @param [options.groupedRows] {boolean} enable normal item-by-item rendering when inside a `#group` helper -*/ -Ember.Handlebars.registerHelper('each', function eachHelper(path, options) { - if (arguments.length === 4) { - - var keywordName = arguments[0]; - - options = arguments[3]; - path = arguments[2]; - if (path === '') { path = "this"; } - - options.hash.keyword = keywordName; - } - - if (arguments.length === 1) { - options = path; - path = 'this'; - } - - options.hash.dataSourceBinding = path; - // Set up emptyView as a metamorph with no tag - //options.hash.emptyViewClass = Ember._MetamorphView; - - if (options.data.insideGroup && !options.hash.groupedRows && !options.hash.itemViewClass) { - new Ember.Handlebars.GroupedEach(this, path, options).render(); - } else { - 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: - - ```html - - ``` - - ```html - - ``` - - ```handlebars - {{#if isUser}} - {{template "user_info"}} - {{else}} - {{template "unlogged_user_info"}} - {{/if}} - ``` - - This helper looks for templates in the global `Ember.TEMPLATES` hash. If you - add ` - ``` - - Take note that `"welcome"` is a string and not an object - reference. - - @method loc - @for Ember.Handlebars.helpers - @param {String} str The string to format -*/ - -Ember.Handlebars.registerHelper('loc', function locHelper(str) { - return Ember.String.loc(str); -}); - -})(); - - - -(function() { - -})(); - - - -(function() { - -})(); - - - -(function() { -/** -@module ember -@submodule ember-handlebars -*/ - -var set = Ember.set, get = Ember.get; - -/** - The internal class used to create text inputs when the `{{input}}` - helper is used with `type` of `checkbox`. - - See [handlebars.helpers.input](/api/classes/Ember.Handlebars.helpers.html#method_input) for usage details. - - ## Direct manipulation of `checked` - - 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](/api/classes/Ember.View.html)'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', 'indeterminate', 'disabled', 'tabindex', 'name'], - - type: "checkbox", - checked: false, - disabled: false, - indeterminate: false, - - init: function() { - this._super(); - this.on("change", this, this._updateElementValue); - }, - - didInsertElement: function() { - this._super(); - this.get('element').indeterminate = !!this.get('indeterminate'); - }, - - _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 - @private -*/ -Ember.TextSupport = Ember.Mixin.create({ - value: "", - - attributeBindings: ['placeholder', 'disabled', 'maxlength', 'tabindex', 'readonly'], - placeholder: null, - disabled: false, - maxlength: null, - - init: function() { - this._super(); - this.on("focusOut", this, this._elementValueDidChange); - this.on("change", this, this._elementValueDidChange); - this.on("paste", this, this._elementValueDidChange); - this.on("cut", this, this._elementValueDidChange); - this.on("input", this, this._elementValueDidChange); - this.on("keyUp", this, this.interpretKeyEvents); - }, - - /** - The action to be sent when the user presses the return key. - - This is similar to the `{{action}}` helper, but is fired when - the user presses the return key when editing a text field, and sends - the value of the field as the context. - - @property action - @type String - @default null - */ - action: null, - - /** - The event that should send the action. - - Options are: - - * `enter`: the user pressed enter - * `keyPress`: the user pressed a key - - @property onEvent - @type String - @default enter - */ - onEvent: 'enter', - - /** - Whether they `keyUp` event that triggers an `action` to be sent continues - propagating to other views. - - By default, when the user presses the return key on their keyboard and - the text field has an `action` set, the action will be sent to the view's - controller and the key event will stop propagating. - - If you would like parent views to receive the `keyUp` event even after an - action has been dispatched, set `bubbles` to true. - - @property bubbles - @type Boolean - @default false - */ - bubbles: false, - - 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()); - }, - - /** - The action to be sent when the user inserts a new line. - - Called by the `Ember.TextSupport` mixin on keyUp if keycode matches 13. - Uses sendAction to send the `enter` action to the controller. - - @method insertNewline - @param {Event} event - */ - insertNewline: function(event) { - sendAction('enter', this, event); - sendAction('insert-newline', this, event); - }, - - /** - Called when the user hits escape. - - Called by the `Ember.TextSupport` mixin on keyUp if keycode matches 27. - Uses sendAction to send the `escape-press` action to the controller. - - @method cancel - @param {Event} event - */ - cancel: function(event) { - sendAction('escape-press', this, event); - }, - - /** - Called when the text area is focused. - - @method focusIn - @param {Event} event - */ - focusIn: function(event) { - sendAction('focus-in', this, event); - }, - - /** - Called when the text area is blurred. - - @method focusOut - @param {Event} event - */ - focusOut: function(event) { - sendAction('focus-out', this, event); - }, - - /** - The action to be sent when the user presses a key. Enabled by setting - the `onEvent` property to `keyPress`. - - Uses sendAction to send the `keyPress` action to the controller. - - @method keyPress - @param {Event} event - */ - keyPress: function(event) { - sendAction('key-press', this, event); - } - -}); - -Ember.TextSupport.KEY_EVENTS = { - 13: 'insertNewline', - 27: 'cancel' -}; - -// In principle, this shouldn't be necessary, but the legacy -// sectionAction semantics for TextField are different from -// the component semantics so this method normalizes them. -function sendAction(eventName, view, event) { - var action = get(view, eventName), - on = get(view, 'onEvent'), - value = get(view, 'value'); - - // back-compat support for keyPress as an event name even though - // it's also a method name that consumes the event (and therefore - // incompatible with sendAction semantics). - if (on === eventName || (on === 'keyPress' && eventName === 'key-press')) { - view.sendAction('action', value); - } - - view.sendAction(eventName, value); - - if (action || on === eventName) { - if(!get(view, 'bubbles')) { - event.stopPropagation(); - } - } -} - -})(); - - - -(function() { -/** -@module ember -@submodule ember-handlebars -*/ - -var get = Ember.get, set = Ember.set; - -/** - - The internal class used to create text inputs when the `{{input}}` - helper is used with `type` of `text`. - - See [Handlebars.helpers.input](/api/classes/Ember.Handlebars.helpers.html#method_input) for usage details. - - ## Layout and LayoutName properties - - Because HTML `input` elements are self closing `layout` and `layoutName` - properties will not be applied. See [Ember.View](/api/classes/Ember.View.html)'s - layout section for more information. - - @class TextField - @namespace Ember - @extends Ember.Component - @uses Ember.TextSupport -*/ -Ember.TextField = Ember.Component.extend(Ember.TextSupport, { - - classNames: ['ember-text-field'], - tagName: "input", - attributeBindings: ['type', 'value', 'size', 'pattern', 'name'], - - /** - 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, - - /** - The `pattern` the pattern attribute of input element. - - @property pattern - @type String - @default null - */ - pattern: 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.get(root, target, { data: data }); - }).property('target'), - - // Defaults to 'button' if tagName is 'input' or 'button' - type: Ember.computed(function(key) { - var tagName = this.tagName; - if (tagName === 'input' || tagName === 'button') { return 'button'; } - }), - - disabled: false, - - // Allow 'a' tags to act like buttons - href: Ember.computed(function() { - return this.tagName === 'a' ? '#' : null; - }), - - 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() { - this._super(); - } -}); - -})(); - - - -(function() { -/** -@module ember -@submodule ember-handlebars -*/ - -var get = Ember.get, set = Ember.set; - -/** - The internal class used to create textarea element when the `{{textarea}}` - helper is used. - - See [handlebars.helpers.textarea](/api/classes/Ember.Handlebars.helpers.html#method_textarea) for usage details. - - ## 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](/api/classes/Ember.View.html)'s - layout section for more information. - - @class TextArea - @namespace Ember - @extends Ember.Component - @uses Ember.TextSupport -*/ -Ember.TextArea = Ember.Component.extend(Ember.TextSupport, { - classNames: ['ember-text-area'], - - tagName: "textarea", - attributeBindings: ['rows', 'cols', 'name'], - rows: null, - cols: null, - - _updateElementValue: Ember.observer('value', 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); - } - }), - - init: function() { - this._super(); - this.on("didInsertElement", this, this._updateElementValue); - } - -}); - -})(); - - - -(function() { -/*jshint eqeqeq:false */ - -/** -@module ember -@submodule ember-handlebars -*/ - -var set = Ember.set, - get = Ember.get, - indexOf = Ember.EnumerableUtils.indexOf, - indexesOf = Ember.EnumerableUtils.indexesOf, - forEach = Ember.EnumerableUtils.forEach, - replace = Ember.EnumerableUtils.replace, - isArray = Ember.isArray, - precompileTemplate = Ember.Handlebars.compile; - -Ember.SelectOption = Ember.View.extend({ - tagName: 'option', - attributeBindings: ['value', 'selected'], - - defaultTemplate: function(context, options) { - options = { data: options.data, hash: {} }; - Ember.Handlebars.helpers.bind.call(context, "view.label", options); - }, - - init: function() { - this.labelPathDidChange(); - this.valuePathDidChange(); - - this._super(); - }, - - selected: Ember.computed(function() { - var content = get(this, 'content'), - selection = get(this, 'parentView.selection'); - if (get(this, 'parentView.multiple')) { - return selection && indexOf(selection, content.valueOf()) > -1; - } else { - // Primitives get passed through bindings as objects... since - // `new Number(4) !== 4`, we use `==` below - return content == selection; - } - }).property('content', 'parentView.selection'), - - labelPathDidChange: Ember.observer('parentView.optionLabelPath', function() { - var labelPath = get(this, 'parentView.optionLabelPath'); - - if (!labelPath) { return; } - - Ember.defineProperty(this, 'label', Ember.computed(function() { - return get(this, labelPath); - }).property(labelPath)); - }), - - valuePathDidChange: Ember.observer('parentView.optionValuePath', function() { - var valuePath = get(this, 'parentView.optionValuePath'); - - if (!valuePath) { return; } - - Ember.defineProperty(this, 'value', Ember.computed(function() { - return get(this, valuePath); - }).property(valuePath)); - }) -}); - -Ember.SelectOptgroup = Ember.CollectionView.extend({ - tagName: 'optgroup', - attributeBindings: ['label'], - - selectionBinding: 'parentView.selection', - multipleBinding: 'parentView.multiple', - optionLabelPathBinding: 'parentView.optionLabelPath', - optionValuePathBinding: 'parentView.optionValuePath', - - itemViewClassBinding: 'parentView.optionView' -}); - -/** - 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 ` - - - ``` - - The `value` attribute of the selected `"); - return buffer; - } - -function program3(depth0,data) { - - var stack1, hashTypes, hashContexts; - hashTypes = {}; - hashContexts = {}; - stack1 = helpers.each.call(depth0, "view.groupedContent", {hash:{},inverse:self.noop,fn:self.program(4, program4, data),contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data}); - if(stack1 || stack1 === 0) { data.buffer.push(stack1); } - else { data.buffer.push(''); } - } -function program4(depth0,data) { - - var hashContexts, hashTypes; - hashContexts = {'content': depth0,'label': depth0}; - hashTypes = {'content': "ID",'label': "ID"}; - data.buffer.push(escapeExpression(helpers.view.call(depth0, "view.groupView", {hash:{ - 'content': ("content"), - 'label': ("label") - },contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data}))); - } - -function program6(depth0,data) { - - var stack1, hashTypes, hashContexts; - hashTypes = {}; - hashContexts = {}; - stack1 = helpers.each.call(depth0, "view.content", {hash:{},inverse:self.noop,fn:self.program(7, program7, data),contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data}); - if(stack1 || stack1 === 0) { data.buffer.push(stack1); } - else { data.buffer.push(''); } - } -function program7(depth0,data) { - - var hashContexts, hashTypes; - hashContexts = {'content': depth0}; - hashTypes = {'content': "ID"}; - data.buffer.push(escapeExpression(helpers.view.call(depth0, "view.optionView", {hash:{ - 'content': ("") - },contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data}))); - } - - hashTypes = {}; - hashContexts = {}; - stack1 = helpers['if'].call(depth0, "view.prompt", {hash:{},inverse:self.noop,fn:self.program(1, program1, data),contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data}); - if(stack1 || stack1 === 0) { data.buffer.push(stack1); } - hashTypes = {}; - hashContexts = {}; - stack1 = helpers['if'].call(depth0, "view.optionGroupPath", {hash:{},inverse:self.program(6, program6, data),fn:self.program(3, program3, data),contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data}); - if(stack1 || stack1 === 0) { data.buffer.push(stack1); } - return buffer; - -}), - attributeBindings: ['multiple', 'disabled', 'tabindex', 'name'], - - /** - The `multiple` attribute of the select element. Indicates whether multiple - options can be selected. - - @property multiple - @type Boolean - @default false - */ - multiple: false, - - /** - The `disabled` attribute of the select element. Indicates whether - the element is disabled from interactions. - - @property disabled - @type Boolean - @default false - */ - disabled: false, - - /** - The list of options. - - If `optionLabelPath` and `optionValuePath` are not overridden, this should - be a list of strings, which will serve simultaneously as labels and values. - - Otherwise, this should be a list of objects. For instance: - - ```javascript - Ember.Select.create({ - content: Ember.A([ - { id: 1, firstName: 'Yehuda' }, - { id: 2, firstName: 'Tom' } - ]), - optionLabelPath: 'content.firstName', - optionValuePath: 'content.id' - }); - ``` - - @property content - @type Array - @default null - */ - content: null, - - /** - When `multiple` is `false`, the element of `content` that is currently - selected, if any. - - When `multiple` is `true`, an array of such elements. - - @property selection - @type Object or Array - @default null - */ - selection: null, - - /** - In single selection mode (when `multiple` is `false`), value can be used to - get the current selection's value or set the selection by it's value. - - It is not currently supported in multiple selection mode. - - @property value - @type String - @default null - */ - value: Ember.computed(function(key, value) { - if (arguments.length === 2) { return value; } - var valuePath = get(this, 'optionValuePath').replace(/^content\.?/, ''); - return valuePath ? get(this, 'selection.' + valuePath) : get(this, 'selection'); - }).property('selection'), - - /** - If given, a top-most dummy option will be rendered to serve as a user - prompt. - - @property prompt - @type String - @default null - */ - prompt: null, - - /** - The path of the option labels. See [content](/api/classes/Ember.Select.html#property_content). - - @property optionLabelPath - @type String - @default 'content' - */ - optionLabelPath: 'content', - - /** - The path of the option values. See [content](/api/classes/Ember.Select.html#property_content). - - @property optionValuePath - @type String - @default 'content' - */ - optionValuePath: 'content', - - /** - The path of the option group. - When this property is used, `content` should be sorted by `optionGroupPath`. - - @property optionGroupPath - @type String - @default null - */ - optionGroupPath: null, - - /** - The view class for optgroup. - - @property groupView - @type Ember.View - @default Ember.SelectOptgroup - */ - groupView: Ember.SelectOptgroup, - - groupedContent: Ember.computed(function() { - var groupPath = get(this, 'optionGroupPath'); - var groupedContent = Ember.A(); - var content = get(this, 'content') || []; - - forEach(content, function(item) { - var label = get(item, groupPath); - - if (get(groupedContent, 'lastObject.label') !== label) { - groupedContent.pushObject({ - label: label, - content: Ember.A() - }); - } - - get(groupedContent, 'lastObject.content').push(item); - }); - - return groupedContent; - }).property('optionGroupPath', 'content.@each'), - - /** - The view class for option. - - @property optionView - @type Ember.View - @default Ember.SelectOption - */ - optionView: Ember.SelectOption, - - _change: function() { - if (get(this, 'multiple')) { - this._changeMultiple(); - } else { - this._changeSingle(); - } - }, - - selectionDidChange: Ember.observer('selection.@each', function() { - var selection = get(this, 'selection'); - if (get(this, 'multiple')) { - if (!isArray(selection)) { - set(this, 'selection', Ember.A([selection])); - return; - } - this._selectionDidChangeMultiple(); - } else { - this._selectionDidChangeSingle(); - } - }), - - valueDidChange: Ember.observer('value', function() { - var content = get(this, 'content'), - value = get(this, 'value'), - valuePath = get(this, 'optionValuePath').replace(/^content\.?/, ''), - selectedValue = (valuePath ? get(this, 'selection.' + valuePath) : get(this, 'selection')), - selection; - - if (value !== selectedValue) { - selection = content ? content.find(function(obj) { - return value === (valuePath ? get(obj, valuePath) : obj); - }) : null; - - this.set('selection', selection); - } - }), - - - _triggerChange: function() { - var selection = get(this, 'selection'); - var value = get(this, 'value'); - - if (!Ember.isNone(selection)) { this.selectionDidChange(); } - if (!Ember.isNone(value)) { this.valueDidChange(); } - - this._change(); - }, - - _changeSingle: function() { - var selectedIndex = this.$()[0].selectedIndex, - content = get(this, 'content'), - prompt = get(this, 'prompt'); - - if (!content || !get(content, 'length')) { return; } - if (prompt && selectedIndex === 0) { set(this, 'selection', null); return; } - - if (prompt) { selectedIndex -= 1; } - set(this, 'selection', content.objectAt(selectedIndex)); - }, - - - _changeMultiple: function() { - var options = this.$('option:selected'), - prompt = get(this, 'prompt'), - offset = prompt ? 1 : 0, - content = get(this, 'content'), - selection = get(this, 'selection'); - - if (!content) { return; } - if (options) { - var selectedIndexes = options.map(function() { - return this.index - offset; - }).toArray(); - var newSelection = content.objectsAt(selectedIndexes); - - if (isArray(selection)) { - replace(selection, 0, get(selection, 'length'), newSelection); - } else { - set(this, 'selection', newSelection); - } - } - }, - - _selectionDidChangeSingle: function() { - var el = this.get('element'); - if (!el) { return; } - - var content = get(this, 'content'), - selection = get(this, 'selection'), - selectionIndex = content ? indexOf(content, selection) : -1, - prompt = get(this, 'prompt'); - - if (prompt) { selectionIndex += 1; } - if (el) { el.selectedIndex = selectionIndex; } - }, - - _selectionDidChangeMultiple: function() { - var content = get(this, 'content'), - selection = get(this, 'selection'), - selectedIndexes = content ? indexesOf(content, selection) : [-1], - prompt = get(this, 'prompt'), - offset = prompt ? 1 : 0, - options = this.$('option'), - adjusted; - - if (options) { - options.each(function() { - adjusted = this.index > -1 ? this.index - offset : -1; - this.selected = indexOf(selectedIndexes, adjusted) > -1; - }); - } - }, - - init: function() { - this._super(); - this.on("didInsertElement", this, this._triggerChange); - this.on("change", this, this._change); - } -}); - -})(); - - - -(function() { -/** -@module ember -@submodule ember-handlebars-compiler -*/ - -/** - - The `{{input}}` helper inserts an HTML `` tag into the template, - with a `type` value of either `text` or `checkbox`. If no `type` is provided, - `text` will be the default value applied. The attributes of `{{input}}` - match those of the native HTML tag as closely as possible for these two types. - - ## Use as text field - An `{{input}}` with no `type` or a `type` of `text` will render an HTML text input. - The following HTML attributes can be set via the helper: - -* `value` -* `size` -* `name` -* `pattern` -* `placeholder` -* `disabled` -* `maxlength` -* `tabindex` - - - When set to a quoted string, these values will be directly applied to the HTML - element. When left unquoted, these values will be bound to a property on the - template's current rendering context (most typically a controller instance). - - ## Unbound: - - ```handlebars - {{input value="http://www.facebook.com"}} - ``` - - - ```html - - ``` - - ## Bound: - - ```javascript - App.ApplicationController = Ember.Controller.extend({ - firstName: "Stanley", - entryNotAllowed: true - }); - ``` - - - ```handlebars - {{input type="text" value=firstName disabled=entryNotAllowed size="50"}} - ``` - - - ```html - - ``` - - ## Extension - - Internally, `{{input type="text"}}` creates an instance of `Ember.TextField`, passing - arguments from the helper to `Ember.TextField`'s `create` method. You can extend the - capablilties of text inputs in your applications by reopening this class. For example, - if you are deploying to browsers where the `required` attribute is used, you - can add this to the `TextField`'s `attributeBindings` property: - - - ```javascript - Ember.TextField.reopen({ - attributeBindings: ['required'] - }); - ``` - - Keep in mind when writing `Ember.TextField` subclasses that `Ember.TextField` - itself extends `Ember.Component`, meaning that it does NOT inherit - the `controller` of the parent view. - - See more about [Ember components](api/classes/Ember.Component.html) - - - ## Use as checkbox - - An `{{input}}` with a `type` of `checkbox` will render an HTML checkbox input. - The following HTML attributes can be set via the helper: - -* `checked` -* `disabled` -* `tabindex` -* `indeterminate` -* `name` - - - When set to a quoted string, these values will be directly applied to the HTML - element. When left unquoted, these values will be bound to a property on the - template's current rendering context (most typically a controller instance). - - ## Unbound: - - ```handlebars - {{input type="checkbox" name="isAdmin"}} - ``` - - ```html - - ``` - - ## Bound: - - ```javascript - App.ApplicationController = Ember.Controller.extend({ - isAdmin: true - }); - ``` - - - ```handlebars - {{input type="checkbox" checked=isAdmin }} - ``` - - - ```html - - ``` - - ## Extension - - Internally, `{{input type="checkbox"}}` creates an instance of `Ember.Checkbox`, passing - arguments from the helper to `Ember.Checkbox`'s `create` method. You can extend the - capablilties of checkbox inputs in your applications by reopening this class. For example, - if you wanted to add a css class to all checkboxes in your application: - - - ```javascript - Ember.Checkbox.reopen({ - classNames: ['my-app-checkbox'] - }); - ``` - - - @method input - @for Ember.Handlebars.helpers - @param {Hash} options -*/ -Ember.Handlebars.registerHelper('input', function(options) { - - var hash = options.hash, - types = options.hashTypes, - inputType = hash.type, - onEvent = hash.on; - - delete hash.type; - delete hash.on; - - if (inputType === 'checkbox') { - return Ember.Handlebars.helpers.view.call(this, Ember.Checkbox, options); - } else { - if (inputType) { hash.type = inputType; } - hash.onEvent = onEvent || 'enter'; - return Ember.Handlebars.helpers.view.call(this, Ember.TextField, options); - } -}); - -/** - `{{textarea}}` inserts a new instance of ` - ``` - - Bound: - - In the following example, the `writtenWords` property on `App.ApplicationController` - will be updated live as the user types 'Lots of text that IS bound' into - the text area of their browser's window. - - ```javascript - App.ApplicationController = Ember.Controller.extend({ - writtenWords: "Lots of text that IS bound" - }); - ``` - - ```handlebars - {{textarea value=writtenWords}} - ``` - - Would result in the following HTML: - - ```html - - ``` - - If you wanted a one way binding between the text area and a div tag - somewhere else on your screen, you could use `Ember.computed.oneWay`: - - ```javascript - App.ApplicationController = Ember.Controller.extend({ - writtenWords: "Lots of text that IS bound", - outputWrittenWords: Ember.computed.oneWay("writtenWords") - }); - ``` - - ```handlebars - {{textarea value=writtenWords}} - -
    - {{outputWrittenWords}} -
    - ``` - - Would result in the following HTML: - - ```html - - - <-- the following div will be updated in real time as you type --> - -
    - Lots of text that IS bound -
    - ``` - - Finally, this example really shows the power and ease of Ember when two - properties are bound to eachother via `Ember.computed.alias`. Type into - either text area box and they'll both stay in sync. Note that - `Ember.computed.alias` costs more in terms of performance, so only use it when - your really binding in both directions: - - ```javascript - App.ApplicationController = Ember.Controller.extend({ - writtenWords: "Lots of text that IS bound", - twoWayWrittenWords: Ember.computed.alias("writtenWords") - }); - ``` - - ```handlebars - {{textarea value=writtenWords}} - {{textarea value=twoWayWrittenWords}} - ``` - - ```html - - - <-- both updated in real time --> - - - ``` - - ## Extension - - Internally, `{{textarea}}` creates an instance of `Ember.TextArea`, passing - arguments from the helper to `Ember.TextArea`'s `create` method. You can - extend the capabilities of text areas in your application by reopening this - class. For example, if you are deploying to browsers where the `required` - attribute is used, you can globally add support for the `required` attribute - on all `{{textarea}}`s' in your app by reopening `Ember.TextArea` or - `Ember.TextSupport` and adding it to the `attributeBindings` concatenated - property: - - ```javascript - Ember.TextArea.reopen({ - attributeBindings: ['required'] - }); - ``` - - Keep in mind when writing `Ember.TextArea` subclasses that `Ember.TextArea` - itself extends `Ember.Component`, meaning that it does NOT inherit - the `controller` of the parent view. - - See more about [Ember components](api/classes/Ember.Component.html) - - @method textarea - @for Ember.Handlebars.helpers - @param {Hash} options -*/ -Ember.Handlebars.registerHelper('textarea', function(options) { - - var hash = options.hash, - types = options.hashTypes; - - return Ember.Handlebars.helpers.view.call(this, Ember.TextArea, options); -}); - -})(); - - - -(function() { -Ember.ComponentLookup = Ember.Object.extend({ - lookupFactory: function(name, container) { - - container = container || this.container; - - var fullName = 'component:' + name, - templateFullName = 'template:components/' + name, - templateRegistered = container && container.has(templateFullName); - - if (templateRegistered) { - container.injection(fullName, 'layout', templateFullName); - } - - var Component = container.lookupFactory(fullName); - - // Only treat as a component if either the component - // or a template has been registered. - if (templateRegistered || Component) { - if (!Component) { - container.register(fullName, Ember.Component); - Component = container.lookupFactory(fullName); - } - return Component; - } - } -}); - -})(); - - - -(function() { -/*globals Handlebars */ -/** -@module ember -@submodule ember-handlebars -*/ - -/** - Find templates stored in the head tag as script tags and make them available - to `Ember.CoreView` in the global `Ember.TEMPLATES` object. This will be run - as as jQuery DOM-ready callback. - - Script tags with `text/x-handlebars` will be compiled - with Ember's Handlebars and are suitable for use as a view's template. - Those with type `text/x-raw-handlebars` will be compiled with regular - Handlebars and are suitable for use in views' computed properties. - - @private - @method bootstrap - @for Ember.Handlebars - @static - @param ctx -*/ -Ember.Handlebars.bootstrap = function(ctx) { - var selectors = 'script[type="text/x-handlebars"], script[type="text/x-raw-handlebars"]'; - - Ember.$(selectors, ctx) - .each(function() { - // Get a reference to the script tag - var script = Ember.$(this); - - var compile = (script.attr('type') === 'text/x-raw-handlebars') ? - Ember.$.proxy(Handlebars.compile, Handlebars) : - Ember.$.proxy(Ember.Handlebars.compile, Ember.Handlebars), - // Get the name of the script, used by Ember.View's templateName property. - // First look for data-template-name attribute, then fall back to its - // id if no name is found. - templateName = script.attr('data-template-name') || script.attr('id') || 'application', - template = compile(script.html()); - - // Check if template of same name already exists - if (Ember.TEMPLATES[templateName] !== undefined) { - throw new Ember.Error('Template named "' + templateName + '" already exists.'); - } - - // For templates which have a name, we save them and then remove them from the DOM - Ember.TEMPLATES[templateName] = template; - - // Remove script tag from DOM - script.remove(); - }); -}; - -function bootstrap() { - Ember.Handlebars.bootstrap( Ember.$(document) ); -} - -function registerComponentLookup(container) { - container.register('component-lookup:main', Ember.ComponentLookup); -} - -/* - We tie this to application.load to ensure that we've at least - attempted to bootstrap at the point that the application is loaded. - - We also tie this to document ready since we're guaranteed that all - the inline templates are present at this point. - - There's no harm to running this twice, since we remove the templates - from the DOM after processing. -*/ - -Ember.onLoad('Ember.Application', function(Application) { - Application.initializer({ - name: 'domTemplates', - initialize: bootstrap - }); - - Application.initializer({ - name: 'registerComponentLookup', - after: 'domTemplates', - initialize: registerComponentLookup - }); -}); - -})(); - - - -(function() { -/** -Ember Handlebars - -@module ember -@submodule ember-handlebars -@requires ember-views -*/ - -Ember.runLoadHooks('Ember.Handlebars', Ember.Handlebars); - -})(); - -(function() { -define("route-recognizer", - [], - function() { - "use strict"; - var specials = [ - '/', '.', '*', '+', '?', '|', - '(', ')', '[', ']', '{', '}', '\\' - ]; - - var escapeRegex = new RegExp('(\\' + specials.join('|\\') + ')', 'g'); - - // A Segment represents a segment in the original route description. - // Each Segment type provides an `eachChar` and `regex` method. - // - // The `eachChar` method invokes the callback with one or more character - // specifications. A character specification consumes one or more input - // characters. - // - // The `regex` method returns a regex fragment for the segment. If the - // segment is a dynamic of star segment, the regex fragment also includes - // a capture. - // - // A character specification contains: - // - // * `validChars`: a String with a list of all valid characters, or - // * `invalidChars`: a String with a list of all invalid characters - // * `repeat`: true if the character specification can repeat - - function StaticSegment(string) { this.string = string; } - StaticSegment.prototype = { - eachChar: function(callback) { - var string = this.string, char; - - for (var i=0, l=string.length; i " + n.nextStates.map(function(s) { return s.debug() }).join(" or ") + " )"; - }).join(", ") - } - END IF **/ - - // This is a somewhat naive strategy, but should work in a lot of cases - // A better strategy would properly resolve /posts/:id/new and /posts/edit/:id - function sortSolutions(states) { - return states.sort(function(a, b) { - if (a.types.stars !== b.types.stars) { return a.types.stars - b.types.stars; } - if (a.types.dynamics !== b.types.dynamics) { return a.types.dynamics - b.types.dynamics; } - if (a.types.statics !== b.types.statics) { return b.types.statics - a.types.statics; } - - return 0; - }); - } - - function recognizeChar(states, char) { - var nextStates = []; - - for (var i=0, l=states.length; i 0) { - currentResult.queryParams = activeQueryParams; - } - result.push(currentResult); - } - - return result; - } - - function addSegment(currentState, segment) { - segment.eachChar(function(char) { - var state; - - currentState = currentState.put(char); - }); - - return currentState; - } - - // The main interface - - var RouteRecognizer = function() { - this.rootState = new State(); - this.names = {}; - }; - - - RouteRecognizer.prototype = { - add: function(routes, options) { - var currentState = this.rootState, regex = "^", - types = { statics: 0, dynamics: 0, stars: 0 }, - handlers = [], allSegments = [], name; - - var isEmpty = true; - - for (var i=0, l=routes.length; i 1 && path.charAt(pathLen - 1) === "/") { - path = path.substr(0, pathLen - 1); - } - - for (i=0, l=path.length; i 0) { - var err = 'You supplied the params '; - err += missingParams.map(function(param) { - return '"' + param + "=" + queryParams[param] + '"'; - }).join(' and '); - - err += ' which are not valid for the "' + handlerName + '" handler or its parents'; - - throw new Error(err); - } - - return this.recognizer.generate(handlerName, params); - }, - - isActive: function(handlerName) { - var partitionedArgs = extractQueryParams(slice.call(arguments, 1)), - contexts = partitionedArgs[0], - queryParams = partitionedArgs[1], - activeQueryParams = {}, - effectiveQueryParams = {}; - - var targetHandlerInfos = this.targetHandlerInfos, - found = false, names, object, handlerInfo, handlerObj; - - if (!targetHandlerInfos) { return false; } - - var recogHandlers = this.recognizer.handlersFor(targetHandlerInfos[targetHandlerInfos.length - 1].name); - for (var i=targetHandlerInfos.length-1; i>=0; i--) { - handlerInfo = targetHandlerInfos[i]; - if (handlerInfo.name === handlerName) { found = true; } - - if (found) { - var recogHandler = recogHandlers[i]; - - merge(activeQueryParams, handlerInfo.queryParams); - if (queryParams !== false) { - merge(effectiveQueryParams, handlerInfo.queryParams); - mergeSomeKeys(effectiveQueryParams, queryParams, recogHandler.queryParams); - } - - if (handlerInfo.isDynamic && contexts.length > 0) { - object = contexts.pop(); - - if (isParam(object)) { - var name = recogHandler.names[0]; - if (!this.currentParams || "" + object !== this.currentParams[name]) { return false; } - } else if (handlerInfo.context !== object) { - return false; - } - } - } - } - - - return contexts.length === 0 && found && queryParamsEqual(activeQueryParams, effectiveQueryParams); - }, - - trigger: function(name) { - var args = slice.call(arguments); - trigger(this, this.currentHandlerInfos, false, args); - }, - - /** - Hook point for logging transition status updates. - - @param {String} message The message to log. - */ - log: null - }; - - /** - @private - - Used internally for both URL and named transition to determine - a shared pivot parent route and other data necessary to perform - a transition. - */ - function getMatchPoint(router, handlers, objects, inputParams, queryParams) { - - var matchPoint = handlers.length, - providedModels = {}, i, - currentHandlerInfos = router.currentHandlerInfos || [], - params = {}, - oldParams = router.currentParams || {}, - activeTransition = router.activeTransition, - handlerParams = {}, - obj; - - objects = slice.call(objects); - merge(params, inputParams); - - for (i = handlers.length - 1; i >= 0; i--) { - var handlerObj = handlers[i], - handlerName = handlerObj.handler, - oldHandlerInfo = currentHandlerInfos[i], - hasChanged = false; - - // Check if handler names have changed. - if (!oldHandlerInfo || oldHandlerInfo.name !== handlerObj.handler) { hasChanged = true; } - - if (handlerObj.isDynamic) { - // URL transition. - - if (obj = getMatchPointObject(objects, handlerName, activeTransition, true, params)) { - hasChanged = true; - providedModels[handlerName] = obj; - } else { - handlerParams[handlerName] = {}; - for (var prop in handlerObj.params) { - if (!handlerObj.params.hasOwnProperty(prop)) { continue; } - var newParam = handlerObj.params[prop]; - if (oldParams[prop] !== newParam) { hasChanged = true; } - handlerParams[handlerName][prop] = params[prop] = newParam; - } - } - } else if (handlerObj.hasOwnProperty('names')) { - // Named transition. - - if (objects.length) { hasChanged = true; } - - if (obj = getMatchPointObject(objects, handlerName, activeTransition, handlerObj.names[0], params)) { - providedModels[handlerName] = obj; - } else { - var names = handlerObj.names; - handlerParams[handlerName] = {}; - for (var j = 0, len = names.length; j < len; ++j) { - var name = names[j]; - handlerParams[handlerName][name] = params[name] = params[name] || oldParams[name]; - } - } - } - - // If there is an old handler, see if query params are the same. If there isn't an old handler, - // hasChanged will already be true here - if(oldHandlerInfo && !queryParamsEqual(oldHandlerInfo.queryParams, handlerObj.queryParams)) { - hasChanged = true; - } - - if (hasChanged) { matchPoint = i; } - } - - if (objects.length > 0) { - throw new Error("More context objects were passed than there are dynamic segments for the route: " + handlers[handlers.length - 1].handler); - } - - var pivotHandlerInfo = currentHandlerInfos[matchPoint - 1], - pivotHandler = pivotHandlerInfo && pivotHandlerInfo.handler; - - return { matchPoint: matchPoint, providedModels: providedModels, params: params, handlerParams: handlerParams, pivotHandler: pivotHandler }; - } - - function getMatchPointObject(objects, handlerName, activeTransition, paramName, params) { - - if (objects.length && paramName) { - - var object = objects.pop(); - - // If provided object is string or number, treat as param. - if (isParam(object)) { - params[paramName] = object.toString(); - } else { - return object; - } - } else if (activeTransition) { - // Use model from previous transition attempt, preferably the resolved one. - return activeTransition.resolvedModels[handlerName] || - (paramName && activeTransition.providedModels[handlerName]); - } - } - - function isParam(object) { - return (typeof object === "string" || object instanceof String || typeof object === "number" || object instanceof Number); - } - - - - /** - @private - - This method takes a handler name and returns a list of query params - that are valid to pass to the handler or its parents - - @param {Router} router - @param {String} handlerName - @return {Array[String]} a list of query parameters - */ - function queryParamsForHandler(router, handlerName) { - var handlers = router.recognizer.handlersFor(handlerName), - queryParams = []; - - for (var i = 0; i < handlers.length; i++) { - queryParams.push.apply(queryParams, handlers[i].queryParams || []); - } - - return queryParams; - } - /** - @private - - This method takes a handler name and a list of contexts and returns - a serialized parameter hash suitable to pass to `recognizer.generate()`. - - @param {Router} router - @param {String} handlerName - @param {Array[Object]} objects - @return {Object} a serialized parameter hash - */ - function paramsForHandler(router, handlerName, objects, queryParams) { - - var handlers = router.recognizer.handlersFor(handlerName), - params = {}, - handlerInfos = generateHandlerInfosWithQueryParams(router, handlers, queryParams), - matchPoint = getMatchPoint(router, handlerInfos, objects).matchPoint, - mergedQueryParams = {}, - object, handlerObj, handler, names, i; - - params.queryParams = {}; - - for (i=0; i= matchPoint) { - object = objects.shift(); - // Otherwise use existing context - } else { - object = handler.context; - } - - // Serialize to generate params - merge(params, serialize(handler, object, names)); - } - if (queryParams !== false) { - mergeSomeKeys(params.queryParams, router.currentQueryParams, handlerObj.queryParams); - mergeSomeKeys(params.queryParams, queryParams, handlerObj.queryParams); - } - } - - if (queryParamsEqual(params.queryParams, {})) { delete params.queryParams; } - return params; - } - - function merge(hash, other) { - for (var prop in other) { - if (other.hasOwnProperty(prop)) { hash[prop] = other[prop]; } - } - } - - function mergeSomeKeys(hash, other, keys) { - if (!other || !keys) { return; } - for(var i = 0; i < keys.length; i++) { - var key = keys[i], value; - if(other.hasOwnProperty(key)) { - value = other[key]; - if(value === null || value === false || typeof value === "undefined") { - delete hash[key]; - } else { - hash[key] = other[key]; - } - } - } - } - - /** - @private - */ - - function generateHandlerInfosWithQueryParams(router, handlers, queryParams) { - var handlerInfos = []; - - for (var i = 0; i < handlers.length; i++) { - var handler = handlers[i], - handlerInfo = { handler: handler.handler, names: handler.names, context: handler.context, isDynamic: handler.isDynamic }, - activeQueryParams = {}; - - if (queryParams !== false) { - mergeSomeKeys(activeQueryParams, router.currentQueryParams, handler.queryParams); - mergeSomeKeys(activeQueryParams, queryParams, handler.queryParams); - } - - if (handler.queryParams && handler.queryParams.length > 0) { - handlerInfo.queryParams = activeQueryParams; - } - - handlerInfos.push(handlerInfo); - } - - return handlerInfos; - } - - /** - @private - */ - function createQueryParamTransition(router, queryParams, isIntermediate) { - var currentHandlers = router.currentHandlerInfos, - currentHandler = currentHandlers[currentHandlers.length - 1], - name = currentHandler.name; - - log(router, "Attempting query param transition"); - - return createNamedTransition(router, [name, queryParams], isIntermediate); - } - - /** - @private - */ - function createNamedTransition(router, args, isIntermediate) { - var partitionedArgs = extractQueryParams(args), - pureArgs = partitionedArgs[0], - queryParams = partitionedArgs[1], - handlers = router.recognizer.handlersFor(pureArgs[0]), - handlerInfos = generateHandlerInfosWithQueryParams(router, handlers, queryParams); - - - log(router, "Attempting transition to " + pureArgs[0]); - - return performTransition(router, - handlerInfos, - slice.call(pureArgs, 1), - router.currentParams, - queryParams, - null, - isIntermediate); - } - - /** - @private - */ - function createURLTransition(router, url, isIntermediate) { - var results = router.recognizer.recognize(url), - currentHandlerInfos = router.currentHandlerInfos, - queryParams = {}, - i, len; - - log(router, "Attempting URL transition to " + url); - - if (results) { - // Make sure this route is actually accessible by URL. - for (i = 0, len = results.length; i < len; ++i) { - - if (router.getHandler(results[i].handler).inaccessibleByURL) { - results = null; - break; - } - } - } - - if (!results) { - return errorTransition(router, new Router.UnrecognizedURLError(url)); - } - - for(i = 0, len = results.length; i < len; i++) { - merge(queryParams, results[i].queryParams); - } - - return performTransition(router, results, [], {}, queryParams, null, isIntermediate); - } - - - /** - @private - - Takes an Array of `HandlerInfo`s, figures out which ones are - exiting, entering, or changing contexts, and calls the - proper handler hooks. - - For example, consider the following tree of handlers. Each handler is - followed by the URL segment it handles. - - ``` - |~index ("/") - | |~posts ("/posts") - | | |-showPost ("/:id") - | | |-newPost ("/new") - | | |-editPost ("/edit") - | |~about ("/about/:id") - ``` - - Consider the following transitions: - - 1. A URL transition to `/posts/1`. - 1. Triggers the `*model` callbacks on the - `index`, `posts`, and `showPost` handlers - 2. Triggers the `enter` callback on the same - 3. Triggers the `setup` callback on the same - 2. A direct transition to `newPost` - 1. Triggers the `exit` callback on `showPost` - 2. Triggers the `enter` callback on `newPost` - 3. Triggers the `setup` callback on `newPost` - 3. A direct transition to `about` with a specified - context object - 1. Triggers the `exit` callback on `newPost` - and `posts` - 2. Triggers the `serialize` callback on `about` - 3. Triggers the `enter` callback on `about` - 4. Triggers the `setup` callback on `about` - - @param {Transition} transition - @param {Array[HandlerInfo]} handlerInfos - */ - function setupContexts(transition, handlerInfos) { - var router = transition.router, - partition = partitionHandlers(router.currentHandlerInfos || [], handlerInfos); - - router.targetHandlerInfos = handlerInfos; - - eachHandler(partition.exited, function(handlerInfo) { - var handler = handlerInfo.handler; - delete handler.context; - if (handler.exit) { handler.exit(); } - }); - - var currentHandlerInfos = partition.unchanged.slice(); - router.currentHandlerInfos = currentHandlerInfos; - - eachHandler(partition.updatedContext, function(handlerInfo) { - handlerEnteredOrUpdated(transition, currentHandlerInfos, handlerInfo, false); - }); - - eachHandler(partition.entered, function(handlerInfo) { - handlerEnteredOrUpdated(transition, currentHandlerInfos, handlerInfo, true); - }); - } - - /** - @private - - Helper method used by setupContexts. Handles errors or redirects - that may happen in enter/setup. - */ - function handlerEnteredOrUpdated(transition, currentHandlerInfos, handlerInfo, enter) { - var handler = handlerInfo.handler, - context = handlerInfo.context; - - try { - if (enter && handler.enter) { handler.enter(); } - checkAbort(transition); - - setContext(handler, context); - setQueryParams(handler, handlerInfo.queryParams); - - if (handler.setup) { handler.setup(context, handlerInfo.queryParams); } - checkAbort(transition); - } catch(e) { - if (!(e instanceof Router.TransitionAborted)) { - // Trigger the `error` event starting from this failed handler. - transition.trigger(true, 'error', e, transition, handler); - } - - // Propagate the error so that the transition promise will reject. - throw e; - } - - currentHandlerInfos.push(handlerInfo); - } - - - /** - @private - - Iterates over an array of `HandlerInfo`s, passing the handler - and context into the callback. - - @param {Array[HandlerInfo]} handlerInfos - @param {Function(Object, Object)} callback - */ - function eachHandler(handlerInfos, callback) { - for (var i=0, l=handlerInfos.length; i=0; i--) { - var handlerInfo = handlerInfos[i], - handler = handlerInfo.handler; - - if (handler.events && handler.events[name]) { - if (handler.events[name].apply(handler, args) === true) { - eventWasHandled = true; - } else { - return; - } - } - } - - if (!eventWasHandled && !ignoreFailure) { - throw new Error("Nothing handled the event '" + name + "'."); - } - } - - function setContext(handler, context) { - handler.context = context; - if (handler.contextDidChange) { handler.contextDidChange(); } - } - - function setQueryParams(handler, queryParams) { - handler.queryParams = queryParams; - if (handler.queryParamsDidChange) { handler.queryParamsDidChange(); } - } - - - /** - @private - - Extracts query params from the end of an array - **/ - - function extractQueryParams(array) { - var len = (array && array.length), head, queryParams; - - if(len && len > 0 && array[len - 1] && array[len - 1].hasOwnProperty('queryParams')) { - queryParams = array[len - 1].queryParams; - head = slice.call(array, 0, len - 1); - return [head, queryParams]; - } else { - return [array, null]; - } - } - - function performIntermediateTransition(router, recogHandlers, matchPointResults) { - - var handlerInfos = generateHandlerInfos(router, recogHandlers); - for (var i = 0; i < handlerInfos.length; ++i) { - var handlerInfo = handlerInfos[i]; - handlerInfo.context = matchPointResults.providedModels[handlerInfo.name]; - } - - var stubbedTransition = { - router: router, - isAborted: false - }; - - setupContexts(stubbedTransition, handlerInfos); - } - - /** - @private - - Creates, begins, and returns a Transition. - */ - function performTransition(router, recogHandlers, providedModelsArray, params, queryParams, data, isIntermediate) { - - var matchPointResults = getMatchPoint(router, recogHandlers, providedModelsArray, params, queryParams), - targetName = recogHandlers[recogHandlers.length - 1].handler, - wasTransitioning = false, - currentHandlerInfos = router.currentHandlerInfos; - - if (isIntermediate) { - return performIntermediateTransition(router, recogHandlers, matchPointResults); - } - - // Check if there's already a transition underway. - if (router.activeTransition) { - if (transitionsIdentical(router.activeTransition, targetName, providedModelsArray, queryParams)) { - return router.activeTransition; - } - router.activeTransition.abort(); - wasTransitioning = true; - } - - var deferred = RSVP.defer(), - transition = new Transition(router, deferred.promise); - - transition.targetName = targetName; - transition.providedModels = matchPointResults.providedModels; - transition.providedModelsArray = providedModelsArray; - transition.params = matchPointResults.params; - transition.data = data || {}; - transition.queryParams = queryParams; - transition.pivotHandler = matchPointResults.pivotHandler; - router.activeTransition = transition; - - var handlerInfos = generateHandlerInfos(router, recogHandlers); - transition.handlerInfos = handlerInfos; - - // Fire 'willTransition' event on current handlers, but don't fire it - // if a transition was already underway. - if (!wasTransitioning) { - trigger(router, currentHandlerInfos, true, ['willTransition', transition]); - } - - log(router, transition.sequence, "Beginning validation for transition to " + transition.targetName); - validateEntry(transition, matchPointResults.matchPoint, matchPointResults.handlerParams) - .then(transitionSuccess, transitionFailure); - - return transition; - - function transitionSuccess() { - checkAbort(transition); - - try { - finalizeTransition(transition, handlerInfos); - - // currentHandlerInfos was updated in finalizeTransition - trigger(router, router.currentHandlerInfos, true, ['didTransition']); - - if (router.didTransition) { - router.didTransition(handlerInfos); - } - - log(router, transition.sequence, "TRANSITION COMPLETE."); - - // Resolve with the final handler. - transition.isActive = false; - deferred.resolve(handlerInfos[handlerInfos.length - 1].handler); - } catch(e) { - deferred.reject(e); - } - - // Don't nullify if another transition is underway (meaning - // there was a transition initiated with enter/setup). - if (!transition.isAborted) { - router.activeTransition = null; - } - } - - function transitionFailure(reason) { - deferred.reject(reason); - } - } - - /** - @private - - Accepts handlers in Recognizer format, either returned from - recognize() or handlersFor(), and returns unified - `HandlerInfo`s. - */ - function generateHandlerInfos(router, recogHandlers) { - var handlerInfos = []; - for (var i = 0, len = recogHandlers.length; i < len; ++i) { - var handlerObj = recogHandlers[i], - isDynamic = handlerObj.isDynamic || (handlerObj.names && handlerObj.names.length); - - var handlerInfo = { - isDynamic: !!isDynamic, - name: handlerObj.handler, - handler: router.getHandler(handlerObj.handler) - }; - if(handlerObj.queryParams) { - handlerInfo.queryParams = handlerObj.queryParams; - } - handlerInfos.push(handlerInfo); - } - return handlerInfos; - } - - /** - @private - */ - function transitionsIdentical(oldTransition, targetName, providedModelsArray, queryParams) { - - if (oldTransition.targetName !== targetName) { return false; } - - var oldModels = oldTransition.providedModelsArray; - if (oldModels.length !== providedModelsArray.length) { return false; } - - for (var i = 0, len = oldModels.length; i < len; ++i) { - if (oldModels[i] !== providedModelsArray[i]) { return false; } - } - - if(!queryParamsEqual(oldTransition.queryParams, queryParams)) { - return false; - } - - return true; - } - - /** - @private - - Updates the URL (if necessary) and calls `setupContexts` - to update the router's array of `currentHandlerInfos`. - */ - function finalizeTransition(transition, handlerInfos) { - - log(transition.router, transition.sequence, "Validation succeeded, finalizing transition;"); - - var router = transition.router, - seq = transition.sequence, - handlerName = handlerInfos[handlerInfos.length - 1].name, - urlMethod = transition.urlMethod, - i; - - // Collect params for URL. - var objects = [], providedModels = transition.providedModelsArray.slice(); - for (i = handlerInfos.length - 1; i>=0; --i) { - var handlerInfo = handlerInfos[i]; - if (handlerInfo.isDynamic) { - var providedModel = providedModels.pop(); - objects.unshift(isParam(providedModel) ? providedModel.toString() : handlerInfo.context); - } - - if (handlerInfo.handler.inaccessibleByURL) { - urlMethod = null; - } - } - - var newQueryParams = {}; - for (i = handlerInfos.length - 1; i>=0; --i) { - merge(newQueryParams, handlerInfos[i].queryParams); - } - router.currentQueryParams = newQueryParams; - - - var params = paramsForHandler(router, handlerName, objects, transition.queryParams); - - router.currentParams = params; - - if (urlMethod) { - var url = router.recognizer.generate(handlerName, params); - - if (urlMethod === 'replace') { - router.replaceURL(url); - } else { - // Assume everything else is just a URL update for now. - router.updateURL(url); - } - } - - setupContexts(transition, handlerInfos); - } - - /** - @private - - Internal function used to construct the chain of promises used - to validate a transition. Wraps calls to `beforeModel`, `model`, - and `afterModel` in promises, and checks for redirects/aborts - between each. - */ - function validateEntry(transition, matchPoint, handlerParams) { - - var handlerInfos = transition.handlerInfos, - index = transition.resolveIndex; - - if (index === handlerInfos.length) { - // No more contexts to resolve. - return RSVP.resolve(transition.resolvedModels); - } - - var router = transition.router, - handlerInfo = handlerInfos[index], - handler = handlerInfo.handler, - handlerName = handlerInfo.name, - seq = transition.sequence; - - if (index < matchPoint) { - log(router, seq, handlerName + ": using context from already-active handler"); - - // We're before the match point, so don't run any hooks, - // just use the already resolved context from the handler. - transition.resolvedModels[handlerInfo.name] = - transition.providedModels[handlerInfo.name] || - handlerInfo.handler.context; - return proceed(); - } - - transition.trigger(true, 'willResolveModel', transition, handler); - - return RSVP.resolve().then(handleAbort) - .then(beforeModel) - .then(handleAbort) - .then(model) - .then(handleAbort) - .then(afterModel) - .then(handleAbort) - .then(null, handleError) - .then(proceed); - - function handleAbort(result) { - if (transition.isAborted) { - log(transition.router, transition.sequence, "detected abort."); - return RSVP.reject(new Router.TransitionAborted()); - } - - return result; - } - - function handleError(reason) { - if (reason instanceof Router.TransitionAborted || transition.isAborted) { - // if the transition was aborted and *no additional* error was thrown, - // reject with the Router.TransitionAborted instance - return RSVP.reject(reason); - } - - // otherwise, we're here because of a different error - transition.abort(); - - log(router, seq, handlerName + ": handling error: " + reason); - - // An error was thrown / promise rejected, so fire an - // `error` event from this handler info up to root. - transition.trigger(true, 'error', reason, transition, handlerInfo.handler); - - // Propagate the original error. - return RSVP.reject(reason); - } - - function beforeModel() { - - log(router, seq, handlerName + ": calling beforeModel hook"); - - var args; - - if (handlerInfo.queryParams) { - args = [handlerInfo.queryParams, transition]; - } else { - args = [transition]; - } - - var p = handler.beforeModel && handler.beforeModel.apply(handler, args); - return (p instanceof Transition) ? null : p; - } - - function model() { - log(router, seq, handlerName + ": resolving model"); - var p = getModel(handlerInfo, transition, handlerParams[handlerName], index >= matchPoint); - return (p instanceof Transition) ? null : p; - } - - function afterModel(context) { - - log(router, seq, handlerName + ": calling afterModel hook"); - - // Pass the context and resolved parent contexts to afterModel, but we don't - // want to use the value returned from `afterModel` in any way, but rather - // always resolve with the original `context` object. - - transition.resolvedModels[handlerInfo.name] = context; - - var args; - - if (handlerInfo.queryParams) { - args = [context, handlerInfo.queryParams, transition]; - } else { - args = [context, transition]; - } - - var p = handler.afterModel && handler.afterModel.apply(handler, args); - return (p instanceof Transition) ? null : p; - } - - function proceed() { - log(router, seq, handlerName + ": validation succeeded, proceeding"); - - handlerInfo.context = transition.resolvedModels[handlerInfo.name]; - transition.resolveIndex++; - return validateEntry(transition, matchPoint, handlerParams); - } - } - - /** - @private - - Throws a TransitionAborted if the provided transition has been aborted. - */ - function checkAbort(transition) { - if (transition.isAborted) { - log(transition.router, transition.sequence, "detected abort."); - throw new Router.TransitionAborted(); - } - } - - /** - @private - - Encapsulates the logic for whether to call `model` on a route, - or use one of the models provided to `transitionTo`. - */ - function getModel(handlerInfo, transition, handlerParams, needsUpdate) { - var handler = handlerInfo.handler, - handlerName = handlerInfo.name, args; - - if (!needsUpdate && handler.hasOwnProperty('context')) { - return handler.context; - } - - if (transition.providedModels.hasOwnProperty(handlerName)) { - var providedModel = transition.providedModels[handlerName]; - return typeof providedModel === 'function' ? providedModel() : providedModel; - } - - if (handlerInfo.queryParams) { - args = [handlerParams || {}, handlerInfo.queryParams, transition]; - } else { - args = [handlerParams || {}, transition, handlerInfo.queryParams]; - } - - return handler.model && handler.model.apply(handler, args); - } - - /** - @private - */ - function log(router, sequence, msg) { - - if (!router.log) { return; } - - if (arguments.length === 3) { - router.log("Transition #" + sequence + ": " + msg); - } else { - msg = sequence; - router.log(msg); - } - } - - /** - @private - - Begins and returns a Transition based on the provided - arguments. Accepts arguments in the form of both URL - transitions and named transitions. - - @param {Router} router - @param {Array[Object]} args arguments passed to transitionTo, - replaceWith, or handleURL - */ - function doTransition(router, args, isIntermediate) { - // Normalize blank transitions to root URL transitions. - var name = args[0] || '/'; - - if(args.length === 1 && args[0].hasOwnProperty('queryParams')) { - return createQueryParamTransition(router, args[0], isIntermediate); - } else if (name.charAt(0) === '/') { - return createURLTransition(router, name, isIntermediate); - } else { - return createNamedTransition(router, slice.call(args), isIntermediate); - } - } - - /** - @private - - Serializes a handler using its custom `serialize` method or - by a default that looks up the expected property name from - the dynamic segment. - - @param {Object} handler a router handler - @param {Object} model the model to be serialized for this handler - @param {Array[Object]} names the names array attached to an - handler object returned from router.recognizer.handlersFor() - */ - function serialize(handler, model, names) { - - var object = {}; - if (isParam(model)) { - object[names[0]] = model; - return object; - } - - // Use custom serialize if it exists. - if (handler.serialize) { - return handler.serialize(model, names); - } - - if (names.length !== 1) { return; } - - var name = names[0]; - - if (/_id$/.test(name)) { - object[name] = model.id; - } else { - object[name] = model; - } - return object; - } - }); - -})(); - - - -(function() { -/** -@module ember -@submodule ember-routing -*/ - -function DSL(name) { - this.parent = name; - this.matches = []; -} - -DSL.prototype = { - resource: function(name, options, callback) { - if (arguments.length === 2 && typeof options === 'function') { - callback = options; - options = {}; - } - - if (arguments.length === 1) { - options = {}; - } - - if (typeof options.path !== 'string') { - options.path = "/" + name; - } - - if (callback) { - var dsl = new DSL(name); - route(dsl, 'loading'); - route(dsl, 'error', { path: "/_unused_dummy_error_path_route_" + name + "/:error" }); - callback.call(dsl); - this.push(options.path, name, dsl.generate(), options.queryParams); - } else { - this.push(options.path, name, null, options.queryParams); - } - - - }, - - push: function(url, name, callback, queryParams) { - var parts = name.split('.'); - if (url === "" || url === "/" || parts[parts.length-1] === "index") { this.explicitIndex = true; } - - this.matches.push([url, name, callback, queryParams]); - }, - - route: function(name, options) { - route(this, name, options); - }, - - generate: function() { - var dslMatches = this.matches; - - if (!this.explicitIndex) { - this.route("index", { path: "/" }); - } - - return function(match) { - for (var i=0, l=dslMatches.length; i= 0; --i) { - var handlerInfo = handlerInfos[i], - route = handlerInfo.handler; - - if (!originRouteFound) { - if (originRoute === route) { - originRouteFound = true; - } - continue; - } - - if (callback(route, handlerInfos[i + 1].handler) !== true) { - return false; - } - } - return true; -} - -// These get invoked when an action bubbles above ApplicationRoute -// and are not meant to be overridable. -var defaultActionHandlers = { - - willResolveModel: function(transition, originRoute) { - originRoute.router._scheduleLoadingEvent(transition, originRoute); - }, - - error: function(error, transition, originRoute) { - // Attempt to find an appropriate error substate to enter. - var router = originRoute.router; - - var tryTopLevel = forEachRouteAbove(originRoute, transition, function(route, childRoute) { - var childErrorRouteName = findChildRouteName(route, childRoute, 'error'); - if (childErrorRouteName) { - router.intermediateTransitionTo(childErrorRouteName, error); - return; - } - return true; - }); - - if (tryTopLevel) { - // Check for top-level error state to enter. - if (routeHasBeenDefined(originRoute.router, 'application_error')) { - router.intermediateTransitionTo('application_error', error); - return; - } - } else { - // Don't fire an assertion if we found an error substate. - return; - } - - Ember.Logger.error('Error while loading route: ' + error.stack); - }, - - loading: function(transition, originRoute) { - // Attempt to find an appropriate loading substate to enter. - var router = originRoute.router; - - var tryTopLevel = forEachRouteAbove(originRoute, transition, function(route, childRoute) { - var childLoadingRouteName = findChildRouteName(route, childRoute, 'loading'); - - if (childLoadingRouteName) { - router.intermediateTransitionTo(childLoadingRouteName); - return; - } - - // Don't bubble above pivot route. - if (transition.pivotHandler !== route) { - return true; - } - }); - - if (tryTopLevel) { - // Check for top-level loading state to enter. - if (routeHasBeenDefined(originRoute.router, 'application_loading')) { - router.intermediateTransitionTo('application_loading'); - return; - } - } - } -}; - -function findChildRouteName(parentRoute, originatingChildRoute, name) { - var router = parentRoute.router, - childName, - targetChildRouteName = originatingChildRoute.routeName.split('.').pop(), - namespace = parentRoute.routeName === 'application' ? '' : parentRoute.routeName + '.'; - - - // Second, try general loading state, e.g. 'loading' - childName = namespace + name; - if (routeHasBeenDefined(router, childName)) { - return childName; - } -} - -function routeHasBeenDefined(router, name) { - var container = router.container; - return router.hasRoute(name) && - (container.has('template:' + name) || container.has('route:' + name)); -} - -function triggerEvent(handlerInfos, ignoreFailure, args) { - var name = args.shift(); - - if (!handlerInfos) { - if (ignoreFailure) { return; } - throw new Ember.Error("Can't trigger action '" + name + "' because your app hasn't finished transitioning into its first route. To trigger an action on destination routes during a transition, you can call `.send()` on the `Transition` object passed to the `model/beforeModel/afterModel` hooks."); - } - - var eventWasHandled = false; - - for (var i = handlerInfos.length - 1; i >= 0; i--) { - var handlerInfo = handlerInfos[i], - handler = handlerInfo.handler; - - if (handler._actions && handler._actions[name]) { - if (handler._actions[name].apply(handler, args) === true) { - eventWasHandled = true; - } else { - return; - } - } - } - - if (defaultActionHandlers[name]) { - defaultActionHandlers[name].apply(null, args); - return; - } - - if (!eventWasHandled && !ignoreFailure) { - throw new Ember.Error("Nothing handled the action '" + name + "'. If you did handle the action, this error can be caused by returning true from an action handler in a controller, causing the action to bubble."); - } -} - -function updatePaths(router) { - var appController = router.container.lookup('controller:application'); - - if (!appController) { - // appController might not exist when top-level loading/error - // substates have been entered since ApplicationRoute hasn't - // actually been entered at that point. - return; - } - - var infos = router.router.currentHandlerInfos, - path = Ember.Router._routePath(infos); - - if (!('currentPath' in appController)) { - defineProperty(appController, 'currentPath'); - } - - set(appController, 'currentPath', path); - - if (!('currentRouteName' in appController)) { - defineProperty(appController, 'currentRouteName'); - } - - set(appController, 'currentRouteName', infos[infos.length - 1].name); -} - -Ember.Router.reopenClass({ - router: null, - map: function(callback) { - var router = this.router; - if (!router) { - router = new Router(); - router.callbacks = []; - router.triggerEvent = triggerEvent; - this.reopenClass({ router: router }); - } - - var dsl = Ember.RouterDSL.map(function() { - this.resource('application', { path: "/" }, function() { - for (var i=0; i < router.callbacks.length; i++) { - router.callbacks[i].call(this); - } - callback.call(this); - }); - }); - - router.callbacks.push(callback); - router.map(dsl.generate()); - return router; - }, - - _routePath: function(handlerInfos) { - var path = []; - - // We have to handle coalescing resource names that - // are prefixed with their parent's names, e.g. - // ['foo', 'foo.bar.baz'] => 'foo.bar.baz', not 'foo.foo.bar.baz' - - function intersectionMatches(a1, a2) { - for (var i = 0, len = a1.length; i < len; ++i) { - if (a1[i] !== a2[i]) { - return false; - } - } - return true; - } - - for (var i=1, l=handlerInfos.length; i - Great Hamster Photos - - ``` - - ### Supplying a tagName - By default `{{link-to}}` renders an `` element. This can - be overridden for a single use of `{{link-to}}` by supplying - a `tagName` option: - - ```handlebars - {{#link-to 'photoGallery' tagName="li"}} - Great Hamster Photos - {{/link-to}} - ``` - - ```html -
  • - Great Hamster Photos -
  • - ``` - - To override this option for your entire application, see - "Overriding Application-wide Defaults". - - ### Disabling the `link-to` helper - By default `{{link-to}}` is enabled. - any passed value to `disabled` helper property will disable the `link-to` helper. - - static use: the `disabled` option: - - ```handlebars - {{#link-to 'photoGallery' disabled=true}} - Great Hamster Photos - {{/link-to}} - ``` - - dynamic use: the `disabledWhen` option: - - ```handlebars - {{#link-to 'photoGallery' disabledWhen=controller.someProperty}} - Great Hamster Photos - {{/link-to}} - ``` - - any passed value to `disabled` will disable it except `undefined`. - to ensure that only `true` disable the `link-to` helper you can - override the global behaviour of `Ember.LinkView`. - - ```javascript - Ember.LinkView.reopen({ - disabled: Ember.computed(function(key, value) { - if (value !== undefined) { - this.set('_isDisabled', value === true); - } - return value === true ? get(this, 'disabledClass') : false; - }) - }); - ``` - - see "Overriding Application-wide Defaults" for more. - - ### Handling `href` - `{{link-to}}` will use your application's Router to - fill the element's `href` property with a url that - matches the path to the supplied `routeName` for your - routers's configured `Location` scheme, which defaults - to Ember.HashLocation. - - ### Handling current route - `{{link-to}}` will apply a CSS class name of 'active' - when the application's current route matches - the supplied routeName. For example, if the application's - current route is 'photoGallery.recent' the following - use of `{{link-to}}`: - - ```handlebars - {{#link-to 'photoGallery.recent'}} - Great Hamster Photos from the last week - {{/link-to}} - ``` - - will result in - - ```html -
    - Great Hamster Photos - - ``` - - The CSS class name used for active classes can be customized - for a single use of `{{link-to}}` by passing an `activeClass` - option: - - ```handlebars - {{#link-to 'photoGallery.recent' activeClass="current-url"}} - Great Hamster Photos from the last week - {{/link-to}} - ``` - - ```html - - Great Hamster Photos - - ``` - - To override this option for your entire application, see - "Overriding Application-wide Defaults". - - ### Supplying a model - An optional model argument can be used for routes whose - paths contain dynamic segments. This argument will become - the model context of the linked route: - - ```javascript - App.Router.map(function() { - this.resource("photoGallery", {path: "hamster-photos/:photo_id"}); - }); - ``` - - ```handlebars - {{#link-to 'photoGallery' aPhoto}} - {{aPhoto.title}} - {{/link-to}} - ``` - - ```html - - Tomster - - ``` - - ### Supplying multiple models - For deep-linking to route paths that contain multiple - dynamic segments, multiple model arguments can be used. - As the router transitions through the route path, each - supplied model argument will become the context for the - route with the dynamic segments: - - ```javascript - App.Router.map(function() { - this.resource("photoGallery", {path: "hamster-photos/:photo_id"}, function() { - this.route("comment", {path: "comments/:comment_id"}); - }); - }); - ``` - This argument will become the model context of the linked route: - - ```handlebars - {{#link-to 'photoGallery.comment' aPhoto comment}} - {{comment.body}} - {{/link-to}} - ``` - - ```html - - A+++ would snuggle again. - - ``` - - ### Supplying an explicit dynamic segment value - If you don't have a model object available to pass to `{{link-to}}`, - an optional string or integer argument can be passed for routes whose - paths contain dynamic segments. This argument will become the value - of the dynamic segment: - - ```javascript - App.Router.map(function() { - this.resource("photoGallery", {path: "hamster-photos/:photo_id"}); - }); - ``` - - ```handlebars - {{#link-to 'photoGallery' aPhotoId}} - {{aPhoto.title}} - {{/link-to}} - ``` - - ```html - - Tomster - - ``` - - When transitioning into the linked route, the `model` hook will - be triggered with parameters including this passed identifier. - - ### Allowing Default Action - - By default the `{{link-to}}` helper prevents the default browser action - by calling `preventDefault()` as this sort of action bubbling is normally - handled internally and we do not want to take the browser to a new URL (for - example). - - If you need to override this behavior specify `preventDefault=false` in - your template: - - ```handlebars - {{#link-to 'photoGallery' aPhotoId preventDefault=false}} - {{aPhotoId.title}} - {{/link-to}} - ``` - - ### Overriding attributes - You can override any given property of the Ember.LinkView - that is generated by the `{{link-to}}` helper by passing - key/value pairs, like so: - - ```handlebars - {{#link-to aPhoto tagName='li' title='Following this link will change your life' classNames='pic sweet'}} - Uh-mazing! - {{/link-to}} - ``` - - See [Ember.LinkView](/api/classes/Ember.LinkView.html) for a - complete list of overrideable properties. Be sure to also - check out inherited properties of `LinkView`. - - ### Overriding Application-wide Defaults - ``{{link-to}}`` creates an instance of Ember.LinkView - for rendering. To override options for your entire - application, reopen Ember.LinkView and supply the - desired values: - - ``` javascript - Ember.LinkView.reopen({ - activeClass: "is-active", - tagName: 'li' - }) - ``` - - It is also possible to override the default event in - this manner: - - ``` javascript - Ember.LinkView.reopen({ - eventName: 'customEventName' - }); - ``` - - @method link-to - @for Ember.Handlebars.helpers - @param {String} routeName - @param {Object} [context]* - @param [options] {Object} Handlebars key/value pairs of options, you can override any property of Ember.LinkView - @return {String} HTML string - @see {Ember.LinkView} - */ - Ember.Handlebars.registerHelper('link-to', function linkToHelper(name) { - var options = [].slice.call(arguments, -1)[0], - params = [].slice.call(arguments, 0, -1), - hash = options.hash; - - hash.disabledBinding = hash.disabledWhen; - - if (!options.fn) { - var linkTitle = params.shift(); - var linkType = options.types.shift(); - var context = this; - if (linkType === 'ID') { - options.linkTextPath = linkTitle; - options.fn = function() { - return Ember.Handlebars.getEscaped(context, linkTitle, options); - }; - } else { - options.fn = function() { - return linkTitle; - }; - } - } - - hash.parameters = { - context: this, - options: options, - params: params - }; - - return Ember.Handlebars.helpers.view.call(this, LinkView, options); - }); - - /** - See [link-to](/api/classes/Ember.Handlebars.helpers.html#method_link-to) - - @method linkTo - @for Ember.Handlebars.helpers - @deprecated - @param {String} routeName - @param {Object} [context]* - @return {String} HTML string - */ - Ember.Handlebars.registerHelper('linkTo', function linkToHelper() { - return Ember.Handlebars.helpers['link-to'].apply(this, arguments); - }); -}); - - - -})(); - - - -(function() { -/** -@module ember -@submodule ember-routing -*/ - -var get = Ember.get, set = Ember.set; -Ember.onLoad('Ember.Handlebars', function(Handlebars) { - /** - @module ember - @submodule ember-routing - */ - - Handlebars.OutletView = Ember.ContainerView.extend(Ember._Metamorph); - - /** - The `outlet` helper is a placeholder that the router will fill in with - the appropriate template based on the current state of the application. - - ``` handlebars - {{outlet}} - ``` - - By default, a template based on Ember's naming conventions will be rendered - into the `outlet` (e.g. `App.PostsRoute` will render the `posts` template). - - You can render a different template by using the `render()` method in the - route's `renderTemplate` hook. The following will render the `favoritePost` - template into the `outlet`. - - ``` javascript - App.PostsRoute = Ember.Route.extend({ - renderTemplate: function() { - this.render('favoritePost'); - } - }); - ``` - - You can create custom named outlets for more control. - - ``` handlebars - {{outlet 'favoritePost'}} - {{outlet 'posts'}} - ``` - - Then you can define what template is rendered into each outlet in your - route. - - - ``` javascript - App.PostsRoute = Ember.Route.extend({ - renderTemplate: function() { - this.render('favoritePost', { outlet: 'favoritePost' }); - this.render('posts', { outlet: 'posts' }); - } - }); - ``` - - You can specify the view that the outlet uses to contain and manage the - templates rendered into it. - - ``` handlebars - {{outlet view='sectionContainer'}} - ``` - - ``` javascript - App.SectionContainer = Ember.ContainerView.extend({ - tagName: 'section', - classNames: ['special'] - }); - ``` - - @method outlet - @for Ember.Handlebars.helpers - @param {String} property the property on the controller - that holds the view for this outlet - @return {String} HTML string - */ - Handlebars.registerHelper('outlet', function outletHelper(property, options) { - - var outletSource, - container, - viewName, - viewClass, - viewFullName; - - if (property && property.data && property.data.isRenderData) { - options = property; - property = 'main'; - } - - container = options.data.view.container; - - outletSource = options.data.view; - while (!outletSource.get('template.isTop')) { - outletSource = outletSource.get('_parentView'); - } - - // provide controller override - viewName = options.hash.view; - - if (viewName) { - viewFullName = 'view:' + viewName; - } - - viewClass = viewName ? container.lookupFactory(viewFullName) : options.hash.viewClass || Handlebars.OutletView; - - options.data.view.set('outletSource', outletSource); - options.hash.currentViewBinding = '_view.outletSource._outlets.' + property; - - return Handlebars.helpers.view.call(this, viewClass, options); - }); -}); - -})(); - - - -(function() { -/** -@module ember -@submodule ember-routing -*/ - -var get = Ember.get, set = Ember.set; -Ember.onLoad('Ember.Handlebars', function(Handlebars) { - - /** - Calling ``{{render}}`` from within a template will insert another - template that matches the provided name. The inserted template will - access its properties on its own controller (rather than the controller - of the parent template). - - If a view class with the same name exists, the view class also will be used. - - Note: A given controller may only be used *once* in your app in this manner. - A singleton instance of the controller will be created for you. - - Example: - - ```javascript - App.NavigationController = Ember.Controller.extend({ - who: "world" - }); - ``` - - ```handlebars - - Hello, {{who}}. - ``` - - ```handelbars - -

    My great app

    - {{render navigation}} - ``` - - ```html -

    My great app

    -
    - Hello, world. -
    - ``` - - Optionally you may provide a second argument: a property path - that will be bound to the `model` property of the controller. - - If a `model` property path is specified, then a new instance of the - controller will be created and `{{render}}` can be used multiple times - with the same name. - - For example if you had this `author` template. - - ```handlebars -
    - Written by {{firstName}} {{lastName}}. - Total Posts: {{postCount}} -
    - ``` - - You could render it inside the `post` template using the `render` helper. - - ```handlebars -
    -

    {{title}}

    -
    {{body}}
    - {{render "author" author}} -
    - ``` - - @method render - @for Ember.Handlebars.helpers - @param {String} name - @param {Object?} contextString - @param {Hash} options - @return {String} HTML string - */ - Ember.Handlebars.registerHelper('render', function renderHelper(name, contextString, options) { - var length = arguments.length; - var contextProvided = length === 3, - container, router, controller, view, context, lookupOptions; - - container = (options || contextString).data.keywords.controller.container; - router = container.lookup('router:main'); - - if (length === 2) { - // use the singleton controller - options = contextString; - contextString = undefined; - } else if (length === 3) { - // create a new controller - context = Ember.Handlebars.get(options.contexts[1], contextString, options); - } else { - throw Ember.Error("You must pass a templateName to render"); - } - - // # legacy namespace - name = name.replace(/\//g, '.'); - // \ legacy slash as namespace support - - - view = container.lookup('view:' + name) || container.lookup('view:default'); - - // provide controller override - var controllerName = options.hash.controller || name; - var controllerFullName = 'controller:' + controllerName; - - if (options.hash.controller) { - } - - var parentController = options.data.keywords.controller; - - // choose name - if (length > 2) { - var factory = container.lookupFactory(controllerFullName) || - Ember.generateControllerFactory(container, controllerName, context); - - controller = factory.create({ - model: context, - parentController: parentController, - target: parentController - }); - - } else { - controller = container.lookup(controllerFullName) || - Ember.generateController(container, controllerName); - - controller.setProperties({ - target: parentController, - parentController: parentController - }); - } - - var root = options.contexts[1]; - - if (root) { - view.registerObserver(root, contextString, function() { - controller.set('model', Ember.Handlebars.get(root, contextString, options)); - }); - } - - options.hash.viewName = Ember.String.camelize(name); - - var templateName = 'template:' + name; - options.hash.template = container.lookup(templateName); - - options.hash.controller = controller; - - if (router && !context) { - router._connectActiveView(name, view); - } - - Ember.Handlebars.helpers.view.call(this, view, options); - }); -}); - -})(); - - - -(function() { -/** -@module ember -@submodule ember-routing -*/ -Ember.onLoad('Ember.Handlebars', function(Handlebars) { - - var resolveParams = Ember.Router.resolveParams, - isSimpleClick = Ember.ViewUtils.isSimpleClick; - - var EmberHandlebars = Ember.Handlebars, - handlebarsGet = EmberHandlebars.get, - SafeString = EmberHandlebars.SafeString, - forEach = Ember.ArrayPolyfills.forEach, - get = Ember.get, - a_slice = Array.prototype.slice; - - function args(options, actionName) { - var ret = []; - if (actionName) { ret.push(actionName); } - - var types = options.options.types.slice(1), - data = options.options.data; - - return ret.concat(resolveParams(options.context, options.params, { types: types, data: data })); - } - - var ActionHelper = EmberHandlebars.ActionHelper = { - registeredActions: {} - }; - - var keys = ["alt", "shift", "meta", "ctrl"]; - - var POINTER_EVENT_TYPE_REGEX = /^click|mouse|touch/; - - var isAllowedEvent = function(event, allowedKeys) { - if (typeof allowedKeys === "undefined") { - if (POINTER_EVENT_TYPE_REGEX.test(event.type)) { - return isSimpleClick(event); - } else { - allowedKeys = ''; - } - } - - if (allowedKeys.indexOf("any") >= 0) { - return true; - } - - var allowed = true; - - forEach.call(keys, function(key) { - if (event[key + "Key"] && allowedKeys.indexOf(key) === -1) { - allowed = false; - } - }); - - return allowed; - }; - - ActionHelper.registerAction = function(actionName, options, allowedKeys) { - var actionId = (++Ember.uuid).toString(); - - ActionHelper.registeredActions[actionId] = { - eventName: options.eventName, - handler: function handleRegisteredAction(event) { - if (!isAllowedEvent(event, allowedKeys)) { return true; } - - if (options.preventDefault !== false) { - event.preventDefault(); - } - - if (options.bubbles === false) { - event.stopPropagation(); - } - - var target = options.target; - - if (target.target) { - target = handlebarsGet(target.root, target.target, target.options); - } else { - target = target.root; - } - - Ember.run(function runRegisteredAction() { - if (target.send) { - target.send.apply(target, args(options.parameters, actionName)); - } else { - target[actionName].apply(target, args(options.parameters)); - } - }); - } - }; - - 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 templates's controller - or supplied `target` option (see 'Specifying a Target'). - - If the controller does not implement the event, the event is sent - to the current route, and it bubbles up the route hierarchy from there. - - User interaction with that element will invoke the supplied action name on - the appropriate target. - - Given the following application Handlebars template on the page - - ```handlebars -
    - click me -
    - ``` - - And application code - - ```javascript - App.ApplicationController = Ember.Controller.extend({ - actions: { - anActionName: function() { - } - } - }); - ``` - - Will result in the following rendered HTML - - ```html -
    -
    - click me -
    -
    - ``` - - Clicking "click me" will trigger the `anActionName` action of the - `App.ApplicationController`. In this case, no additional parameters will be passed. - - If you provide additional parameters to the helper: - - ```handlebars - - ``` - - Those parameters will be passed along as arguments to the JavaScript - function implementing the action. - - ### 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. If you need to allow event propagation (to handle file inputs for - example) you can supply the `preventDefault=false` option to the `{{action}}` helper: - - ```handlebars -
    - - -
    - ``` - - To disable bubbling, pass `bubbles=false` to the helper: - - ```handlebars - - ``` - - 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](/api/classes/Ember.View.html) - '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 -
    - click me -
    - ``` - - See `Ember.View` 'Responding to Browser Events' for a list of - acceptable DOM event names. - - NOTE: 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 whitelisted modifier keys - - By default the `{{action}}` helper will ignore click event with pressed modifier - keys. You can supply an `allowedKeys` option to specify which keys should not be ignored. - - ```handlebars -
    - click me -
    - ``` - - This way the `{{action}}` will fire when clicking with the alt key pressed down. - - Alternatively, supply "any" to the `allowedKeys` option to accept any combination of modifier keys. - - ```handlebars -
    - click me with any key pressed -
    - ``` - - ### Specifying a Target - - There are several possible target objects for `{{action}}` helpers: - - In a typical Ember application, where views are managed through use of the - `{{outlet}}` helper, actions will bubble to the current controller, then - to the current route, and then up the route hierarchy. - - Alternatively, a `target` option can be provided to the helper to change - which object will receive the method call. This option must be a path - to an object, accessible in the current context: - - ```handlebars - {{! the application template }} -
    - click me -
    - ``` - - ```javascript - App.ApplicationView = Ember.View.extend({ - actions: { - anActionName: function(){} - } - }); - - ``` - - ### Additional Parameters - - You may specify additional parameters to the `{{action}}` helper. These - parameters are passed along as the arguments to the JavaScript function - implementing the action. - - ```handlebars - {{#each person in people}} -
    - click me -
    - {{/each}} - ``` - - Clicking "click me" will trigger the `edit` method on the current controller - with the value of `person` as a parameter. - - @method action - @for Ember.Handlebars.helpers - @param {String} actionName - @param {Object} [context]* - @param {Hash} options - */ - EmberHandlebars.registerHelper('action', function actionHelper(actionName) { - var options = arguments[arguments.length - 1], - contexts = a_slice.call(arguments, 1, -1); - - var hash = options.hash, - controller; - - // create a hash to pass along to registerAction - var action = { - eventName: hash.on || "click" - }; - - action.parameters = { - context: this, - options: options, - params: contexts - }; - - action.view = options.data.view; - - var root, target; - - if (hash.target) { - root = this; - target = hash.target; - } else if (controller = options.data.keywords.controller) { - root = controller; - } - - action.target = { root: root, target: target, options: options }; - action.bubbles = hash.bubbles; - action.preventDefault = hash.preventDefault; - - var actionId = ActionHelper.registerAction(actionName, action, hash.allowedKeys); - return new SafeString('data-ember-action="' + actionId + '"'); - }); - -}); - -})(); - - - -(function() { - -})(); - - - -(function() { -/** -@module ember -@submodule ember-routing -*/ - -var get = Ember.get, set = Ember.set; - -Ember.ControllerMixin.reopen({ - /** - Transition the application into another route. The route may - be either a single route or route path: - - ```javascript - aController.transitionToRoute('blogPosts'); - aController.transitionToRoute('blogPosts.recentEntries'); - ``` - - Optionally supply a model for the route in question. The model - will be serialized into the URL using the `serialize` hook of - the route: - - ```javascript - aController.transitionToRoute('blogPost', aPost); - ``` - - Multiple models will be applied last to first recursively up the - resource tree. - - ```javascript - this.resource('blogPost', {path:':blogPostId'}, function(){ - this.resource('blogComment', {path: ':blogCommentId'}); - }); - - aController.transitionToRoute('blogComment', aPost, aComment); - ``` - - See also 'replaceRoute'. - - @param {String} name the name of the route - @param {...Object} models the model(s) to be used while transitioning - to the route. - @for Ember.ControllerMixin - @method transitionToRoute - */ - transitionToRoute: function() { - // target may be either another controller or a router - var target = get(this, 'target'), - method = target.transitionToRoute || target.transitionTo; - return method.apply(target, arguments); - }, - - /** - @deprecated - @for Ember.ControllerMixin - @method transitionTo - */ - transitionTo: function() { - return this.transitionToRoute.apply(this, arguments); - }, - - /** - Transition into another route while replacing the current URL, if possible. - This will replace the current history entry instead of adding a new one. - Beside that, it is identical to `transitionToRoute` in all other respects. - - ```javascript - aController.replaceRoute('blogPosts'); - aController.replaceRoute('blogPosts.recentEntries'); - ``` - - Optionally supply a model for the route in question. The model - will be serialized into the URL using the `serialize` hook of - the route: - - ```javascript - aController.replaceRoute('blogPost', aPost); - ``` - - Multiple models will be applied last to first recursively up the - resource tree. - - ```javascript - this.resource('blogPost', {path:':blogPostId'}, function(){ - this.resource('blogComment', {path: ':blogCommentId'}); - }); - - aController.replaceRoute('blogComment', aPost, aComment); - ``` - - @param {String} name the name of the route - @param {...Object} models the model(s) to be used while transitioning - to the route. - @for Ember.ControllerMixin - @method replaceRoute - */ - replaceRoute: function() { - // target may be either another controller or a router - var target = get(this, 'target'), - method = target.replaceRoute || target.replaceWith; - return method.apply(target, arguments); - }, - - /** - @deprecated - @for Ember.ControllerMixin - @method replaceWith - */ - replaceWith: function() { - return this.replaceRoute.apply(this, arguments); - } -}); - -})(); - - - -(function() { -/** -@module ember -@submodule ember-routing -*/ - -var get = Ember.get, set = Ember.set; - -Ember.View.reopen({ - - /** - Sets the private `_outlets` object on the view. - - @method init - */ - init: function() { - set(this, '_outlets', {}); - this._super(); - }, - - /** - Manually fill any of a view's `{{outlet}}` areas with the - supplied view. - - Example - - ```javascript - var MyView = Ember.View.extend({ - template: Ember.Handlebars.compile('Child view: {{outlet "main"}} ') - }); - var myView = MyView.create(); - myView.appendTo('body'); - // The html for myView now looks like: - //
    Child view:
    - - var FooView = Ember.View.extend({ - template: Ember.Handlebars.compile('

    Foo

    ') - }); - var fooView = FooView.create(); - myView.connectOutlet('main', fooView); - // The html for myView now looks like: - //
    Child view: - //

    Foo

    - //
    - ``` - @method connectOutlet - @param {String} outletName A unique name for the outlet - @param {Object} view An Ember.View - */ - connectOutlet: function(outletName, view) { - if (this._pendingDisconnections) { - delete this._pendingDisconnections[outletName]; - } - - if (this._hasEquivalentView(outletName, view)) { - view.destroy(); - return; - } - - var outlets = get(this, '_outlets'), - container = get(this, 'container'), - router = container && container.lookup('router:main'), - renderedName = get(view, 'renderedName'); - - set(outlets, outletName, view); - - if (router && renderedName) { - router._connectActiveView(renderedName, view); - } - }, - - /** - Determines if the view has already been created by checking if - the view has the same constructor, template, and context as the - view in the `_outlets` object. - - @private - @method _hasEquivalentView - @param {String} outletName The name of the outlet we are checking - @param {Object} view An Ember.View - @return {Boolean} - */ - _hasEquivalentView: function(outletName, view) { - var existingView = get(this, '_outlets.'+outletName); - return existingView && - existingView.constructor === view.constructor && - existingView.get('template') === view.get('template') && - existingView.get('context') === view.get('context'); - }, - - /** - Removes an outlet from the view. - - Example - - ```javascript - var MyView = Ember.View.extend({ - template: Ember.Handlebars.compile('Child view: {{outlet "main"}} ') - }); - var myView = MyView.create(); - myView.appendTo('body'); - // myView's html: - //
    Child view:
    - - var FooView = Ember.View.extend({ - template: Ember.Handlebars.compile('

    Foo

    ') - }); - var fooView = FooView.create(); - myView.connectOutlet('main', fooView); - // myView's html: - //
    Child view: - //

    Foo

    - //
    - - myView.disconnectOutlet('main'); - // myView's html: - //
    Child view:
    - ``` - - @method disconnectOutlet - @param {String} outletName The name of the outlet to be removed - */ - disconnectOutlet: function(outletName) { - if (!this._pendingDisconnections) { - this._pendingDisconnections = {}; - } - this._pendingDisconnections[outletName] = true; - Ember.run.once(this, '_finishDisconnections'); - }, - - /** - Gets an outlet that is pending disconnection and then - nullifys the object on the `_outlet` object. - - @private - @method _finishDisconnections - */ - _finishDisconnections: function() { - var outlets = get(this, '_outlets'); - var pendingDisconnections = this._pendingDisconnections; - this._pendingDisconnections = null; - - for (var outletName in pendingDisconnections) { - set(outlets, outletName, null); - } - } -}); - -})(); - - - -(function() { -/** -@module ember -@submodule ember-views -*/ - -// Add a new named queue after the 'actions' queue (where RSVP promises -// resolve), which is used in router transitions to prevent unnecessary -// loading state entry if all context promises resolve on the -// 'actions' queue first. - -var queues = Ember.run.queues, - indexOf = Ember.ArrayPolyfills.indexOf; -queues.splice(indexOf.call(queues, 'actions') + 1, 0, 'routerTransitions'); - -})(); - - - -(function() { -/** -@module ember -@submodule ember-routing -*/ - -var get = Ember.get, set = Ember.set; - -/** - Ember.Location returns an instance of the correct implementation of - the `location` API. - - ## Implementations - - You can pass an implementation name (`hash`, `history`, `none`) to force a - particular implementation to be used in your application. - - ### HashLocation - - Using `HashLocation` results in URLs with a `#` (hash sign) separating the - server side URL portion of the URL from the portion that is used by Ember. - This relies upon the `hashchange` event existing in the browser. - - Example: - - ```javascript - App.Router.map(function() { - this.resource('posts', function() { - this.route('new'); - }); - }); - - App.Router.reopen({ - location: 'hash' - }); - ``` - - This will result in a posts.new url of `/#/posts/new`. - - ### HistoryLocation - - Using `HistoryLocation` results in URLs that are indistinguishable from a - standard URL. This relies upon the browser's `history` API. - - Example: - - ```javascript - App.Router.map(function() { - this.resource('posts', function() { - this.route('new'); - }); - }); - - App.Router.reopen({ - location: 'history' - }); - ``` - - This will result in a posts.new url of `/posts/new`. - - ### NoneLocation - - Using `NoneLocation` causes Ember to not store the applications URL state - in the actual URL. This is generally used for testing purposes, and is one - of the changes made when calling `App.setupForTesting()`. - - ## Location API - - Each location implementation must provide the following methods: - - * implementation: returns the string name used to reference the implementation. - * getURL: returns the current URL. - * setURL(path): sets the current URL. - * replaceURL(path): replace the current URL (optional). - * onUpdateURL(callback): triggers the callback when the URL changes. - * formatURL(url): formats `url` to be placed into `href` attribute. - - Calling setURL or replaceURL will not trigger onUpdateURL callbacks. - - @class Location - @namespace Ember - @static -*/ -Ember.Location = { - /** - This is deprecated in favor of using the container to lookup the location - implementation as desired. - - For example: - - ```javascript - // Given a location registered as follows: - container.register('location:history-test', HistoryTestLocation); - - // You could create a new instance via: - container.lookup('location:history-test'); - ``` - - @method create - @param {Object} options - @return {Object} an instance of an implementation of the `location` API - @deprecated Use the container to lookup the location implementation that you - need. - */ - create: function(options) { - var implementation = options && options.implementation; - - var implementationClass = this.implementations[implementation]; - - return implementationClass.create.apply(implementationClass, arguments); - }, - - /** - This is deprecated in favor of using the container to register the - location implementation as desired. - - Example: - - ```javascript - Application.initializer({ - name: "history-test-location", - - initialize: function(container, application) { - application.register('location:history-test', HistoryTestLocation); - } - }); - ``` - - @method registerImplementation - @param {String} name - @param {Object} implementation of the `location` API - @deprecated Register your custom location implementation with the - container directly. - */ - registerImplementation: function(name, implementation) { - this.implementations[name] = implementation; - }, - - implementations: {} -}; - -})(); - - - -(function() { -/** -@module ember -@submodule ember-routing -*/ - -var get = Ember.get, set = Ember.set; - -/** - Ember.NoneLocation does not interact with the browser. It is useful for - testing, or when you need to manage state with your Router, but temporarily - don't want it to muck with the URL (for example when you embed your - application in a larger page). - - @class NoneLocation - @namespace Ember - @extends Ember.Object -*/ -Ember.NoneLocation = Ember.Object.extend({ - path: '', - - /** - Returns the current path. - - @private - @method getURL - @return {String} path - */ - getURL: function() { - return get(this, 'path'); - }, - - /** - Set the path and remembers what was set. Using this method - to change the path will not invoke the `updateURL` callback. - - @private - @method setURL - @param path {String} - */ - setURL: function(path) { - set(this, 'path', path); - }, - - /** - Register a callback to be invoked when the path changes. These - callbacks will execute when the user presses the back or forward - button, but not after `setURL` is invoked. - - @private - @method onUpdateURL - @param callback {Function} - */ - onUpdateURL: function(callback) { - this.updateCallback = callback; - }, - - /** - Sets the path and calls the `updateURL` callback. - - @private - @method handleURL - @param callback {Function} - */ - handleURL: function(url) { - set(this, 'path', url); - this.updateCallback(url); - }, - - /** - Given a URL, formats it to be placed into the page as part - of an element's `href` attribute. - - This is used, for example, when using the {{action}} helper - to generate a URL based on an event. - - @private - @method formatURL - @param url {String} - @return {String} url - */ - formatURL: function(url) { - // The return value is not overly meaningful, but we do not want to throw - // errors when test code renders templates containing {{action href=true}} - // helpers. - return url; - } -}); - -Ember.Location.registerImplementation('none', Ember.NoneLocation); - -})(); - - - -(function() { -/** -@module ember -@submodule ember-routing -*/ - -var get = Ember.get, set = Ember.set; - -/** - `Ember.HashLocation` implements the location API using the browser's - hash. At present, it relies on a `hashchange` event existing in the - browser. - - @class HashLocation - @namespace Ember - @extends Ember.Object -*/ -Ember.HashLocation = Ember.Object.extend({ - - init: function() { - set(this, 'location', get(this, 'location') || window.location); - }, - - /** - Returns the current `location.hash`, minus the '#' at the front. - - @private - @method getURL - */ - getURL: function() { - // Default implementation without feature flag enabled - return get(this, 'location').hash.substr(1); - }, - - /** - Set the `location.hash` and remembers what was set. This prevents - `onUpdateURL` callbacks from triggering when the hash was set by - `HashLocation`. - - @private - @method setURL - @param path {String} - */ - setURL: function(path) { - get(this, 'location').hash = path; - set(this, 'lastSetURL', path); - }, - - /** - Uses location.replace to update the url without a page reload - or history modification. - - @private - @method replaceURL - @param path {String} - */ - replaceURL: function(path) { - get(this, 'location').replace('#' + path); - }, - - /** - Register a callback to be invoked when the hash changes. These - callbacks will execute when the user presses the back or forward - button, but not after `setURL` is invoked. - - @private - @method onUpdateURL - @param callback {Function} - */ - onUpdateURL: function(callback) { - var self = this; - var guid = Ember.guidFor(this); - - Ember.$(window).on('hashchange.ember-location-'+guid, function() { - Ember.run(function() { - var path = location.hash.substr(1); - if (get(self, 'lastSetURL') === path) { return; } - - set(self, 'lastSetURL', null); - - callback(path); - }); - }); - }, - - /** - Given a URL, formats it to be placed into the page as part - of an element's `href` attribute. - - This is used, for example, when using the {{action}} helper - to generate a URL based on an event. - - @private - @method formatURL - @param url {String} - */ - formatURL: function(url) { - return '#'+url; - }, - - /** - Cleans up the HashLocation event listener. - - @private - @method willDestroy - */ - willDestroy: function() { - var guid = Ember.guidFor(this); - - Ember.$(window).off('hashchange.ember-location-'+guid); - } -}); - -Ember.Location.registerImplementation('hash', Ember.HashLocation); - -})(); - - - -(function() { -/** -@module ember -@submodule ember-routing -*/ - -var get = Ember.get, set = Ember.set; -var popstateFired = false; -var supportsHistoryState = window.history && 'state' in window.history; - -/** - Ember.HistoryLocation implements the location API using the browser's - history.pushState API. - - @class HistoryLocation - @namespace Ember - @extends Ember.Object -*/ -Ember.HistoryLocation = Ember.Object.extend({ - - init: function() { - set(this, 'location', get(this, 'location') || window.location); - }, - - /** - Used to set state on first call to setURL - - @private - @method initState - */ - initState: function() { - set(this, 'history', get(this, 'history') || window.history); - this.replaceState(this.formatURL(this.getURL())); - }, - - /** - Will be pre-pended to path upon state change - - @property rootURL - @default '/' - */ - rootURL: '/', - - /** - Returns the current `location.pathname` without `rootURL`. - - @private - @method getURL - @return url {String} - */ - getURL: function() { - var rootURL = get(this, 'rootURL'), - location = get(this, 'location'), - path = location.pathname; - - rootURL = rootURL.replace(/\/$/, ''); - var url = path.replace(rootURL, ''); - - - return url; - }, - - /** - Uses `history.pushState` to update the url without a page reload. - - @private - @method setURL - @param path {String} - */ - setURL: function(path) { - var state = this.getState(); - path = this.formatURL(path); - - if (state && state.path !== path) { - this.pushState(path); - } - }, - - /** - Uses `history.replaceState` to update the url without a page reload - or history modification. - - @private - @method replaceURL - @param path {String} - */ - replaceURL: function(path) { - var state = this.getState(); - path = this.formatURL(path); - - if (state && state.path !== path) { - this.replaceState(path); - } - }, - - /** - Get the current `history.state` - Polyfill checks for native browser support and falls back to retrieving - from a private _historyState variable - - @private - @method getState - @return state {Object} - */ - getState: function() { - return supportsHistoryState ? get(this, 'history').state : this._historyState; - }, - - /** - Pushes a new state. - - @private - @method pushState - @param path {String} - */ - pushState: function(path) { - var state = { path: path }; - - get(this, 'history').pushState(state, null, path); - - // store state if browser doesn't support `history.state` - if (!supportsHistoryState) { - this._historyState = state; - } - - // used for webkit workaround - this._previousURL = this.getURL(); - }, - - /** - Replaces the current state. - - @private - @method replaceState - @param path {String} - */ - replaceState: function(path) { - var state = { path: path }; - - get(this, 'history').replaceState(state, null, path); - - // store state if browser doesn't support `history.state` - if (!supportsHistoryState) { - this._historyState = state; - } - - // used for webkit workaround - this._previousURL = this.getURL(); - }, - - /** - Register a callback to be invoked whenever the browser - history changes, including using forward and back buttons. - - @private - @method onUpdateURL - @param callback {Function} - */ - onUpdateURL: function(callback) { - var guid = Ember.guidFor(this), - self = this; - - Ember.$(window).on('popstate.ember-location-'+guid, function(e) { - // Ignore initial page load popstate event in Chrome - if (!popstateFired) { - popstateFired = true; - if (self.getURL() === self._previousURL) { return; } - } - callback(self.getURL()); - }); - }, - - /** - Used when using `{{action}}` helper. The url is always appended to the rootURL. - - @private - @method formatURL - @param url {String} - @return formatted url {String} - */ - formatURL: function(url) { - var rootURL = get(this, 'rootURL'); - - if (url !== '') { - rootURL = rootURL.replace(/\/$/, ''); - } - - return rootURL + url; - }, - - /** - Cleans up the HistoryLocation event listener. - - @private - @method willDestroy - */ - willDestroy: function() { - var guid = Ember.guidFor(this); - - Ember.$(window).off('popstate.ember-location-'+guid); - } -}); - -Ember.Location.registerImplementation('history', Ember.HistoryLocation); - -})(); - - - -(function() { - -})(); - - - -(function() { -/** -Ember Routing - -@module ember -@submodule ember-routing -@requires ember-views -*/ - -})(); - -(function() { -function visit(vertex, fn, visited, path) { - var name = vertex.name, - vertices = vertex.incoming, - names = vertex.incomingNames, - len = names.length, - i; - if (!visited) { - visited = {}; - } - if (!path) { - path = []; - } - if (visited.hasOwnProperty(name)) { - return; - } - path.push(name); - visited[name] = true; - for (i = 0; i < len; i++) { - visit(vertices[names[i]], fn, visited, path); - } - fn(vertex, path); - path.pop(); -} - -function DAG() { - this.names = []; - this.vertices = {}; -} - -DAG.prototype.add = function(name) { - if (!name) { return; } - if (this.vertices.hasOwnProperty(name)) { - return this.vertices[name]; - } - var vertex = { - name: name, incoming: {}, incomingNames: [], hasOutgoing: false, value: null - }; - this.vertices[name] = vertex; - this.names.push(name); - return vertex; -}; - -DAG.prototype.map = function(name, value) { - this.add(name).value = value; -}; - -DAG.prototype.addEdge = function(fromName, toName) { - if (!fromName || !toName || fromName === toName) { - return; - } - var from = this.add(fromName), to = this.add(toName); - if (to.incoming.hasOwnProperty(fromName)) { - return; - } - function checkCycle(vertex, path) { - if (vertex.name === toName) { - throw new Ember.Error("cycle detected: " + toName + " <- " + path.join(" <- ")); - } - } - visit(from, checkCycle); - from.hasOutgoing = true; - to.incoming[fromName] = from; - to.incomingNames.push(fromName); -}; - -DAG.prototype.topsort = function(fn) { - var visited = {}, - vertices = this.vertices, - names = this.names, - len = names.length, - i, vertex; - for (i = 0; i < len; i++) { - vertex = vertices[names[i]]; - if (!vertex.hasOutgoing) { - visit(vertex, fn, visited); - } - } -}; - -DAG.prototype.addEdges = function(name, value, before, after) { - var i; - this.map(name, value); - if (before) { - if (typeof before === 'string') { - this.addEdge(name, before); - } else { - for (i = 0; i < before.length; i++) { - this.addEdge(name, before[i]); - } - } - } - if (after) { - if (typeof after === 'string') { - this.addEdge(after, name); - } else { - for (i = 0; i < after.length; i++) { - this.addEdge(after[i], name); - } - } - } -}; - -Ember.DAG = DAG; - -})(); - - - -(function() { -/** -@module ember -@submodule ember-application -*/ - -var get = Ember.get, - classify = Ember.String.classify, - capitalize = Ember.String.capitalize, - decamelize = Ember.String.decamelize; - -/** - The DefaultResolver defines the default lookup rules to resolve - container lookups before consulting the container for registered - items: - -* templates are looked up on `Ember.TEMPLATES` -* other names are looked up on the application after converting - the name. For example, `controller:post` looks up - `App.PostController` by default. -* there are some nuances (see examples below) - - ### How Resolving Works - - The container calls this object's `resolve` method with the - `fullName` argument. - - It first parses the fullName into an object using `parseName`. - - Then it checks for the presence of a type-specific instance - method of the form `resolve[Type]` and calls it if it exists. - For example if it was resolving 'template:post', it would call - the `resolveTemplate` method. - - Its last resort is to call the `resolveOther` method. - - The methods of this object are designed to be easy to override - in a subclass. For example, you could enhance how a template - is resolved like so: - - ```javascript - App = Ember.Application.create({ - Resolver: Ember.DefaultResolver.extend({ - resolveTemplate: function(parsedName) { - var resolvedTemplate = this._super(parsedName); - if (resolvedTemplate) { return resolvedTemplate; } - return Ember.TEMPLATES['not_found']; - } - }) - }); - ``` - - Some examples of how names are resolved: - - ``` - 'template:post' //=> Ember.TEMPLATES['post'] - 'template:posts/byline' //=> Ember.TEMPLATES['posts/byline'] - 'template:posts.byline' //=> Ember.TEMPLATES['posts/byline'] - 'template:blogPost' //=> Ember.TEMPLATES['blogPost'] - // OR - // Ember.TEMPLATES['blog_post'] - 'controller:post' //=> App.PostController - 'controller:posts.index' //=> App.PostsIndexController - 'controller:blog/post' //=> Blog.PostController - 'controller:basic' //=> Ember.Controller - 'route:post' //=> App.PostRoute - 'route:posts.index' //=> App.PostsIndexRoute - 'route:blog/post' //=> Blog.PostRoute - 'route:basic' //=> Ember.Route - 'view:post' //=> App.PostView - 'view:posts.index' //=> App.PostsIndexView - 'view:blog/post' //=> Blog.PostView - 'view:basic' //=> Ember.View - 'foo:post' //=> App.PostFoo - 'model:post' //=> App.Post - ``` - - @class DefaultResolver - @namespace Ember - @extends Ember.Object -*/ -Ember.DefaultResolver = Ember.Object.extend({ - /** - This will be set to the Application instance when it is - created. - - @property namespace - */ - namespace: null, - - normalize: function(fullName) { - var split = fullName.split(':', 2), - type = split[0], - name = split[1]; - - - if (type !== 'template') { - var result = name; - - if (result.indexOf('.') > -1) { - result = result.replace(/\.(.)/g, function(m) { return m.charAt(1).toUpperCase(); }); - } - - if (name.indexOf('_') > -1) { - result = result.replace(/_(.)/g, function(m) { return m.charAt(1).toUpperCase(); }); - } - - return type + ':' + result; - } else { - return fullName; - } - }, - - - /** - This method is called via the container's resolver method. - It parses the provided `fullName` and then looks up and - returns the appropriate template or class. - - @method resolve - @param {String} fullName the lookup string - @return {Object} the resolved factory - */ - resolve: function(fullName) { - var parsedName = this.parseName(fullName), - typeSpecificResolveMethod = this[parsedName.resolveMethodName]; - - if (!parsedName.name || !parsedName.type) { - throw new TypeError("Invalid fullName: `" + fullName + "`, must be of the form `type:name` "); - } - - if (typeSpecificResolveMethod) { - var resolved = typeSpecificResolveMethod.call(this, parsedName); - if (resolved) { return resolved; } - } - return this.resolveOther(parsedName); - }, - /** - Convert the string name of the form "type:name" to - a Javascript object with the parsed aspects of the name - broken out. - - @protected - @param {String} fullName the lookup string - @method parseName - */ - parseName: function(fullName) { - var nameParts = fullName.split(":"), - type = nameParts[0], fullNameWithoutType = nameParts[1], - name = fullNameWithoutType, - namespace = get(this, 'namespace'), - root = namespace; - - if (type !== 'template' && name.indexOf('/') !== -1) { - var parts = name.split('/'); - name = parts[parts.length - 1]; - var namespaceName = capitalize(parts.slice(0, -1).join('.')); - root = Ember.Namespace.byName(namespaceName); - - } - - return { - fullName: fullName, - type: type, - fullNameWithoutType: fullNameWithoutType, - name: name, - root: root, - resolveMethodName: "resolve" + classify(type) - }; - }, - /** - Look up the template in Ember.TEMPLATES - - @protected - @param {Object} parsedName a parseName object with the parsed - fullName lookup string - @method resolveTemplate - */ - resolveTemplate: function(parsedName) { - var templateName = parsedName.fullNameWithoutType.replace(/\./g, '/'); - - if (Ember.TEMPLATES[templateName]) { - return Ember.TEMPLATES[templateName]; - } - - templateName = decamelize(templateName); - if (Ember.TEMPLATES[templateName]) { - return Ember.TEMPLATES[templateName]; - } - }, - /** - Given a parseName object (output from `parseName`), apply - the conventions expected by `Ember.Router` - - @protected - @param {Object} parsedName a parseName object with the parsed - fullName lookup string - @method useRouterNaming - */ - useRouterNaming: function(parsedName) { - parsedName.name = parsedName.name.replace(/\./g, '_'); - if (parsedName.name === 'basic') { - parsedName.name = ''; - } - }, - /** - Lookup the controller using `resolveOther` - - @protected - @param {Object} parsedName a parseName object with the parsed - fullName lookup string - @method resolveController - */ - resolveController: function(parsedName) { - this.useRouterNaming(parsedName); - return this.resolveOther(parsedName); - }, - /** - Lookup the route using `resolveOther` - - @protected - @param {Object} parsedName a parseName object with the parsed - fullName lookup string - @method resolveRoute - */ - resolveRoute: function(parsedName) { - this.useRouterNaming(parsedName); - return this.resolveOther(parsedName); - }, - /** - Lookup the view using `resolveOther` - - @protected - @param {Object} parsedName a parseName object with the parsed - fullName lookup string - @method resolveView - */ - resolveView: function(parsedName) { - this.useRouterNaming(parsedName); - return this.resolveOther(parsedName); - }, - - resolveHelper: function(parsedName) { - return this.resolveOther(parsedName) || Ember.Handlebars.helpers[parsedName.fullNameWithoutType]; - }, - - /** - Lookup the model on the Application namespace - - @protected - @param {Object} parsedName a parseName object with the parsed - fullName lookup string - @method resolveModel - */ - resolveModel: function(parsedName) { - var className = classify(parsedName.name), - factory = get(parsedName.root, className); - - if (factory) { return factory; } - }, - /** - Look up the specified object (from parsedName) on the appropriate - namespace (usually on the Application) - - @protected - @param {Object} parsedName a parseName object with the parsed - fullName lookup string - @method resolveOther - */ - resolveOther: function(parsedName) { - var className = classify(parsedName.name) + classify(parsedName.type), - factory = get(parsedName.root, className); - if (factory) { return factory; } - }, - - /** - Returns a human-readable description for a fullName. Used by the - Application namespace in assertions to describe the - precise name of the class that Ember is looking for, rather than - container keys. - - @protected - @param {String} fullName the lookup string - @method lookupDescription - */ - lookupDescription: function(fullName) { - var parsedName = this.parseName(fullName); - - if (parsedName.type === 'template') { - return "template at " + parsedName.fullNameWithoutType.replace(/\./g, '/'); - } - - var description = parsedName.root + "." + classify(parsedName.name); - if (parsedName.type !== 'model') { description += classify(parsedName.type); } - - return description; - }, - - makeToString: function(factory, fullName) { - return factory.toString(); - } -}); - -})(); - - - -(function() { -/** -@module ember -@submodule ember-application -*/ - -var get = Ember.get, set = Ember.set; - -function DeprecatedContainer(container) { - this._container = container; -} - -DeprecatedContainer.deprecate = function(method) { - return function() { - var container = this._container; - - return container[method].apply(container, arguments); - }; -}; - -DeprecatedContainer.prototype = { - _container: null, - lookup: DeprecatedContainer.deprecate('lookup'), - resolve: DeprecatedContainer.deprecate('resolve'), - register: DeprecatedContainer.deprecate('register') -}; - -/** - An instance of `Ember.Application` is the starting point for every Ember - application. It helps to instantiate, initialize and coordinate the many - objects that make up your app. - - Each Ember app has one and only one `Ember.Application` object. In fact, the - very first thing you should do in your application is create the instance: - - ```javascript - window.App = Ember.Application.create(); - ``` - - Typically, the application object is the only global variable. All other - classes in your app should be properties on the `Ember.Application` instance, - which highlights its first role: a global namespace. - - For example, if you define a view class, it might look like this: - - ```javascript - App.MyView = Ember.View.extend(); - ``` - - By default, calling `Ember.Application.create()` will automatically initialize - your application by calling the `Ember.Application.initialize()` method. If - you need to delay initialization, you can call your app's `deferReadiness()` - method. When you are ready for your app to be initialized, call its - `advanceReadiness()` method. - - You can define a `ready` method on the `Ember.Application` instance, which - will be run by Ember when the application is initialized. - - Because `Ember.Application` inherits from `Ember.Namespace`, any classes - you create will have useful string representations when calling `toString()`. - See the `Ember.Namespace` documentation for more information. - - While you can think of your `Ember.Application` as a container that holds the - other classes in your application, there are several other responsibilities - going on under-the-hood that you may want to understand. - - ### Event Delegation - - Ember uses a technique called _event delegation_. This allows the framework - to set up a global, shared event listener instead of requiring each view to - do it manually. For example, instead of each view registering its own - `mousedown` listener on its associated element, Ember sets up a `mousedown` - listener on the `body`. - - If a `mousedown` event occurs, Ember will look at the target of the event and - start walking up the DOM node tree, finding corresponding views and invoking - their `mouseDown` method as it goes. - - `Ember.Application` has a number of default events that it listens for, as - well as a mapping from lowercase events to camel-cased view method names. For - example, the `keypress` event causes the `keyPress` method on the view to be - called, the `dblclick` event causes `doubleClick` to be called, and so on. - - If there is a bubbling browser event that Ember does not listen for by - default, you can specify custom events and their corresponding view method - names by setting the application's `customEvents` property: - - ```javascript - App = Ember.Application.create({ - customEvents: { - // add support for the paste event - paste: "paste" - } - }); - ``` - - By default, the application sets up these event listeners on the document - body. However, in cases where you are embedding an Ember application inside - an existing page, you may want it to set up the listeners on an element - inside the body. - - For example, if only events inside a DOM element with the ID of `ember-app` - should be delegated, set your application's `rootElement` property: - - ```javascript - window.App = Ember.Application.create({ - rootElement: '#ember-app' - }); - ``` - - The `rootElement` can be either a DOM element or a jQuery-compatible selector - string. Note that *views appended to the DOM outside the root element will - not receive events.* If you specify a custom root element, make sure you only - append views inside it! - - To learn more about the advantages of event delegation and the Ember view - layer, and a list of the event listeners that are setup by default, visit the - [Ember View Layer guide](http://emberjs.com/guides/understanding-ember/the-view-layer/#toc_event-delegation). - - ### Initializers - - Libraries on top of Ember can register additional initializers, like so: - - ```javascript - Ember.Application.initializer({ - name: "store", - - initialize: function(container, application) { - container.register('store:main', application.Store); - } - }); - ``` - - ### Routing - - In addition to creating your application's router, `Ember.Application` is - also responsible for telling the router when to start routing. Transitions - between routes can be logged with the `LOG_TRANSITIONS` flag, and more - detailed intra-transition logging can be logged with - the `LOG_TRANSITIONS_INTERNAL` flag: - - ```javascript - window.App = Ember.Application.create({ - LOG_TRANSITIONS: true, // basic logging of successful transitions - LOG_TRANSITIONS_INTERNAL: true // detailed logging of all routing steps - }); - ``` - - By default, the router will begin trying to translate the current URL into - application state once the browser emits the `DOMContentReady` event. If you - need to defer routing, you can call the application's `deferReadiness()` - method. Once routing can begin, call the `advanceReadiness()` method. - - If there is any setup required before routing begins, you can implement a - `ready()` method on your app that will be invoked immediately before routing - begins. - ``` - - @class Application - @namespace Ember - @extends Ember.Namespace -*/ - -var Application = Ember.Application = Ember.Namespace.extend(Ember.DeferredMixin, { - - /** - The root DOM element of the Application. This can be specified as an - element or a - [jQuery-compatible selector string](http://api.jquery.com/category/selectors/). - - This is the element that will be passed to the Application's, - `eventDispatcher`, which sets up the listeners for event delegation. Every - view in your application should be a child of the element you specify here. - - @property rootElement - @type DOMElement - @default 'body' - */ - rootElement: 'body', - - /** - The `Ember.EventDispatcher` responsible for delegating events to this - application's views. - - The event dispatcher is created by the application at initialization time - and sets up event listeners on the DOM element described by the - application's `rootElement` property. - - See the documentation for `Ember.EventDispatcher` for more information. - - @property eventDispatcher - @type Ember.EventDispatcher - @default null - */ - eventDispatcher: null, - - /** - The DOM events for which the event dispatcher should listen. - - By default, the application's `Ember.EventDispatcher` listens - for a set of standard DOM events, such as `mousedown` and - `keyup`, and delegates them to your application's `Ember.View` - instances. - - If you would like additional bubbling events to be delegated to your - views, set your `Ember.Application`'s `customEvents` property - to a hash containing the DOM event name as the key and the - corresponding view method name as the value. For example: - - ```javascript - App = Ember.Application.create({ - customEvents: { - // add support for the paste event - paste: "paste" - } - }); - ``` - - @property customEvents - @type Object - @default null - */ - customEvents: null, - - // Start off the number of deferrals at 1. This will be - // decremented by the Application's own `initialize` method. - _readinessDeferrals: 1, - - init: function() { - if (!this.$) { this.$ = Ember.$; } - this.__container__ = this.buildContainer(); - - this.Router = this.defaultRouter(); - - this._super(); - - this.scheduleInitialize(); - - Ember.libraries.registerCoreLibrary('Handlebars', Ember.Handlebars.VERSION); - Ember.libraries.registerCoreLibrary('jQuery', Ember.$().jquery); - - if ( Ember.LOG_VERSION ) { - Ember.LOG_VERSION = false; // we only need to see this once per Application#init - var maxNameLength = Math.max.apply(this, Ember.A(Ember.libraries).mapBy("name.length")); - - Ember.libraries.each(function(name, version) { - var spaces = new Array(maxNameLength - name.length + 1).join(" "); - }); - } - }, - - /** - Build the container for the current application. - - Also register a default application view in case the application - itself does not. - - @private - @method buildContainer - @return {Ember.Container} the configured container - */ - buildContainer: function() { - var container = this.__container__ = Application.buildContainer(this); - - return container; - }, - - /** - If the application has not opted out of routing and has not explicitly - defined a router, supply a default router for the application author - to configure. - - This allows application developers to do: - - ```javascript - var App = Ember.Application.create(); - - App.Router.map(function() { - this.resource('posts'); - }); - ``` - - @private - @method defaultRouter - @return {Ember.Router} the default router - */ - - defaultRouter: function() { - if (this.Router === false) { return; } - var container = this.__container__; - - if (this.Router) { - container.unregister('router:main'); - container.register('router:main', this.Router); - } - - return container.lookupFactory('router:main'); - }, - - /** - Automatically initialize the application once the DOM has - become ready. - - The initialization itself is scheduled on the actions queue - which ensures that application loading finishes before - booting. - - If you are asynchronously loading code, you should call - `deferReadiness()` to defer booting, and then call - `advanceReadiness()` once all of your code has finished - loading. - - @private - @method scheduleInitialize - */ - scheduleInitialize: function() { - var self = this; - - if (!this.$ || this.$.isReady) { - Ember.run.schedule('actions', self, '_initialize'); - } else { - this.$().ready(function runInitialize() { - Ember.run(self, '_initialize'); - }); - } - }, - - /** - Use this to defer readiness until some condition is true. - - Example: - - ```javascript - App = Ember.Application.create(); - App.deferReadiness(); - - jQuery.getJSON("/auth-token", function(token) { - App.token = token; - App.advanceReadiness(); - }); - ``` - - This allows you to perform asynchronous setup logic and defer - booting your application until the setup has finished. - - However, if the setup requires a loading UI, it might be better - to use the router for this purpose. - - @method deferReadiness - */ - deferReadiness: function() { - this._readinessDeferrals++; - }, - - /** - Call `advanceReadiness` after any asynchronous setup logic has completed. - Each call to `deferReadiness` must be matched by a call to `advanceReadiness` - or the application will never become ready and routing will not begin. - - @method advanceReadiness - @see {Ember.Application#deferReadiness} - */ - advanceReadiness: function() { - this._readinessDeferrals--; - - if (this._readinessDeferrals === 0) { - Ember.run.once(this, this.didBecomeReady); - } - }, - - /** - registers a factory for later injection - - Example: - - ```javascript - App = Ember.Application.create(); - - App.Person = Ember.Object.extend({}); - App.Orange = Ember.Object.extend({}); - App.Email = Ember.Object.extend({}); - App.session = Ember.Object.create({}); - - App.register('model:user', App.Person, {singleton: false }); - App.register('fruit:favorite', App.Orange); - App.register('communication:main', App.Email, {singleton: false}); - App.register('session', App.session, {instantiate: false}); - ``` - - @method register - @param fullName {String} type:name (e.g., 'model:user') - @param factory {Function} (e.g., App.Person) - @param options {String} (optional) - **/ - register: function() { - var container = this.__container__; - container.register.apply(container, arguments); - }, - /** - defines an injection or typeInjection - - Example: - - ```javascript - App.inject(, , ) - App.inject('model:user', 'email', 'model:email') - App.inject('model', 'source', 'source:main') - ``` - - @method inject - @param factoryNameOrType {String} - @param property {String} - @param injectionName {String} - **/ - inject: function() { - var container = this.__container__; - container.injection.apply(container, arguments); - }, - - /** - Calling initialize manually is not supported. - - Please see Ember.Application#advanceReadiness and - Ember.Application#deferReadiness. - - @private - @deprecated - @method initialize - **/ - initialize: function() { - }, - /** - Initialize the application. This happens automatically. - - Run any initializers and run the application load hook. These hooks may - choose to defer readiness. For example, an authentication hook might want - to defer readiness until the auth token has been retrieved. - - @private - @method _initialize - */ - _initialize: function() { - if (this.isDestroyed) { return; } - - // At this point, the App.Router must already be assigned - if (this.Router) { - var container = this.__container__; - container.unregister('router:main'); - container.register('router:main', this.Router); - } - - this.runInitializers(); - Ember.runLoadHooks('application', this); - - // At this point, any initializers or load hooks that would have wanted - // to defer readiness have fired. In general, advancing readiness here - // will proceed to didBecomeReady. - this.advanceReadiness(); - - return this; - }, - - /** - Reset the application. This is typically used only in tests. It cleans up - the application in the following order: - - 1. Deactivate existing routes - 2. Destroy all objects in the container - 3. Create a new application container - 4. Re-route to the existing url - - Typical Example: - - ```javascript - - var App; - - Ember.run(function() { - App = Ember.Application.create(); - }); - - module("acceptance test", { - setup: function() { - App.reset(); - } - }); - - test("first test", function() { - // App is freshly reset - }); - - test("first test", function() { - // App is again freshly reset - }); - ``` - - Advanced Example: - - Occasionally you may want to prevent the app from initializing during - setup. This could enable extra configuration, or enable asserting prior - to the app becoming ready. - - ```javascript - - var App; - - Ember.run(function() { - App = Ember.Application.create(); - }); - - module("acceptance test", { - setup: function() { - Ember.run(function() { - App.reset(); - App.deferReadiness(); - }); - } - }); - - test("first test", function() { - ok(true, 'something before app is initialized'); - - Ember.run(function() { - App.advanceReadiness(); - }); - ok(true, 'something after app is initialized'); - }); - ``` - - @method reset - **/ - reset: function() { - this._readinessDeferrals = 1; - - function handleReset() { - var router = this.__container__.lookup('router:main'); - router.reset(); - - Ember.run(this.__container__, 'destroy'); - - this.buildContainer(); - - Ember.run.schedule('actions', this, function() { - this._initialize(); - }); - } - - Ember.run.join(this, handleReset); - }, - - /** - @private - @method runInitializers - */ - runInitializers: function() { - var initializers = get(this.constructor, 'initializers'), - container = this.__container__, - graph = new Ember.DAG(), - namespace = this, - name, initializer; - - for (name in initializers) { - initializer = initializers[name]; - graph.addEdges(initializer.name, initializer.initialize, initializer.before, initializer.after); - } - - graph.topsort(function (vertex) { - var initializer = vertex.value; - initializer(container, namespace); - }); - }, - - /** - @private - @method didBecomeReady - */ - didBecomeReady: function() { - this.setupEventDispatcher(); - this.ready(); // user hook - this.startRouting(); - - if (!Ember.testing) { - // Eagerly name all classes that are already loaded - Ember.Namespace.processAll(); - Ember.BOOTED = true; - } - - this.resolve(this); - }, - - /** - Setup up the event dispatcher to receive events on the - application's `rootElement` with any registered - `customEvents`. - - @private - @method setupEventDispatcher - */ - setupEventDispatcher: function() { - var customEvents = get(this, 'customEvents'), - rootElement = get(this, 'rootElement'), - dispatcher = this.__container__.lookup('event_dispatcher:main'); - - set(this, 'eventDispatcher', dispatcher); - dispatcher.setup(customEvents, rootElement); - }, - - /** - trigger a new call to `route` whenever the URL changes. - If the application has a router, use it to route to the current URL, and - - @private - @method startRouting - @property router {Ember.Router} - */ - startRouting: function() { - var router = this.__container__.lookup('router:main'); - if (!router) { return; } - - router.startRouting(); - }, - - handleURL: function(url) { - var router = this.__container__.lookup('router:main'); - - router.handleURL(url); - }, - - /** - Called when the Application has become ready. - The call will be delayed until the DOM has become ready. - - @event ready - */ - ready: Ember.K, - - /** - @deprecated Use 'Resolver' instead - Set this to provide an alternate class to `Ember.DefaultResolver` - - - @property resolver - */ - resolver: null, - - /** - Set this to provide an alternate class to `Ember.DefaultResolver` - - @property resolver - */ - Resolver: null, - - willDestroy: function() { - Ember.BOOTED = false; - - this.__container__.destroy(); - }, - - initializer: function(options) { - this.constructor.initializer(options); - } -}); - -Ember.Application.reopenClass({ - initializers: {}, - initializer: function(initializer) { - // If this is the first initializer being added to a subclass, we are going to reopen the class - // to make sure we have a new `initializers` object, which extends from the parent class' using - // prototypal inheritance. Without this, attempting to add initializers to the subclass would - // pollute the parent class as well as other subclasses. - if (this.superclass.initializers !== undefined && this.superclass.initializers === this.initializers) { - this.reopenClass({ - initializers: Ember.create(this.initializers) - }); - } - - - this.initializers[initializer.name] = initializer; - }, - - /** - This creates a container with the default Ember naming conventions. - - It also configures the container: - - * registered views are created every time they are looked up (they are - not singletons) - * registered templates are not factories; the registered value is - returned directly. - * the router receives the application as its `namespace` property - * all controllers receive the router as their `target` and `controllers` - properties - * all controllers receive the application as their `namespace` property - * the application view receives the application controller as its - `controller` property - * the application view receives the application template as its - `defaultTemplate` property - - @private - @method buildContainer - @static - @param {Ember.Application} namespace the application to build the - container for. - @return {Ember.Container} the built container - */ - buildContainer: function(namespace) { - var container = new Ember.Container(); - - Ember.Container.defaultContainer = new DeprecatedContainer(container); - - container.set = Ember.set; - container.resolver = resolverFor(namespace); - container.normalize = container.resolver.normalize; - container.describe = container.resolver.describe; - container.makeToString = container.resolver.makeToString; - - container.optionsForType('component', { singleton: false }); - container.optionsForType('view', { singleton: false }); - container.optionsForType('template', { instantiate: false }); - container.optionsForType('helper', { instantiate: false }); - - container.register('application:main', namespace, { instantiate: false }); - - container.register('controller:basic', Ember.Controller, { instantiate: false }); - container.register('controller:object', Ember.ObjectController, { instantiate: false }); - container.register('controller:array', Ember.ArrayController, { instantiate: false }); - container.register('route:basic', Ember.Route, { instantiate: false }); - container.register('event_dispatcher:main', Ember.EventDispatcher); - - container.register('router:main', Ember.Router); - container.injection('router:main', 'namespace', 'application:main'); - - container.injection('controller', 'target', 'router:main'); - container.injection('controller', 'namespace', 'application:main'); - - container.injection('route', 'router', 'router:main'); - - return container; - } -}); - -/** - This function defines the default lookup rules for container lookups: - - * templates are looked up on `Ember.TEMPLATES` - * other names are looked up on the application after classifying the name. - For example, `controller:post` looks up `App.PostController` by default. - * if the default lookup fails, look for registered classes on the container - - This allows the application to register default injections in the container - that could be overridden by the normal naming convention. - - @private - @method resolverFor - @param {Ember.Namespace} namespace the namespace to look for classes - @return {*} the resolved value for a given lookup -*/ -function resolverFor(namespace) { - if (namespace.get('resolver')) { - } - - var ResolverClass = namespace.get('resolver') || namespace.get('Resolver') || Ember.DefaultResolver; - var resolver = ResolverClass.create({ - namespace: namespace - }); - - function resolve(fullName) { - return resolver.resolve(fullName); - } - - resolve.describe = function(fullName) { - return resolver.lookupDescription(fullName); - }; - - resolve.makeToString = function(factory, fullName) { - return resolver.makeToString(factory, fullName); - }; - - resolve.normalize = function(fullName) { - if (resolver.normalize) { - return resolver.normalize(fullName); - } else { - return fullName; - } - }; - - return resolve; -} - -Ember.runLoadHooks('Ember.Application', Ember.Application); - -})(); - - - -(function() { - -})(); - - - -(function() { -/** -@module ember -@submodule ember-application -*/ - -var get = Ember.get, set = Ember.set; - -function verifyNeedsDependencies(controller, container, needs) { - var dependency, i, l, missing = []; - - for (i=0, l=needs.length; i 1 ? 'they' : 'it') + " could not be found"); - } -} - -var defaultControllersComputedProperty = Ember.computed(function() { - var controller = this; - - return { - needs: get(controller, 'needs'), - container: get(controller, 'container'), - unknownProperty: function(controllerName) { - var needs = this.needs, - dependency, i, l; - for (i=0, l=needs.length; i 0) { - - if (this.container) { - verifyNeedsDependencies(this, this.container, needs); - } - - // if needs then initialize controllers proxy - get(this, 'controllers'); - } - - this._super.apply(this, arguments); - }, - - /** - @method controllerFor - @see {Ember.Route#controllerFor} - @deprecated Use `needs` instead - */ - controllerFor: function(controllerName) { - return Ember.controllerFor(get(this, 'container'), controllerName); - }, - - /** - Stores the instances of other controllers available from within - this controller. Any controller listed by name in the `needs` - property will be accessible by name through this property. - - ```javascript - App.CommentsController = Ember.ArrayController.extend({ - needs: ['post'], - postTitle: function(){ - var currentPost = this.get('controllers.post'); // instance of App.PostController - return currentPost.get('title'); - }.property('controllers.post.title') - }); - ``` - - @see {Ember.ControllerMixin#needs} - @property {Object} controllers - @default null - */ - controllers: defaultControllersComputedProperty -}); - -})(); - - - -(function() { - -})(); - - - -(function() { -/** -Ember Application - -@module ember -@submodule ember-application -@requires ember-views, ember-routing -*/ - -})(); - -(function() { -/** -@module ember -@submodule ember-extension-support -*/ -/** - The `DataAdapter` helps a data persistence library - interface with tools that debug Ember such - as the [Ember Extension](https://github.com/tildeio/ember-extension) - for Chrome and Firefox. - - This class will be extended by a persistence library - which will override some of the methods with - library-specific code. - - The methods likely to be overridden are: - - * `getFilters` - * `detect` - * `columnsForType` - * `getRecords` - * `getRecordColumnValues` - * `getRecordKeywords` - * `getRecordFilterValues` - * `getRecordColor` - * `observeRecord` - - The adapter will need to be registered - in the application's container as `dataAdapter:main` - - Example: - - ```javascript - Application.initializer({ - name: "dataAdapter", - - initialize: function(container, application) { - application.register('dataAdapter:main', DS.DataAdapter); - } - }); - ``` - - @class DataAdapter - @namespace Ember - @extends Ember.Object -*/ -Ember.DataAdapter = Ember.Object.extend({ - init: function() { - this._super(); - this.releaseMethods = Ember.A(); - }, - - /** - The container of the application being debugged. - This property will be injected - on creation. - - @property container - @default null - */ - container: null, - - /** - Number of attributes to send - as columns. (Enough to make the record - identifiable). - - @private - @property attributeLimit - @default 3 - */ - attributeLimit: 3, - - /** - Stores all methods that clear observers. - These methods will be called on destruction. - - @private - @property releaseMethods - */ - releaseMethods: Ember.A(), - - /** - Specifies how records can be filtered. - Records returned will need to have a `filterValues` - property with a key for every name in the returned array. - - @public - @method getFilters - @return {Array} List of objects defining filters. - The object should have a `name` and `desc` property. - */ - getFilters: function() { - return Ember.A(); - }, - - /** - Fetch the model types and observe them for changes. - - @public - @method watchModelTypes - - @param {Function} typesAdded Callback to call to add types. - Takes an array of objects containing wrapped types (returned from `wrapModelType`). - - @param {Function} typesUpdated Callback to call when a type has changed. - Takes an array of objects containing wrapped types. - - @return {Function} Method to call to remove all observers - */ - watchModelTypes: function(typesAdded, typesUpdated) { - var modelTypes = this.getModelTypes(), - self = this, typesToSend, releaseMethods = Ember.A(); - - typesToSend = modelTypes.map(function(type) { - var wrapped = self.wrapModelType(type); - releaseMethods.push(self.observeModelType(type, typesUpdated)); - return wrapped; - }); - - typesAdded(typesToSend); - - var release = function() { - releaseMethods.forEach(function(fn) { fn(); }); - self.releaseMethods.removeObject(release); - }; - this.releaseMethods.pushObject(release); - return release; - }, - - /** - Fetch the records of a given type and observe them for changes. - - @public - @method watchRecords - - @param {Function} recordsAdded Callback to call to add records. - Takes an array of objects containing wrapped records. - The object should have the following properties: - columnValues: {Object} key and value of a table cell - object: {Object} the actual record object - - @param {Function} recordsUpdated Callback to call when a record has changed. - Takes an array of objects containing wrapped records. - - @param {Function} recordsRemoved Callback to call when a record has removed. - Takes the following parameters: - index: the array index where the records were removed - count: the number of records removed - - @return {Function} Method to call to remove all observers - */ - watchRecords: function(type, recordsAdded, recordsUpdated, recordsRemoved) { - var self = this, releaseMethods = Ember.A(), records = this.getRecords(type), release; - - var recordUpdated = function(updatedRecord) { - recordsUpdated([updatedRecord]); - }; - - var recordsToSend = records.map(function(record) { - releaseMethods.push(self.observeRecord(record, recordUpdated)); - return self.wrapRecord(record); - }); - - - var contentDidChange = function(array, idx, removedCount, addedCount) { - for (var i = idx; i < idx + addedCount; i++) { - var record = array.objectAt(i); - var wrapped = self.wrapRecord(record); - releaseMethods.push(self.observeRecord(record, recordUpdated)); - recordsAdded([wrapped]); - } - - if (removedCount) { - recordsRemoved(idx, removedCount); - } - }; - - var observer = { didChange: contentDidChange, willChange: Ember.K }; - records.addArrayObserver(self, observer); - - release = function() { - releaseMethods.forEach(function(fn) { fn(); }); - records.removeArrayObserver(self, observer); - self.releaseMethods.removeObject(release); - }; - - recordsAdded(recordsToSend); - - this.releaseMethods.pushObject(release); - return release; - }, - - /** - Clear all observers before destruction - @private - */ - willDestroy: function() { - this._super(); - this.releaseMethods.forEach(function(fn) { - fn(); - }); - }, - - /** - Detect whether a class is a model. - - Test that against the model class - of your persistence library - - @private - @method detect - @param {Class} klass The class to test - @return boolean Whether the class is a model class or not - */ - detect: function(klass) { - return false; - }, - - /** - Get the columns for a given model type. - - @private - @method columnsForType - @param {Class} type The model type - @return {Array} An array of columns of the following format: - name: {String} name of the column - desc: {String} Humanized description (what would show in a table column name) - */ - columnsForType: function(type) { - return Ember.A(); - }, - - /** - Adds observers to a model type class. - - @private - @method observeModelType - @param {Class} type The model type class - @param {Function} typesUpdated Called when a type is modified. - @return {Function} The function to call to remove observers - */ - - observeModelType: function(type, typesUpdated) { - var self = this, records = this.getRecords(type); - - var onChange = function() { - typesUpdated([self.wrapModelType(type)]); - }; - var observer = { - didChange: function() { - Ember.run.scheduleOnce('actions', this, onChange); - }, - willChange: Ember.K - }; - - records.addArrayObserver(this, observer); - - var release = function() { - records.removeArrayObserver(self, observer); - }; - - return release; - }, - - - /** - Wraps a given model type and observes changes to it. - - @private - @method wrapModelType - @param {Class} type A model class - @param {Function} typesUpdated callback to call when the type changes - @return {Object} contains the wrapped type and the function to remove observers - Format: - type: {Object} the wrapped type - The wrapped type has the following format: - name: {String} name of the type - count: {Integer} number of records available - columns: {Columns} array of columns to describe the record - object: {Class} the actual Model type class - release: {Function} The function to remove observers - */ - wrapModelType: function(type, typesUpdated) { - var release, records = this.getRecords(type), - typeToSend, self = this; - - typeToSend = { - name: type.toString(), - count: Ember.get(records, 'length'), - columns: this.columnsForType(type), - object: type - }; - - - return typeToSend; - }, - - - /** - Fetches all models defined in the application. - - @private - @method getModelTypes - @return {Array} Array of model types - */ - - // TODO: Use the resolver instead of looping over namespaces. - getModelTypes: function() { - var namespaces = Ember.A(Ember.Namespace.NAMESPACES), types = Ember.A(), self = this; - - namespaces.forEach(function(namespace) { - for (var key in namespace) { - if (!namespace.hasOwnProperty(key)) { continue; } - var klass = namespace[key]; - if (self.detect(klass)) { - types.push(klass); - } - } - }); - return types; - }, - - /** - Fetches all loaded records for a given type. - - @private - @method getRecords - @return {Array} An array of records. - This array will be observed for changes, - so it should update when new records are added/removed. - */ - getRecords: function(type) { - return Ember.A(); - }, - - /** - Wraps a record and observers changes to it. - - @private - @method wrapRecord - @param {Object} record The record instance. - @return {Object} The wrapped record. Format: - columnValues: {Array} - searchKeywords: {Array} - */ - wrapRecord: function(record) { - var recordToSend = { object: record }, columnValues = {}, self = this; - - recordToSend.columnValues = this.getRecordColumnValues(record); - recordToSend.searchKeywords = this.getRecordKeywords(record); - recordToSend.filterValues = this.getRecordFilterValues(record); - recordToSend.color = this.getRecordColor(record); - - return recordToSend; - }, - - /** - Gets the values for each column. - - @private - @method getRecordColumnValues - @return {Object} Keys should match column names defined - by the model type. - */ - getRecordColumnValues: function(record) { - return {}; - }, - - /** - Returns keywords to match when searching records. - - @private - @method getRecordKeywords - @return {Array} Relevant keywords for search. - */ - getRecordKeywords: function(record) { - return Ember.A(); - }, - - /** - Returns the values of filters defined by `getFilters`. - - @private - @method getRecordFilterValues - @param {Object} record The record instance - @return {Object} The filter values - */ - getRecordFilterValues: function(record) { - return {}; - }, - - /** - Each record can have a color that represents its state. - - @private - @method getRecordColor - @param {Object} record The record instance - @return {String} The record's color - Possible options: black, red, blue, green - */ - getRecordColor: function(record) { - return null; - }, - - /** - Observes all relevant properties and re-sends the wrapped record - when a change occurs. - - @private - @method observerRecord - @param {Object} record The record instance - @param {Function} recordUpdated The callback to call when a record is updated. - @return {Function} The function to call to remove all observers. - */ - observeRecord: function(record, recordUpdated) { - return function(){}; - } - -}); - - -})(); - - - -(function() { -/** -Ember Extension Support - -@module ember -@submodule ember-extension-support -@requires ember-application -*/ - -})(); - - -})(); - - -if (typeof location !== 'undefined' && (location.hostname === 'localhost' || location.hostname === '127.0.0.1')) { - Ember.Logger.warn("You are running a production build of Ember on localhost and won't receive detailed error messages. "+ - "If you want full error messages please use the non-minified build provided on the Ember website."); -} diff --git a/perf/todomvc-benchmark/todomvc/architecture-examples/emberjs/index.html b/perf/todomvc-benchmark/todomvc/architecture-examples/emberjs/index.html index fdae3ce085..8c6172ce97 100644 --- a/perf/todomvc-benchmark/todomvc/architecture-examples/emberjs/index.html +++ b/perf/todomvc-benchmark/todomvc/architecture-examples/emberjs/index.html @@ -62,8 +62,8 @@

    todos

    - - + +