language
stringclasses
1 value
owner
stringlengths
2
15
repo
stringlengths
2
21
sha
stringlengths
45
45
message
stringlengths
7
36.3k
path
stringlengths
1
199
patch
stringlengths
15
102k
is_multipart
bool
2 classes
Other
emberjs
ember.js
e996eacc3c684814b534fce469f37b4579846b62.json
Finalize CHANGELOG for 1.8.0.
CHANGELOG.md
@@ -4,8 +4,29 @@ * [BREAKING] Require Handlebars 2.0. See [blog post](http://emberjs.com/blog/2014/10/16/handlebars-update.html) for details. -### Ember 1.8.0-beta.3 (September, 27, 2014) - +### Ember 1.8.0 (October, 28, 2014) + +* [BUGFIX] Ensure published builds do not use `define` or `require` internally. +* [BUGFIX] Remove strict mode for Object.create usage to work around an [iOS bug](https://bugs.webkit.org/show_bug.cgi?id=138038). +* Enable testing of production builds by publishing `ember-testing.js` along with the standard builds. +* [DOC] Make mandatory setter assertions more helpful. +* Deprecate location: 'hash' paths that don't have a forward slash. e.g. #foo vs. #/foo. +* [BUGFIX] Ensure `Ember.setProperties` can handle non-object properties. +* [BUGFIX] Refactor buffer to be simpler, single parsing code-path. +* [BUGFIX] Add assertion when morph is not found in RenderBuffer. +* [BUGFIX] Make computed.sort generate an answer immediately. +* [BUGFIX] Fix broken `Ember.computed.sort` semantics. +* [BUGFIX] Ensure ember-testing is not included in production build output. +* Deprecate usage of quoted paths in `{{view}}` helper. +* [BUGFIX] Ensure `{{view}}` lookup works properly when name is a keyword. +* [BUGFIX] Ensure `Ember.Map` works properly with falsey values. +* [BUGFIX] Make Ember.Namespace#toString ember-cli aware. +* [PERF] Avoid using `for x in y` in `Ember.RenderBuffer.prototype.add`. +* [BUGFIX] Enable setProperties to work on Object.create(null) objects. +* [PERF] Update RSVP to 3.0.14 (faster instrumentation). +* [BUGFIX] Add SVG support for metal-views. +* [BUGFIX] Allow camelCase attributes in DOM elements. +* [BUGFIX] Update backburner to latest. * [BUGFIX] Use contextualElements to properly handle omitted optional start tags. * [BUGFIX] Ensure that `Route.prototype.activate` is not retriggered when the model for the current route changes. * [PERF] Fix optimization bailouts for `{{view}}` helper. @@ -23,10 +44,6 @@ * [ES6] Remove length in-favor of size. * [ES6] Throw if constructor is invoked without new * [ES6] Make inheritance work correctly - - -### Ember 1.8.0-beta.2 (September, 20, 2014) - * [BUGFIX] Allow for bound property {{input}} type. * [BUGFIX] Ensure pushUnique targetQueue is cleared by flush. * [BUGFIX] instrument should still call block even without subscribers. @@ -38,9 +55,6 @@ * [PERF] Extracts computed property set into a separate function. * [BUGFIX] Make `GUID_KEY = intern(GUID_KEY)` actually work on ES3. * [BUGFIX] Ensure nested routes can inherit model from parent. - -### Ember 1.8.0-beta.1 (August 20, 2014) - * Remove `metamorph` in favor of `morph` package (removes the need for `<script>` tags in the DOM). * [FEATURE] ember-routing-linkto-target-attribute * [FEATURE] ember-routing-multi-current-when
false
Other
emberjs
ember.js
1647fdd3ccdce1502ab7e9041c77b2136beba32e.json
Ensure consistent use of Ember.create.
packages/ember-application/lib/system/application.js
@@ -794,7 +794,7 @@ var Application = Namespace.extend(DeferredMixin, { }); Application.reopenClass({ - initializers: Object.create(null), + initializers: create(null), /** Initializer receives an object which has the following attributes:
true
Other
emberjs
ember.js
1647fdd3ccdce1502ab7e9041c77b2136beba32e.json
Ensure consistent use of Ember.create.
packages/ember-metal-views/tests/test_helpers.js
@@ -1,3 +1,4 @@ +import { create } from "ember-metal/platform"; import { Renderer } from "ember-metal-views"; var renderer; @@ -6,7 +7,7 @@ function MetalRenderer () { MetalRenderer._super.call(this); } MetalRenderer._super = Renderer; -MetalRenderer.prototype = Object.create(Renderer.prototype, { +MetalRenderer.prototype = create(Renderer.prototype, { constructor: { value: MetalRenderer, enumerable: false,
true
Other
emberjs
ember.js
1647fdd3ccdce1502ab7e9041c77b2136beba32e.json
Ensure consistent use of Ember.create.
packages/ember-metal/lib/dictionary.js
@@ -1,10 +1,12 @@ +import { create } from "ember-metal/platform"; + // the delete is meant to hint at runtimes that this object should remain in // dictionary mode. This is clearly a runtime specific hack, but currently it // appears worthwile in some usecases. Please note, these deletes do increase // the cost of creation dramatically over a plain Object.create. And as this // only makes sense for long-lived dictionaries that aren't instantiated often. export default function makeDictionary(parent) { - var dict = Object.create(parent); + var dict = create(parent); dict['_dict'] = null; delete dict['_dict']; return dict;
true
Other
emberjs
ember.js
1647fdd3ccdce1502ab7e9041c77b2136beba32e.json
Ensure consistent use of Ember.create.
packages/ember-metal/lib/map.js
@@ -34,7 +34,7 @@ function missingNew(name) { } function copyNull(obj) { - var output = Object.create(null); + var output = create(null); for (var prop in obj) { // hasOwnPropery is not needed because obj is Object.create(null); @@ -92,7 +92,7 @@ OrderedSet.prototype = { @method clear */ clear: function() { - this.presenceSet = Object.create(null); + this.presenceSet = create(null); this.list = []; this.size = 0; }, @@ -256,7 +256,7 @@ function Map() { if (this instanceof this.constructor) { this.keys = OrderedSet.create(); this.keys._silenceRemoveDeprecation = true; - this.values = Object.create(null); + this.values = create(null); this.size = 0; } else { missingNew("OrderedSet"); @@ -418,7 +418,7 @@ Map.prototype = { */ clear: function() { this.keys.clear(); - this.values = Object.create(null); + this.values = create(null); this.size = 0; },
true
Other
emberjs
ember.js
1647fdd3ccdce1502ab7e9041c77b2136beba32e.json
Ensure consistent use of Ember.create.
packages/ember-metal/lib/mixin.js
@@ -333,7 +333,7 @@ function connectStreamBinding(obj, key, stream) { stream.subscribe(onNotify); if (obj._streamBindingSubscriptions === undefined) { - obj._streamBindingSubscriptions = Object.create(null); + obj._streamBindingSubscriptions = o_create(null); } obj._streamBindingSubscriptions[key] = onNotify;
true
Other
emberjs
ember.js
1647fdd3ccdce1502ab7e9041c77b2136beba32e.json
Ensure consistent use of Ember.create.
packages/ember-metal/lib/streams/stream.js
@@ -1,3 +1,4 @@ +import { create } from "ember-metal/platform"; import { getFirstKey, getTailPath @@ -23,7 +24,7 @@ Stream.prototype = { var tailPath = getTailPath(path); if (this.children === undefined) { - this.children = Object.create(null); + this.children = create(null); } var keyStream = this.children[firstKey];
true
Other
emberjs
ember.js
1647fdd3ccdce1502ab7e9041c77b2136beba32e.json
Ensure consistent use of Ember.create.
packages/ember-routing/lib/system/router.js
@@ -19,6 +19,7 @@ import { getActiveTargetName, stashParamNames } from "ember-routing/utils"; +import { create } from "ember-metal/platform"; /** @module ember @@ -319,7 +320,7 @@ var EmberRouter = EmberObject.extend(Evented, { }, _getHandlerFunction: function() { - var seen = Object.create(null); + var seen = create(null); var container = this.container; var DefaultRoute = container.lookupFactory('route:basic'); var self = this;
true
Other
emberjs
ember.js
1647fdd3ccdce1502ab7e9041c77b2136beba32e.json
Ensure consistent use of Ember.create.
packages/ember-runtime/tests/core/copy_test.js
@@ -1,3 +1,4 @@ +import { create } from "ember-metal/platform"; import copy from "ember-runtime/copy"; QUnit.module("Ember Copy Method"); @@ -16,7 +17,7 @@ test("Ember.copy date", function() { }); test("Ember.copy null prototype object", function() { - var obj = Object.create(null); + var obj = create(null); obj.foo = 'bar';
true
Other
emberjs
ember.js
1647fdd3ccdce1502ab7e9041c77b2136beba32e.json
Ensure consistent use of Ember.create.
packages/ember-views/lib/system/render_buffer.js
@@ -6,6 +6,7 @@ import jQuery from "ember-views/system/jquery"; import { DOMHelper } from "morph"; import Ember from "ember-metal/core"; +import { create } from "ember-metal/platform"; // The HTML spec allows for "omitted start tags". These tags are optional // when their intended child is the first thing in the parent tag. For @@ -54,7 +55,7 @@ function detectOmittedStartTag(string, contextualElement){ } function ClassSet() { - this.seen = Object.create(null); + this.seen = create(null); this.list = []; }
true
Other
emberjs
ember.js
1647fdd3ccdce1502ab7e9041c77b2136beba32e.json
Ensure consistent use of Ember.create.
packages/ember-views/lib/views/view.js
@@ -3,6 +3,7 @@ // Ember.ContainerView circular dependency // Ember.ENV import Ember from 'ember-metal/core'; +import { create } from 'ember-metal/platform'; import Evented from "ember-runtime/mixins/evented"; import EmberObject from "ember-runtime/system/object"; @@ -1709,7 +1710,7 @@ var View = CoreView.extend({ this._streamBindings = undefined; if (!this._keywords) { - this._keywords = Object.create(null); + this._keywords = create(null); } this._keywords.view = new SimpleStream(); this._keywords._view = this; @@ -2006,7 +2007,7 @@ var View = CoreView.extend({ _getBindingForStream: function(path) { if (this._streamBindings === undefined) { - this._streamBindings = Object.create(null); + this._streamBindings = create(null); this.one('willDestroyElement', this, this._destroyStreamBindings); }
true
Other
emberjs
ember.js
cfe3dbf4bdbfb62d0256f3cb55efefe2ed19aa37.json
Remove DAG implementation. As of https://github.com/emberjs/ember.js/pull/5677 the DAG is pulled in from Bower, this file is no longer needed.
packages/ember-application/lib/system/dag.js
@@ -1,181 +0,0 @@ -import EmberError from "ember-metal/error"; - -function visit(vertex, fn, visited, path) { - var name = vertex.name; - var vertices = vertex.incoming; - var names = vertex.incomingNames; - var len = names.length; - var 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(); -} - - -/** - * DAG stands for Directed acyclic graph. - * - * It is used to build a graph of dependencies checking that there isn't circular - * dependencies. p.e Registering initializers with a certain precedence order. - * - * @class DAG - * @constructor - */ -function DAG() { - this.names = []; - this.vertices = Object.create(null); -} - -/** - * DAG Vertex - * - * @class Vertex - * @constructor - */ - -function Vertex(name) { - this.name = name; - this.incoming = {}; - this.incomingNames = []; - this.hasOutgoing = false; - this.value = null; -} - -/** - * Adds a vertex entry to the graph unless it is already added. - * - * @private - * @method add - * @param {String} name The name of the vertex to add - */ -DAG.prototype.add = function(name) { - if (!name) { - throw new Error("Can't add Vertex without name"); - } - if (this.vertices[name] !== undefined) { - return this.vertices[name]; - } - var vertex = new Vertex(name); - this.vertices[name] = vertex; - this.names.push(name); - return vertex; -}; - -/** - * Adds a vertex to the graph and sets its value. - * - * @private - * @method map - * @param {String} name The name of the vertex. - * @param value The value to put in the vertex. - */ -DAG.prototype.map = function(name, value) { - this.add(name).value = value; -}; - -/** - * Connects the vertices with the given names, adding them to the graph if - * necessary, only if this does not produce is any circular dependency. - * - * @private - * @method addEdge - * @param {String} fromName The name the vertex where the edge starts. - * @param {String} toName The name the vertex where the edge ends. - */ -DAG.prototype.addEdge = function(fromName, toName) { - if (!fromName || !toName || fromName === toName) { - return; - } - var from = this.add(fromName); - var to = this.add(toName); - if (to.incoming.hasOwnProperty(fromName)) { - return; - } - function checkCycle(vertex, path) { - if (vertex.name === toName) { - throw new EmberError("cycle detected: " + toName + " <- " + path.join(" <- ")); - } - } - visit(from, checkCycle); - from.hasOutgoing = true; - to.incoming[fromName] = from; - to.incomingNames.push(fromName); -}; - -/** - * Visits all the vertex of the graph calling the given function with each one, - * ensuring that the vertices are visited respecting their precedence. - * - * @method topsort - * @param {Function} fn The function to be invoked on each vertex. - */ -DAG.prototype.topsort = function(fn) { - var visited = {}; - var vertices = this.vertices; - var names = this.names; - var len = names.length; - var i, vertex; - - for (i = 0; i < len; i++) { - vertex = vertices[names[i]]; - if (!vertex.hasOutgoing) { - visit(vertex, fn, visited); - } - } -}; - -/** - * Adds a vertex with the given name and value to the graph and joins it with the - * vertices referenced in _before_ and _after_. If there isn't vertices with those - * names, they are added too. - * - * If either _before_ or _after_ are falsy/empty, the added vertex will not have - * an incoming/outgoing edge. - * - * @method addEdges - * @param {String} name The name of the vertex to be added. - * @param value The value of that vertex. - * @param before An string or array of strings with the names of the vertices before - * which this vertex must be visited. - * @param after An string or array of strings with the names of the vertex after - * which this vertex must be 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); - } - } - } -}; - -export default DAG;
false
Other
emberjs
ember.js
1388cc09b4130ac4266de2e58ef3918b524b4d4b.json
Remove code-climate complains
Brocfile.js
@@ -2,7 +2,6 @@ var fs = require('fs'); var util = require('util'); -var path = require('path'); var pickFiles = require('broccoli-static-compiler'); var transpileES6 = require('broccoli-es6-module-transpiler'); var mergeTrees = require('broccoli-merge-trees'); @@ -52,9 +51,9 @@ var inlineTemplatePrecompiler = require('./lib/broccoli-ember-inline-template-pr The `...` and if block would be stripped out of final output unless `features.json` has `ember-metal-is-present` set to true. */ -function defeatureifyConfig(options) { +function defeatureifyConfig(opts) { var stripDebug = false; - var options = options || {}; + var options = opts || {}; var configJson = JSON.parse(fs.readFileSync("features.json").toString()); var features = options.features || configJson.features; @@ -139,7 +138,7 @@ function concatES6(sourceTrees, options) { /* In order to ensure that tree is compliant with older Javascript versions we recast these trees here. For example, in ie6 the following would be an -error: + error: ``` {default: "something"}.default @@ -432,9 +431,7 @@ function es6Package(packageName) { compiledTrees = mergeTrees(compiledTrees); - /* - Memoizes trees. Guard above ensures that if this is set will automatically return. - */ + // Memoizes trees. Guard above ensures that if this is set will automatically return. pkg['trees'] = {lib: libTree, compiledTree: compiledTrees, vendorTrees: vendorTrees}; // tests go boom if you try to pick them and they don't exists @@ -561,7 +558,7 @@ function htmlbarsPackage(packageName) { /* Relies on bower to install other Ember micro libs. Assumes that /lib is available and contains all the necessary ES6 modules necessary for the library -to be required. And compiles them. + to be required. And compiles them. */ function vendoredEs6Package(packageName) { var tree = pickFiles('bower_components/' + packageName + '/lib', {
false
Other
emberjs
ember.js
fc68c8487b8b2068a0cb9634a3f20ee06e391049.json
Allow more configurability in production builds. ``` DISABLE_ES3=true DISABLE_JSHINT=true DISABLE_MIN=true ember serve --environment=production ``` Takes initial production build time from 70s to 21s, and rebuilds from 6s to 2s.
Brocfile.js
@@ -18,8 +18,15 @@ var es3recast = require('broccoli-es3-safe-recast'); var getVersion = require('git-repo-version'); +// To create fast production builds (without ES3 support, minification, or JSHint) +// run the following: +// +// DISABLE_ES3=true DISABLE_JSHINT=true DISABLE_MIN=true ember serve --environment=production + var env = process.env.EMBER_ENV || 'development'; -var disableJSHint = !!process.env.NO_JSHINT || false; +var disableJSHint = !!process.env.DISABLE_JSHINT || false; +var disableES3 = !!process.env.DISABLE_ES3 || false; +var disableMin = !!process.env.DISABLE_MIN || false; var disableDefeatureify; if (process.env.DEFEATUREIFY === 'true') { @@ -102,7 +109,7 @@ function vendoredPackage(packageName) { destFile: '/' + packageName + '.js' }); - if (env !== 'development') { + if (env !== 'development' && !disableES3) { sourceTree = es3recast(sourceTree); } @@ -144,7 +151,7 @@ error: {default: "something"}['default'] ``` */ - if (options.es3Safe) { + if (options.es3Safe && !disableES3) { sourceTrees = es3recast(sourceTrees); } @@ -565,7 +572,7 @@ function vendoredEs6Package(packageName) { moduleName: true }); - if (env !== 'development') { + if (env !== 'development' && !disableES3) { sourceTree = es3recast(sourceTree); } @@ -678,7 +685,10 @@ var distTrees = [templateCompilerTree, compiledSource, compiledTests, testConfig if (env !== 'development') { distTrees.push(prodCompiledSource); distTrees.push(prodCompiledTests); - distTrees.push(minCompiledSource); + + if (!disableMin) { + distTrees.push(minCompiledSource); + } distTrees.push(buildRuntimeTree()); }
false
Other
emberjs
ember.js
38c7307cc70fedb9c8554b140f7c187548f140a2.json
Add a test for a bug fixed on beta
packages/ember-handlebars/tests/helpers/bound_helper_test.js
@@ -44,6 +44,18 @@ QUnit.module("Handlebars bound helpers", { } }); +test("primitives should work correctly", function() { + view = EmberView.create({ + prims: Ember.A(["string", 12]), + + template: compile('{{#each view.prims}}{{#if this}}inside-if{{/if}}{{#with this}}inside-with{{/with}}{{/each}}') + }); + + appendView(view); + + equal(view.$().text(), 'inside-ifinside-withinside-ifinside-with'); +}); + test("should update bound helpers when properties change", function() { EmberHandlebars.helper('capitalize', function(value) { return value.toUpperCase();
false
Other
emberjs
ember.js
4d5c7c2d8f6fb06ca7dff09e674c9ce1db858344.json
Remove mocha since is not used anymore
.travis.yml
@@ -16,7 +16,6 @@ after_success: - "./bin/bower_ember_build" script: - npm test - - npm run-script test-node env: global:
true
Other
emberjs
ember.js
4d5c7c2d8f6fb06ca7dff09e674c9ce1db858344.json
Remove mocha since is not used anymore
package.json
@@ -8,7 +8,6 @@ "pretest": "ember build --environment production", "test": "bin/run-tests.js", "start": "ember serve", - "test-node": "mocha tests/**/*test.js", "docs": "ember yuidoc" }, "devDependencies": { @@ -41,7 +40,6 @@ "express": "^4.5.0", "glob": "~3.2.8", "handlebars": "^2.0", - "mocha": "1.20.1", "ncp": "~0.5.1", "rimraf": "~2.2.8", "rsvp": "~3.0.6"
true
Other
emberjs
ember.js
09cd3335c85c9b1dd5d20f996d5771f541c55ca3.json
Change variable naming
packages/ember-metal/lib/set_properties.js
@@ -18,20 +18,20 @@ import keys from "ember-metal/keys"; ``` @method setProperties - @param self - @param {Object} hash - @return self + @param obj + @param {Object} properties + @return obj */ -export default function setProperties(self, hash) { +export default function setProperties(obj, properties) { changeProperties(function() { - var props = keys(hash); - var prop; + var props = keys(properties); + var propertyName; for (var i = 0, l = props.length; i < l; i++) { - prop = props[i]; + propertyName = props[i]; - set(self, prop, hash[prop]); + set(obj, propertyName, properties[propertyName]); } }); - return self; + return obj; }
false
Other
emberjs
ember.js
80bbf7b27ca105b4d487fce50f93c41833b6e6ee.json
Log unhandled promise rejections in testing #9376
packages/ember-runtime/lib/ext/rsvp.js
@@ -51,6 +51,7 @@ RSVP.onerrorDefault = function (error) { if (Test && Test.adapter) { Test.adapter.exception(error); + Logger.error(error.stack); } else { throw error; }
false
Other
emberjs
ember.js
19024da35c4eac10f25685b02cfe4d68ca515e2c.json
Add component invocation from Handlebars tests.
packages/ember-handlebars/tests/views/component_test.js
@@ -0,0 +1,88 @@ +import EmberView from "ember-views/views/view"; +import Container from 'container/container'; +import run from "ember-metal/run_loop"; +import jQuery from "ember-views/system/jquery"; +import EmberHandlebars from 'ember-handlebars-compiler'; +import ComponentLookup from 'ember-handlebars/component_lookup'; + +var compile = EmberHandlebars.compile; +var container, view; + +QUnit.module('component - invocation', { + setup: function() { + container = new Container(); + container.optionsForType('component', { singleton: false }); + container.optionsForType('view', { singleton: false }); + container.optionsForType('template', { instantiate: false }); + container.optionsForType('helper', { instantiate: false }); + container.register('component-lookup:main', ComponentLookup); + }, + + teardown: function() { + run(container, 'destroy'); + + if (view) { + run(view, 'destroy'); + } + } +}); + +test('non-block without properties', function() { + expect(1); + + container.register('template:components/non-block', compile('In layout')); + + view = EmberView.extend({ + template: compile('{{non-block}}'), + container: container + }).create(); + + run(view, 'appendTo', '#qunit-fixture'); + + equal(jQuery('#qunit-fixture').text(), 'In layout'); +}); + +test('block without properties', function() { + expect(1); + + container.register('template:components/with-block', compile('In layout - {{yield}}')); + + view = EmberView.extend({ + template: compile('{{#with-block}}In template{{/with-block}}'), + container: container + }).create(); + + run(view, 'appendTo', '#qunit-fixture'); + + equal(jQuery('#qunit-fixture').text(), 'In layout - In template'); +}); + +test('non-block with properties', function() { + expect(1); + + container.register('template:components/non-block', compile('In layout - someProp: {{someProp}}')); + + view = EmberView.extend({ + template: compile('{{non-block someProp="something here"}}'), + container: container + }).create(); + + run(view, 'appendTo', '#qunit-fixture'); + + equal(jQuery('#qunit-fixture').text(), 'In layout - someProp: something here'); +}); + +test('block with properties', function() { + expect(1); + + container.register('template:components/with-block', compile('In layout - someProp: {{someProp}} - {{yield}}')); + + view = EmberView.extend({ + template: compile('{{#with-block someProp="something here"}}In template{{/with-block}}'), + container: container + }).create(); + + run(view, 'appendTo', '#qunit-fixture'); + + equal(jQuery('#qunit-fixture').text(), 'In layout - someProp: something here - In template'); +});
false
Other
emberjs
ember.js
e63c8186517341ecd29fbdebc41cd8b174a6a410.json
Fix Handlebars dependency.
Gemfile.lock
@@ -27,8 +27,8 @@ GIT PATH remote: . specs: - ember-source (1.9.0.alpha) - handlebars-source (~> 1.0) + ember-source (1.9.0.alpha.2) + handlebars-source (~> 2.0) GEM remote: https://rubygems.org/ @@ -45,7 +45,7 @@ GEM diff-lcs (~> 1.1) mime-types (~> 1.15) posix-spawn (~> 0.3.6) - handlebars-source (1.3.0) + handlebars-source (2.0.0) json (1.8.1) kicker (3.0.0) listen (~> 1.3.0)
true
Other
emberjs
ember.js
e63c8186517341ecd29fbdebc41cd8b174a6a410.json
Fix Handlebars dependency.
VERSION
@@ -1 +1 @@ -1.9.0-alpha +1.9.0-alpha.2
true
Other
emberjs
ember.js
e63c8186517341ecd29fbdebc41cd8b174a6a410.json
Fix Handlebars dependency.
ember-source.gemspec
@@ -13,7 +13,7 @@ Gem::Specification.new do |gem| gem.version = Ember.rubygems_version_string - gem.add_dependency "handlebars-source", ["~> 1.0"] + gem.add_dependency "handlebars-source", ["~> 2.0"] gem.files = %w(VERSION) + Dir['dist/*.js', 'lib/ember/*.rb'] end
true
Other
emberjs
ember.js
e63c8186517341ecd29fbdebc41cd8b174a6a410.json
Fix Handlebars dependency.
package.json
@@ -1,7 +1,7 @@ { "name": "ember", "license": "MIT", - "version": "1.9.0-alpha", + "version": "1.9.0-alpha.2", "scripts": { "build": "ember build --environment production", "postinstall": "bower install",
true
Other
emberjs
ember.js
171b1f390d0150893d39ecc3f64742b284daffe0.json
Add CHANGELOG entry.
CHANGELOG.md
@@ -1,5 +1,9 @@ # Ember Changelog +### Master + +* [BREAKING] Require Handlebars 2.0. See [blog post](http://emberjs.com/blog/2014/10/16/handlebars-update.html) for details. + ### Ember 1.8.0-beta.3 (September, 27, 2014) * [BUGFIX] Use contextualElements to properly handle omitted optional start tags.
false
Other
emberjs
ember.js
44a9cdaeb3a3b28cdb95b1c6c65f9051ea62db85.json
Add some tests for bind
packages/ember-handlebars/tests/helpers/bind_test.js
@@ -0,0 +1,55 @@ +import EmberView from "ember-views/views/view"; +import EmberObject from "ember-runtime/system/object"; +import run from "ember-metal/run_loop"; + +function appendView(view) { + run(function() { view.appendTo('#qunit-fixture'); }); +} + +var view; + +QUnit.module("Handlebars {{#bind}} helper", { + teardown: function() { + if (view) { + run(view, view.destroy); + view = null; + } + } +}); + +test("it should render the current value of a property on the context", function() { + view = EmberView.create({ + template: Ember.Handlebars.compile('{{bind "foo"}}'), + context: EmberObject.create({ + foo: "BORK" + }) + }); + + appendView(view); + + equal(view.$().text(), "BORK", "initial value is rendered"); + + run(view, view.set, 'context.foo', 'MWEEER'); + + equal(view.$().text(), "MWEEER", "value can be updated"); +}); + +test("it should render the current value of a path on the context", function() { + view = EmberView.create({ + template: Ember.Handlebars.compile('{{bind "foo.bar"}}'), + context: EmberObject.create({ + foo: { + bar: "BORK" + } + }) + }); + + appendView(view); + + equal(view.$().text(), "BORK", "initial value is rendered"); + + run(view, view.set, 'context.foo.bar', 'MWEEER'); + + equal(view.$().text(), "MWEEER", "value can be updated"); +}); +
false
Other
emberjs
ember.js
21c34de2418dd94afebea05c8e2d92ea93fbed23.json
Fix some.path dependent keys on bound helpers
packages/ember-handlebars/lib/ext.js
@@ -18,7 +18,6 @@ import { var resolveHelper, SimpleHandlebarsView; import Stream from "ember-metal/streams/stream"; -import KeyStream from "ember-views/streams/key_stream"; import { readArray, readHash @@ -419,15 +418,19 @@ function makeBoundHelper(fn) { } if (numParams > 0) { - var onDependentKeyNotify = function onDependentKeyNotify(stream) { - stream.value(); - lazyValue.notify(); - }; - - for (i = 0; i < dependentKeys.length; i++) { - param = new KeyStream(params[0], dependentKeys[i]); - param.value(); - param.subscribe(onDependentKeyNotify); + var firstParam = params[0]; + // Only bother with subscriptions if the first argument + // is a stream itself, and not a primitive. + if (firstParam && firstParam.isStream) { + var onDependentKeyNotify = function onDependentKeyNotify(stream) { + stream.value(); + lazyValue.notify(); + }; + for (i = 0; i < dependentKeys.length; i++) { + var childParam = firstParam.get(dependentKeys[i]); + childParam.value(); + childParam.subscribe(onDependentKeyNotify); + } } } }
true
Other
emberjs
ember.js
21c34de2418dd94afebea05c8e2d92ea93fbed23.json
Fix some.path dependent keys on bound helpers
packages/ember-handlebars/tests/helpers/bound_helper_test.js
@@ -295,28 +295,38 @@ test("bound helpers should not be invoked with blocks", function() { test("should observe dependent keys passed to registerBoundHelper", function() { try { - expect(2); + expect(3); - var SimplyObject = EmberObject.create({ + var simplyObject = EmberObject.create({ firstName: 'Jim', - lastName: 'Owen' + lastName: 'Owen', + birthday: EmberObject.create({ + year: '2009' + }) }); EmberHandlebars.registerBoundHelper('fullName', function(value){ - return value.get('firstName') + ' ' + value.get('lastName'); - }, 'firstName', 'lastName'); + return [ + value.get('firstName'), + value.get('lastName'), + value.get('birthday.year') ].join(' '); + }, 'firstName', 'lastName', 'birthday.year'); view = EmberView.create({ template: compile('{{fullName this}}'), - context: SimplyObject + context: simplyObject }); appendView(view); - equal(view.$().text(), 'Jim Owen', 'simply render the helper'); + equal(view.$().text(), 'Jim Owen 2009', 'simply render the helper'); + + run(simplyObject, simplyObject.set, 'firstName', 'Tom'); + + equal(view.$().text(), 'Tom Owen 2009', 'render the helper after prop change'); - run(SimplyObject, SimplyObject.set, 'firstName', 'Tom'); + run(simplyObject, simplyObject.set, 'birthday.year', '1692'); - equal(view.$().text(), 'Tom Owen', 'simply render the helper'); + equal(view.$().text(), 'Tom Owen 1692', 'render the helper after path change'); } finally { delete EmberHandlebars.helpers['fullName']; }
true
Other
emberjs
ember.js
e87d19507a4189257c16fc211341ca54d4401fbe.json
Remove custom template override The isTop flag will be added to Handlebars itself so this override may be removed.
packages/ember-handlebars/lib/ext.js
@@ -25,7 +25,6 @@ import { } from "ember-metal/streams/read"; var slice = [].slice; -var originalTemplate = EmberHandlebars.template; /** Lookup both on root and on window. If the path starts with @@ -436,21 +435,6 @@ function makeBoundHelper(fn) { return helper; } -/** - Overrides Handlebars.template so that we can distinguish - user-created, top-level templates from inner contexts. - - @private - @method template - @for Ember.Handlebars - @param {String} spec -*/ -export function template(spec) { - var t = originalTemplate(spec); - t.isTop = true; - return t; -} - export { makeBoundHelper, handlebarsGetView,
true
Other
emberjs
ember.js
e87d19507a4189257c16fc211341ca54d4401fbe.json
Remove custom template override The isTop flag will be added to Handlebars itself so this override may be removed.
packages/ember-handlebars/lib/main.js
@@ -5,7 +5,6 @@ import { runLoadHooks } from "ember-runtime/system/lazy_load"; import bootstrap from "ember-handlebars/loader"; import { - template, makeBoundHelper, registerBoundHelper, helperMissingHelper, @@ -87,7 +86,6 @@ Ember Handlebars // Ember.Handlebars.Globals EmberHandlebars.bootstrap = bootstrap; -EmberHandlebars.template = template; EmberHandlebars.makeBoundHelper = makeBoundHelper; EmberHandlebars.registerBoundHelper = registerBoundHelper; EmberHandlebars.resolveHelper = resolveHelper;
true
Other
emberjs
ember.js
b6c816ed9ca8fe9df5d83d344f1be7d0cf3eab28.json
Update precompiler for new format
lib/broccoli-ember-inline-template-precompiler.js
@@ -38,7 +38,7 @@ EmberInlineTemplatePrecompiler.prototype.processFile = function (srcDir, destDir while (nextIndex > -1) { var match = inputString.match(self.inlineTemplateRegExp); - var template = "Ember.Handlebars.template(" + compiler.precompile(match[1]).toString() + ")"; + var template = "Ember.Handlebars.template(" + compiler.precompile(match[1], false) + ")"; inputString = inputString.replace(match[0], template);
true
Other
emberjs
ember.js
b6c816ed9ca8fe9df5d83d344f1be7d0cf3eab28.json
Update precompiler for new format
packages/ember-handlebars-compiler/tests/precompile_type_test.js
@@ -6,23 +6,23 @@ var result; QUnit.module("Ember.Handlebars.precompileType"); -test("precompile creates a function when asObject isn't defined", function(){ +test("precompile creates an object when asObject isn't defined", function(){ result = precompile(template); - equal(typeof(result), "function"); + equal(typeof(result), "object"); }); -test("precompile creates a function when asObject is true", function(){ +test("precompile creates an object when asObject is true", function(){ result = precompile(template, true); - equal(typeof(result), "function"); + equal(typeof(result), "object"); }); test("precompile creates a string when asObject is false", function(){ result = precompile(template, false); equal(typeof(result), "string"); }); -test("precompile creates a function when passed an AST", function(){ +test("precompile creates an object when passed an AST", function(){ var ast = parse(template); result = precompile(ast); - equal(typeof(result), "function"); + equal(typeof(result), "object"); });
true
Other
emberjs
ember.js
8086179d596376becc2819bf1be0c878378a6d68.json
Create Handlebars environment through proper means
packages/ember-handlebars-compiler/lib/main.js
@@ -50,7 +50,7 @@ Ember.assert("Ember Handlebars requires Handlebars version 1.0 or 1.1, " + @class Handlebars @namespace Ember */ -var EmberHandlebars = Ember.Handlebars = objectCreate(Handlebars); +var EmberHandlebars = Ember.Handlebars = Handlebars.create(); /** Register a bound helper or custom view helper.
false
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/lib/controls.js
@@ -6,20 +6,12 @@ import Ember from "ember-metal/core"; // Ember.assert // var emberAssert = Ember.assert; import EmberHandlebars from "ember-handlebars-compiler"; -import { handlebarsGet } from "ember-handlebars/ext"; + /** @module ember @submodule ember-handlebars-compiler */ -function _resolveOption(context, options, key) { - if (options.hashTypes[key] === "ID") { - return handlebarsGet(context, options.hash[key], options); - } else { - return options.hash[key]; - } -} - /** The `{{input}}` helper inserts an HTML `<input>` tag into the template, @@ -198,10 +190,17 @@ function _resolveOption(context, options, key) { export function inputHelper(options) { Ember.assert('You can only pass attributes to the `input` helper, not arguments', arguments.length < 2); + var view = options.data.view; var hash = options.hash; var types = options.hashTypes; - var inputType = _resolveOption(this, options, 'type'); var onEvent = hash.on; + var inputType; + + if (types.type === 'ID') { + inputType = view.getStream(hash.type).value(); + } else { + inputType = hash.type; + } if (inputType === 'checkbox') { delete hash.type;
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/lib/ext.js
@@ -17,109 +17,16 @@ import { // late bound via requireModule because of circular dependencies. var resolveHelper, SimpleHandlebarsView; -import isEmpty from 'ember-metal/is_empty'; +import Stream from "ember-metal/streams/stream"; +import KeyStream from "ember-views/streams/key_stream"; +import { + readArray, + readHash +} from "ember-metal/streams/read"; var slice = [].slice; var originalTemplate = EmberHandlebars.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} -*/ - -import Cache from 'ember-metal/cache'; - -var FIRST_SEGMENT_CACHE = new Cache(1000, function(path){ - return path.split('.', 1)[0]; -}); - -function normalizePath(root, path, data) { - var keywords = (data && data.keywords) || {}; - var keyword, isKeyword; - - // Get the first segment of the path. For example, if the - // path is "foo.bar.baz", returns "foo". - keyword = FIRST_SEGMENT_CACHE.get(path); - - // 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 -*/ -function handlebarsGet(root, path, options) { - var data = options && options.data; - var normalizedPath = normalizePath(root, path, data); - var value; - - // In cases where the path begins with a keyword, change the - // root to the value represented by that keyword, and ensure - // the path is relative to it. - root = normalizedPath.root; - path = normalizedPath.path; - - // Ember.get with a null root and GlobalPath will fall back to - // Ember.lookup, which is no longer allowed in templates. - // - // But when outputting a primitive, root will be the primitive - // and path a blank string. These primitives should pass through - // to `get`. - if (root || path === '') { - value = get(root, path); - } - - if (detectIsGlobal(path)) { - if (value === undefined && root !== Ember.lookup) { - root = Ember.lookup; - value = get(root, path); - } - if (root === Ember.lookup || root === null) { - Ember.deprecate("Global lookup of "+path+" from a Handlebars template is deprecated."); - } - } - - return value; -} - /** handlebarsGetView resolves a view based on strings passed into a template. For example: @@ -149,15 +56,14 @@ function handlebarsGet(root, path, options) { function handlebarsGetView(context, path, container, data) { var viewClass; if ('string' === typeof path) { - if (data) { - var normalizedPath = normalizePath(context, path, data); - context = normalizedPath.root; - path = normalizedPath.path; + if (!data) { + throw new Error("handlebarsGetView: must pass data"); } // Only lookup view class on context if there is a context. If not, // the global lookup path on get may kick in. - viewClass = context && get(context, path); + var lazyValue = data.view.getStream(path); + viewClass = lazyValue.value(); var isGlobal = detectIsGlobal(path); if (!viewClass && !isGlobal) { @@ -190,67 +96,18 @@ function handlebarsGetView(context, path, container, data) { return viewClass; } -/** - 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 - @since 1.4.0 -*/ -export function getEscaped(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; -} - -export function resolveParams(context, params, options) { - var resolvedParams = [], types = options.types, param, type; - - for (var i=0, l=params.length; i<l; i++) { - param = params[i]; - type = types[i]; - - if (type === 'ID') { - resolvedParams.push(handlebarsGet(context, param, options)); - } else { - resolvedParams.push(param); - } +export function stringifyValue(value, shouldEscape) { + if (value === null || value === undefined) { + value = ""; + } else if (!(value instanceof Handlebars.SafeString)) { + value = String(value); } - return resolvedParams; -} - -export function resolveHash(context, hash, options) { - var resolvedHash = {}, types = options.hashTypes, type; - - for (var key in hash) { - if (!hash.hasOwnProperty(key)) { continue; } - - type = types[key]; - - if (type === 'ID') { - resolvedHash[key] = handlebarsGet(context, hash[key], options); - } else { - resolvedHash[key] = hash[key]; - } + if (shouldEscape) { + value = Handlebars.Utils.escapeExpression(value); } - return resolvedHash; + return value; } /** @@ -470,165 +327,97 @@ function makeBoundHelper(fn) { SimpleHandlebarsView = requireModule('ember-handlebars/views/handlebars_bound_view')['SimpleHandlebarsView']; } // ES6TODO: stupid circular dep - var dependentKeys = slice.call(arguments, 1); + var dependentKeys = []; + for (var i = 1; i < arguments.length; i++) { + dependentKeys.push(arguments[i]); + } function helper() { - var properties = slice.call(arguments, 0, -1); - var numProperties = properties.length; - var options = arguments[arguments.length - 1]; - var normalizedProperties = []; + var numParams = arguments.length - 1; + var options = arguments[numParams]; var data = options.data; - var types = data.isUnbound ? slice.call(options.types, 1) : options.types; + var view = data.view; + var types = options.types; var hash = options.hash; var hashTypes = options.hashTypes; - var view = data.view; - var contexts = options.contexts; - var currentContext = (contexts && contexts.length) ? contexts[0] : this; - var prefixPathForDependentKeys = ''; - var loc, len, hashOption; - var boundOption, property; - var normalizedValue = SimpleHandlebarsView.prototype.normalizedValue; + var context = this; Ember.assert("registerBoundHelper-generated helpers do not support use with Handlebars blocks.", !options.fn); - // Detect bound options (e.g. countBinding="otherCount") - var boundOptions = hash.boundOptions = {}; - for (hashOption in hash) { - if (IS_BINDING.test(hashOption)) { - // Lop off 'Binding' suffix. - boundOptions[hashOption.slice(0, -7)] = hash[hashOption]; - } else if (hashTypes[hashOption] === 'ID') { - boundOptions[hashOption] = hash[hashOption]; + var properties = new Array(numParams); + var params = new Array(numParams); + + for (var i = 0; i < numParams; i++) { + properties[i] = arguments[i]; + if (types[i] === 'ID') { + params[i] = view.getStream(arguments[i]); + } else { + params[i] = arguments[i]; } } - // Expose property names on data.properties object. - var watchedProperties = []; - data.properties = []; - for (loc = 0; loc < numProperties; ++loc) { - data.properties.push(properties[loc]); - if (types[loc] === 'ID') { - var normalizedProp = normalizePath(currentContext, properties[loc], data); - normalizedProperties.push(normalizedProp); - watchedProperties.push(normalizedProp); - } else { - if (data.isUnbound) { - normalizedProperties.push({path: properties[loc]}); - }else { - normalizedProperties.push(null); - } + for (var prop in hash) { + if (IS_BINDING.test(prop)) { + hash[prop.slice(0, -7)] = view.getStream(hash[prop]); + hash[prop] = undefined; + } else if (hashTypes[prop] === 'ID') { + hash[prop] = view.getStream(hash[prop]); } } - // Handle case when helper invocation is preceded by `unbound`, e.g. - // {{unbound myHelper foo}} + var valueFn = function() { + var args = readArray(params); + args.push({ + hash: readHash(hash), + data: { properties: properties } + }); + return fn.apply(context, args); + }; + if (data.isUnbound) { - return evaluateUnboundHelper(this, fn, normalizedProperties, options); - } + return valueFn(); + } else { + var lazyValue = new Stream(valueFn); + var bindView = new SimpleHandlebarsView(lazyValue, !options.hash.unescaped); + view.appendChild(bindView); - var bindView = new SimpleHandlebarsView(null, null, !options.hash.unescaped, options.data); + var scheduledRerender = view._wrapAsScheduled(bindView.rerender); + lazyValue.subscribe(scheduledRerender, bindView); - // Override SimpleHandlebarsView's method for generating the view's content. - bindView.normalizedValue = function() { - var args = []; - var boundOption; + var param; - // Copy over bound hash options. - for (boundOption in boundOptions) { - if (!boundOptions.hasOwnProperty(boundOption)) { continue; } - property = normalizePath(currentContext, boundOptions[boundOption], data); - bindView.path = property.path; - bindView.pathRoot = property.root; - hash[boundOption] = normalizedValue.call(bindView); + for (i = 0; i < numParams; i++) { + param = params[i]; + if (param && param.isStream) { + param.subscribe(lazyValue.notifyAll, lazyValue); + } } - for (loc = 0; loc < numProperties; ++loc) { - property = normalizedProperties[loc]; - if (property) { - bindView.path = property.path; - bindView.pathRoot = property.root; - args.push(normalizedValue.call(bindView)); - } else { - args.push(properties[loc]); + for (prop in hash) { + param = hash[prop]; + if (param && param.isStream) { + param.subscribe(lazyValue.notifyAll, lazyValue); } } - args.push(options); - // Run the supplied helper function. - return fn.apply(currentContext, args); - }; - - view.appendChild(bindView); + if (numParams > 0) { + var onDependentKeyNotify = function onDependentKeyNotify(stream) { + stream.value(); + lazyValue.notify(); + }; - // Assemble list of watched properties that'll re-render this helper. - for (boundOption in boundOptions) { - if (boundOptions.hasOwnProperty(boundOption)) { - watchedProperties.push(normalizePath(currentContext, boundOptions[boundOption], data)); + for (i = 0; i < dependentKeys.length; i++) { + param = new KeyStream(params[0], dependentKeys[i]); + param.value(); + param.subscribe(onDependentKeyNotify); + } } } - - // Observe each property. - for (loc = 0, len = watchedProperties.length; loc < len; ++loc) { - property = watchedProperties[loc]; - view.registerObserver(property.root, property.path, bindView, bindView.rerender); - } - - if (types[0] !== 'ID' || normalizedProperties.length === 0) { - return; - } - - // Add dependent key observers to the first param - var normalized = normalizedProperties[0]; - var pathRoot = normalized.root; - var path = normalized.path; - - if(!isEmpty(path)) { - prefixPathForDependentKeys = path + '.'; - } - for (var i=0, l=dependentKeys.length; i<l; i++) { - view.registerObserver(pathRoot, prefixPathForDependentKeys + dependentKeys[i], bindView, bindView.rerender); - } } - helper._rawFunction = fn; return helper; } -/** - Renders the unbound form of an otherwise bound helper function. - - @private - @method evaluateUnboundHelper - @param {Function} fn - @param {Object} context - @param {Array} normalizedProperties - @param {String} options -*/ -function evaluateUnboundHelper(context, fn, normalizedProperties, options) { - var args = []; - var hash = options.hash; - var boundOptions = hash.boundOptions; - var types = slice.call(options.types, 1); - var loc, len, property, propertyType, boundOption; - - for (boundOption in boundOptions) { - if (!boundOptions.hasOwnProperty(boundOption)) { continue; } - hash[boundOption] = handlebarsGet(context, boundOptions[boundOption], options); - } - - for (loc = 0, len = normalizedProperties.length; loc < len; ++loc) { - property = normalizedProperties[loc]; - propertyType = types[loc]; - if (propertyType === "ID") { - args.push(handlebarsGet(property.root, property.path, options)); - } else { - args.push(property.path); - } - } - args.push(options); - return fn.apply(context, args); -} - /** Overrides Handlebars.template so that we can distinguish user-created, top-level templates from inner contexts. @@ -645,9 +434,6 @@ export function template(spec) { } export { - normalizePath, makeBoundHelper, - handlebarsGet, - handlebarsGetView, - evaluateUnboundHelper + handlebarsGetView };
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/lib/helpers/binding.js
@@ -8,40 +8,29 @@ import Ember from "ember-metal/core"; // Ember.assert, Ember.warn, uuid import EmberHandlebars from "ember-handlebars-compiler"; import { get } from "ember-metal/property_get"; +import { set } from "ember-metal/property_set"; import { apply, uuid } from "ember-metal/utils"; import { fmt } from "ember-runtime/system/string"; import { create as o_create } from "ember-metal/platform"; +import { typeOf } from "ember-metal/utils"; import isNone from 'ember-metal/is_none'; import { forEach } from "ember-metal/array"; import View from "ember-views/views/view"; import run from "ember-metal/run_loop"; -import { removeObserver } from "ember-metal/observer"; -import { isGlobalPath } from "ember-metal/binding"; -import { bind as emberBind } from "ember-metal/binding"; -import jQuery from "ember-views/system/jquery"; import { isArray } from "ember-metal/utils"; import keys from "ember-metal/keys"; import Cache from "ember-metal/cache"; +import SimpleStream from "ember-metal/streams/simple"; +import KeyStream from "ember-views/streams/key_stream"; import { _HandlebarsBoundView, SimpleHandlebarsView } from "ember-handlebars/views/handlebars_bound_view"; -import { - normalizePath, - handlebarsGet, - getEscaped -} from "ember-handlebars/ext"; - -import { - guidFor, - typeOf -} from "ember-metal/utils"; - var helpers = EmberHandlebars.helpers; var SafeString = EmberHandlebars.SafeString; @@ -51,45 +40,37 @@ function exists(value) { var WithView = _HandlebarsBoundView.extend({ init: function() { - var controller; - apply(this, this._super, arguments); - var keywords = this.templateData.keywords; var keywordName = this.templateHash.keywordName; - var keywordPath = this.templateHash.keywordPath; var controllerName = this.templateHash.controller; - var preserveContext = this.preserveContext; if (controllerName) { var previousContext = this.previousContext; - controller = this.container.lookupFactory('controller:'+controllerName).create({ + var controller = this.container.lookupFactory('controller:'+controllerName).create({ parentController: previousContext, target: previousContext }); this._generatedController = controller; - if (!preserveContext) { - this.set('controller', controller); - + if (this.preserveContext) { + this._keywords[keywordName] = controller; + this.lazyValue.subscribe(function(modelStream) { + set(controller, 'model', modelStream.value()); + }); + } else { + set(this, 'controller', controller); this.valueNormalizerFunc = function(result) { - controller.set('model', result); - return controller; + controller.set('model', result); + return controller; }; - } else { - var controllerPath = jQuery.expando + guidFor(controller); - keywords[controllerPath] = controller; - emberBind(keywords, controllerPath + '.model', keywordPath); - keywordPath = controllerPath; } - } - if (preserveContext) { - emberBind(keywords, keywordName, keywordPath); + set(controller, 'model', this.lazyValue.value()); } - }, + willDestroy: function() { this._super(); @@ -103,140 +84,83 @@ var WithView = _HandlebarsBoundView.extend({ // KVO system will look for and update if the property changes. function bind(property, options, preserveContext, shouldDisplay, valueNormalizer, childProperties) { var data = options.data; - var fn = options.fn; - var inverse = options.inverse; var view = data.view; - var normalized, observer, i; // we relied on the behavior of calling without // context to mean this === window, but when running // "use strict", it's possible for this to === undefined; var currentContext = this || window; - normalized = normalizePath(currentContext, property, data); + var valueStream = view.getStream(property); + var lazyValue; - // Set up observers for observable objects - if ('object' === typeof this) { - if (data.insideGroup) { - observer = function() { - while (view._contextView) { - view = view._contextView; - } - run.once(view, 'rerender'); - }; + if (childProperties) { + lazyValue = new SimpleStream(valueStream); - var template, context; - var result = handlebarsGet(currentContext, property, options); + var subscriber = function(childStream) { + childStream.value(); + lazyValue.notify(); + }; - result = valueNormalizer ? valueNormalizer(result) : result; + for (var i = 0; i < childProperties.length; i++) { + var childStream = new KeyStream(valueStream, childProperties[i]); + childStream.value(); + childStream.subscribe(subscriber); + } + } else { + lazyValue = valueStream; + } - context = preserveContext ? currentContext : result; - if (shouldDisplay(result)) { - template = fn; - } else if (inverse) { - template = inverse; - } + // Set up observers for observable objects + var viewClass = _HandlebarsBoundView; + var viewOptions = { + preserveContext: preserveContext, + shouldDisplayFunc: shouldDisplay, + valueNormalizerFunc: valueNormalizer, + displayTemplate: options.fn, + inverseTemplate: options.inverse, + lazyValue: lazyValue, + previousContext: currentContext, + isEscaped: !options.hash.unescaped, + templateData: options.data, + templateHash: options.hash, + helperName: options.helperName + }; - template(context, { data: options.data }); - } else { - var viewClass = _HandlebarsBoundView; - var viewOptions = { - preserveContext: preserveContext, - shouldDisplayFunc: shouldDisplay, - valueNormalizerFunc: valueNormalizer, - displayTemplate: fn, - inverseTemplate: inverse, - path: property, - pathRoot: currentContext, - previousContext: currentContext, - isEscaped: !options.hash.unescaped, - templateData: options.data, - templateHash: options.hash, - helperName: options.helperName - }; - - if (options.isWithHelper) { - viewClass = WithView; - } + if (options.keywords) { + viewOptions._keywords = options.keywords; + } - // Create the view that will wrap the output of this template/property - // and add it to the nearest view's childViews array. - // See the documentation of Ember._HandlebarsBoundView for more. - var bindView = view.createChildView(viewClass, viewOptions); + if (options.isWithHelper) { + viewClass = WithView; + } - view.appendChild(bindView); + // Create the view that will wrap the output of this template/property + // and add it to the nearest view's childViews array. + // See the documentation of Ember._HandlebarsBoundView for more. + var bindView = view.createChildView(viewClass, viewOptions); - observer = function() { - run.scheduleOnce('render', bindView, 'rerenderIfNeeded'); - }; - } + view.appendChild(bindView); - // Observes the given property on the context and - // tells the Ember._HandlebarsBoundView to re-render. If property - // is an empty string, we are printing the current context - // object ({{this}}) so updating it is not our responsibility. - if (normalized.path !== '') { - view.registerObserver(normalized.root, normalized.path, observer); - if (childProperties) { - for (i=0; i<childProperties.length; i++) { - view.registerObserver(normalized.root, normalized.path+'.'+childProperties[i], observer); - } - } - } - } else { - // The object is not observable, so just render it out and - // be done with it. - data.buffer.push(getEscaped(currentContext, property, options)); - } + lazyValue.subscribe(view._wrapAsScheduled(function() { + run.scheduleOnce('render', bindView, 'rerenderIfNeeded'); + })); } -function simpleBind(currentContext, property, options) { +function simpleBind(currentContext, lazyValue, options) { var data = options.data; var view = data.view; - var normalized, observer, pathRoot, output; - normalized = normalizePath(currentContext, property, data); - pathRoot = normalized.root; + var bindView = new SimpleHandlebarsView( + lazyValue, !options.hash.unescaped + ); - // Set up observers for observable objects - if (pathRoot && ('object' === typeof pathRoot)) { - if (data.insideGroup) { - observer = function() { - while (view._contextView) { - view = view._contextView; - } - run.once(view, 'rerender'); - }; + bindView._parentView = view; + view.appendChild(bindView); - output = getEscaped(currentContext, property, options); - - data.buffer.push(output); - } else { - var bindView = new SimpleHandlebarsView( - property, currentContext, !options.hash.unescaped, options.data - ); - - bindView._parentView = view; - view.appendChild(bindView); - - observer = function() { - run.scheduleOnce('render', bindView, 'rerender'); - }; - } - - // Observes the given property on the context and - // tells the Ember._HandlebarsBoundView to re-render. If property - // is an empty string, we are printing the current context - // object ({{this}}) so updating it is not our responsibility. - if (normalized.path !== '') { - view.registerObserver(normalized.root, normalized.path, observer); - } - } else { - // The object is not observable, so just render it out and - // be done with it. - output = getEscaped(currentContext, property, options); - data.buffer.push(output); - } + lazyValue.subscribe(view._wrapAsScheduled(function() { + run.scheduleOnce('render', bindView, 'rerender'); + })); } function shouldDisplayIfHelperContent(result) { @@ -349,7 +273,8 @@ function bindHelper(property, options) { var context = (options.contexts && options.contexts.length) ? options.contexts[0] : this; if (!options.fn) { - return simpleBind(context, property, options); + var lazyValue = options.data.view.getStream(property); + return simpleBind(context, lazyValue, options); } options.helperName = 'bind'; @@ -406,12 +331,11 @@ function boundIfHelper(property, fn) { function unboundIfHelper(property, fn) { var context = (fn.contexts && fn.contexts.length) ? fn.contexts[0] : this; var data = fn.data; + var view = data.view; var template = fn.fn; var inverse = fn.inverse; - var normalized, propertyValue; - normalized = normalizePath(context, property, data); - propertyValue = handlebarsGet(context, property, fn); + var propertyValue = view.getStream(property).value(); if (!shouldDisplayIfHelperContent(propertyValue)) { template = inverse; @@ -498,64 +422,48 @@ function unboundIfHelper(property, fn) { @param {Hash} options @return {String} HTML string */ -function withHelper(context, options) { +function withHelper(contextPath) { + var options = arguments[arguments.length - 1]; + var view = options.data.view; var bindContext, preserveContext; var helperName = 'with'; if (arguments.length === 4) { - var keywordName, path, rootPath, normalized, contextPath; - Ember.assert("If you pass more than one argument to the with helper," + " it must be in the form #with foo as bar", arguments[1] === "as"); - options = arguments[3]; - keywordName = arguments[2]; - path = arguments[0]; - if (path) { - helperName += ' ' + path + ' as ' + keywordName; + var keywordName = arguments[2]; + + if (contextPath) { + helperName += ' ' + contextPath + ' as ' + keywordName; } Ember.assert("You must pass a block to the with helper", options.fn && options.fn !== Handlebars.VM.noop); var localizedOptions = o_create(options); localizedOptions.data = o_create(options.data); - localizedOptions.data.keywords = o_create(options.data.keywords || {}); - if (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 = jQuery.expando + guidFor(rootPath); - localizedOptions.data.keywords[contextKey] = rootPath; - // if the path is '' ("this"), just bind directly to the current context - contextPath = path ? contextKey + '.' + path : contextKey; - } + localizedOptions.keywords = {}; + localizedOptions.keywords[keywordName] = view.getStream(contextPath); localizedOptions.hash.keywordName = keywordName; - localizedOptions.hash.keywordPath = contextPath; bindContext = this; - context = contextPath; options = localizedOptions; preserveContext = true; } else { Ember.assert("You must pass exactly one argument to the with helper", arguments.length === 2); Ember.assert("You must pass a block to the with helper", options.fn && options.fn !== Handlebars.VM.noop); - helperName += ' ' + context; + helperName += ' ' + contextPath; bindContext = options.contexts[0]; preserveContext = false; } options.helperName = helperName; options.isWithHelper = true; - return bind.call(bindContext, context, options, preserveContext, exists); + return bind.call(bindContext, contextPath, options, preserveContext, exists); } /** See [boundIf](/api/classes/Ember.Handlebars.helpers.html#method_boundIf) @@ -767,50 +675,30 @@ function bindAttrHelper(options) { // current value of the property as an attribute. forEach.call(attrKeys, function(attr) { var path = attrs[attr]; - var normalized; Ember.assert(fmt("You must provide an expression as the value of bound attribute." + " You specified: %@=%@", [attr, path]), typeof path === 'string'); - normalized = normalizePath(ctx, path, options.data); - - var value = (path === 'this') ? normalized.root : handlebarsGet(ctx, path, options); + var lazyValue = view.getStream(path); + var value = lazyValue.value(); var type = typeOf(value); Ember.assert(fmt("Attributes must be numbers, strings or booleans, not %@", [value]), value === null || value === undefined || type === 'number' || type === 'string' || type === 'boolean'); - var observer; - - observer = function observer() { - var result = handlebarsGet(ctx, path, options); + lazyValue.subscribe(view._wrapAsScheduled(function applyAttributeBindings() { + var result = lazyValue.value(); Ember.assert(fmt("Attributes must be numbers, strings or booleans, not %@", [result]), result === null || result === undefined || typeof result === 'number' || typeof result === 'string' || typeof result === 'boolean'); var elem = view.$("[data-bindattr-" + dataId + "='" + dataId + "']"); - // If we aren't able to find the element, it means the element - // to which we were bound has been removed from the view. - // In that case, we can assume the template has been re-rendered - // and we need to clean up the observer. - if (!elem || elem.length === 0) { - removeObserver(normalized.root, normalized.path, observer); - return; - } + Ember.assert("An attribute binding was triggered when the element was not in the DOM", elem && elem.length !== 0); 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)))) { @@ -869,24 +757,6 @@ function bindClasses(context, classBindings, view, bindAttrId, options) { var ret = []; var 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; - var path = parsedPath.path; - - if (path === 'this') { - val = root; - } else if (path === '') { - val = true; - } else { - val = handlebarsGet(root, path, options); - } - - return View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName); - }; - // For each property passed, loop through and setup // an observer. forEach.call(classBindings.split(' '), function(binding) { @@ -895,31 +765,26 @@ function bindClasses(context, classBindings, view, bindAttrId, options) { // closes over this variable, so it knows which string to remove when // the property changes. var oldClass; - var observer; var parsedPath = View._parsePropertyPath(binding); var path = parsedPath.path; - var pathRoot = context; - var normalized; + var initialValue; - if (path !== '' && path !== 'this') { - normalized = normalizePath(context, path, options.data); + if (path === '') { + initialValue = true; + } else { + var lazyValue = view.getStream(path); + initialValue = lazyValue.value(); - pathRoot = normalized.root; - path = normalized.path; - } + // Set up an observer on the context. If the property changes, toggle the + // class name. + lazyValue.subscribe(view._wrapAsScheduled(function applyClassNameBindings() { + // Get the current value of the property + var value = lazyValue.value(); + newClass = classStringForParsedPath(parsedPath, value); + elem = bindAttrId ? view.$("[data-bindattr-" + bindAttrId + "='" + bindAttrId + "']") : view.$(); + + Ember.assert("A class name binding was triggered when the element was not in the DOM", elem && elem.length !== 0); - // 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) { - removeObserver(pathRoot, path, observer); - } else { // If we had previously added a class to the element, remove it. if (oldClass) { elem.removeClass(oldClass); @@ -933,16 +798,12 @@ function bindClasses(context, classBindings, view, bindAttrId, options) { } 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); + value = classStringForParsedPath(parsedPath, initialValue); if (value) { ret.push(value); @@ -956,6 +817,10 @@ function bindClasses(context, classBindings, view, bindAttrId, options) { return ret; } +function classStringForParsedPath(parsedPath, value) { + return View._classStringForValue(parsedPath.path, value, parsedPath.className, parsedPath.falsyClassName); +} + export { bind, _triageMustacheHelper,
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/lib/helpers/collection.js
@@ -10,11 +10,14 @@ import Ember from "ember-metal/core"; // Ember.assert, Ember.deprecate import EmberHandlebars from "ember-handlebars-compiler"; +import { IS_BINDING } from "ember-metal/mixin"; import { fmt } from "ember-runtime/system/string"; import { get } from "ember-metal/property_get"; +import SimpleStream from "ember-metal/streams/simple"; import { handlebarsGetView } from "ember-handlebars/ext"; import { ViewHelper } from "ember-handlebars/helpers/view"; import alias from "ember-metal/alias"; +import View from "ember-views/views/view"; import CollectionView from "ember-views/views/collection_view"; /** @@ -176,6 +179,7 @@ function collectionHelper(path, options) { } var hash = options.hash; + var hashTypes = options.hashTypes; var itemHash = {}; var match; @@ -184,29 +188,46 @@ function collectionHelper(path, options) { var itemViewClass; if (hash.itemView) { - itemViewClass = handlebarsGetView(this, hash.itemView, container, options.data); + itemViewClass = hash.itemView; } else if (hash.itemViewClass) { - itemViewClass = handlebarsGetView(collectionPrototype, hash.itemViewClass, container, options.data); + if (hashTypes.itemViewClass === 'ID') { + var itemViewClassStream = view.getStream(hash.itemViewClass); + Ember.deprecate('Resolved the view "'+hash.itemViewClass+'" on the global context. Pass a view name to be looked up on the container instead, such as {{view "select"}}. http://emberjs.com/guides/deprecations#toc_global-lookup-of-views-since-1-8', !itemViewClassStream.isGlobal()); + itemViewClass = itemViewClassStream.value(); + } else { + itemViewClass = hash.itemViewClass; + } } else { - itemViewClass = handlebarsGetView(collectionPrototype, collectionPrototype.itemViewClass, container, options.data); + itemViewClass = collectionPrototype.itemViewClass; + } + + if (typeof itemViewClass === 'string') { + itemViewClass = container.lookupFactory('view:'+itemViewClass); } Ember.assert(fmt("%@ #collection: Could not find itemViewClass %@", [data.view, itemViewClass]), !!itemViewClass); delete hash.itemViewClass; delete hash.itemView; + delete hashTypes.itemViewClass; + delete hashTypes.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 (prop === 'itemController' || prop === 'itemClassBinding') { + continue; + } 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. + if (match) { + var childProp = match[1].toLowerCase() + match[2]; + + if (hashTypes[prop] === 'ID' || IS_BINDING.test(prop)) { + itemHash[childProp] = view._getBindingForStream(hash[prop]); + } else { + itemHash[childProp] = hash[prop]; + } delete hash[prop]; } } @@ -236,6 +257,23 @@ function collectionHelper(path, options) { } var viewOptions = ViewHelper.propertiesFromHTMLOptions({ data: data, hash: itemHash }, this); + + if (hash.itemClassBinding) { + var itemClassBindings = hash.itemClassBinding.split(' '); + + for (var i = 0; i < itemClassBindings.length; i++) { + var parsedPath = View._parsePropertyPath(itemClassBindings[i]); + if (parsedPath.path === '') { + parsedPath.stream = new SimpleStream(true); + } else { + parsedPath.stream = view.getStream(parsedPath.path); + } + itemClassBindings[i] = parsedPath; + } + + viewOptions.classNameBindings = itemClassBindings; + } + hash.itemViewClass = itemViewClass.extend(viewOptions); options.helperName = options.helperName || 'collection';
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/lib/helpers/debug.js
@@ -8,11 +8,6 @@ import Ember from "ember-metal/core"; // Ember.FEATURES, import { inspect } from "ember-metal/utils"; import Logger from "ember-metal/logger"; -import { - normalizePath, - handlebarsGet -} from "ember-handlebars/ext"; - var a_slice = [].slice; /** @@ -30,22 +25,14 @@ var a_slice = [].slice; function logHelper() { var params = a_slice.call(arguments, 0, -1); var options = arguments[arguments.length - 1]; + var view = options.data.view; var logger = Logger.log; var values = []; - var allowPrimitives = true; for (var i = 0; i < params.length; i++) { - var type = options.types[i]; - - if (type === 'ID' || !allowPrimitives) { - var context = (options.contexts && options.contexts[i]) || this; - var normalized = normalizePath(context, params[i], options.data); - - if (normalized.path === 'this') { - values.push(normalized.root); - } else { - values.push(handlebarsGet(normalized.root, normalized.path, options)); - } + if (options.types[i] === 'ID') { + var stream = view.getStream(params[i]); + values.push(stream.value()); } else { values.push(params[i]); }
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/lib/helpers/each.js
@@ -4,7 +4,6 @@ @submodule ember-handlebars */ import Ember from "ember-metal/core"; // Ember.assert;, Ember.K -var K = Ember.K; import EmberHandlebars from "ember-handlebars-compiler"; @@ -16,9 +15,6 @@ import { Binding } from "ember-metal/binding"; import ControllerMixin from "ember-runtime/mixins/controller"; import ArrayController from "ember-runtime/controllers/array_controller"; import EmberArray from "ember-runtime/mixins/array"; -import copy from "ember-runtime/copy"; -import run from "ember-metal/run_loop"; -import { handlebarsGet } from "ember-handlebars/ext"; import { addObserver, @@ -92,22 +88,11 @@ var EachView = CollectionView.extend(_Metamorph, { 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'); + var keyword = get(this, 'keyword'); if (keyword) { - var data = get(view, 'templateData'); - - data = 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; + view._keywords[keyword] = content; } // If {{#each}} is looping over an array of controllers, @@ -132,112 +117,6 @@ var EachView = CollectionView.extend(_Metamorph, { } }); -var GroupedEach = EmberHandlebars.GroupedEach = function(context, path, options) { - var self = this; - var normalized = EmberHandlebars.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: K, - - contentArrayDidChange: function() { - this.rerenderContainingView(); - }, - - lookupContent: function() { - return handlebarsGet(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() { - addBeforeObserver(this.normalizedRoot, this.normalizedPath, this, this.contentWillChange); - addObserver(this.normalizedRoot, this.normalizedPath, this, this.contentDidChange); - }, - - removeContentObservers: function() { - removeBeforeObserver(this.normalizedRoot, this.normalizedPath, this.contentWillChange); - removeObserver(this.normalizedRoot, this.normalizedPath, this.contentDidChange); - }, - - render: function() { - if (!this.content) { return; } - - var content = this.content; - var contentLength = get(content, 'length'); - var options = this.options; - var data = options.data; - var template = this.template; - - data.insideEach = true; - for (var i = 0; i < contentLength; i++) { - var context = content.objectAt(i); - options.data.keywords[options.hash.keyword] = context; - template(context, { data: data }); - } - }, - - rerenderContainingView: function() { - var self = this; - 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. It is an extension of the base Handlebars `{{#each}}` helper. @@ -389,47 +268,6 @@ GroupedEach.prototype = { {{/each}} ``` - ### (Experimental) Grouped Each - - If a list's membership often changes, but properties of items in that - group rarely change, a significant improvement in template rendering - time can be achieved by using the experimental [group helper](https://github.com/emberjs/group-helper). - - ```handlebars - {{#group}} - {{#each people}} - {{firstName}} {{lastName}} - {{/each}} - {{/group}} - ``` - - When the membership of `people` changes, or when any property changes, the entire - `{{#group}}` block will be re-rendered. - - An `{{#each}}` inside the `{{#group}}` helper can opt-out of the special group - behavior by passing the `groupedRows` option. For example: - - ```handlebars - {{#group}} - {{#each dealers}} - {{! uses group's special behavior }} - {{firstName}} {{lastName}} - {{/each}} - - {{#each car in cars groupedRows=true}} - {{! does not use group's special behavior }} - {{car.make}} {{car.model}} {{car.color}} - {{/each}} - {{/group}} - ``` - - Any change to the `dealers` collection will cause the entire group to be re-rendered. - Changes to the `cars` collection will be re-rendered individually, as they are with - normal `{{#each}}` usage. - - `{{#group}}` is implemented with an `itemViewClass`, so specifying an `itemViewClass` - on an `{{#each}}` will also disable the special re-rendering behavior. - @method each @for Ember.Handlebars.helpers @param [name] {String} name for item (used with `in`) @@ -438,56 +276,36 @@ GroupedEach.prototype = { @param [options.itemViewClass] {String} a path to a view class used for each item @param [options.emptyViewClass] {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 */ -function eachHelper(path, options) { - var ctx; +function eachHelper(path) { + var options = arguments[arguments.length - 1]; var helperName = 'each'; if (arguments.length === 4) { Ember.assert("If you pass more than one argument to the each helper," + " it must be in the form #each foo in bar", arguments[1] === "in"); var keywordName = arguments[0]; - - - options = arguments[3]; path = arguments[2]; helperName += ' ' + keywordName + ' in ' + path; - if (path === '') { - path = "this"; - } - options.hash.keyword = keywordName; - } else if (arguments.length === 1) { - options = path; - path = 'this'; + path = ''; } else { helperName += ' ' + path; } + options.hash.emptyViewClass = Ember._MetamorphView; options.hash.dataSourceBinding = path; - // Set up emptyView as a metamorph with no tag - //options.hash.emptyViewClass = Ember._MetamorphView; - - // can't rely on this default behavior when use strict - ctx = this || window; - + options.hashTypes.dataSourceBinding = 'STRING'; options.helperName = options.helperName || helperName; - if (options.data.insideGroup && !options.hash.groupedRows && !options.hash.itemViewClass) { - new GroupedEach(ctx, path, options).render(); - } else { - return EmberHandlebars.helpers.collection.call(ctx, EmberHandlebars.EachView, options); - } + return EmberHandlebars.helpers.collection.call(this, EmberHandlebars.EachView, options); } export { EachView, - GroupedEach, eachHelper }; -
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/lib/helpers/partial.js
@@ -2,7 +2,6 @@ import Ember from "ember-metal/core"; // Ember.assert // var emberAssert = Ember.assert; import { isNone } from 'ember-metal/is_none'; -import { handlebarsGet } from "ember-handlebars/ext"; import { bind } from "ember-handlebars/helpers/binding"; /** @@ -61,18 +60,19 @@ import { bind } from "ember-handlebars/helpers/binding"; */ export default function partialHelper(name, options) { + var view = options.data.view; var context = (options.contexts && options.contexts.length) ? options.contexts[0] : this; options.helperName = options.helperName || 'partial'; if (options.types[0] === "ID") { + var partialNameStream = view.getStream(name); // Helper was passed a property path; we need to // create a binding that will re-render whenever // this property changes. options.fn = function(context, fnOptions) { - var partialName = handlebarsGet(context, name, fnOptions); - renderPartial(context, partialName, fnOptions); + renderPartial(context, partialNameStream.value(), fnOptions); }; return bind.call(context, name, options, true, exists);
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/lib/helpers/shared.js
@@ -1,14 +0,0 @@ -import { handlebarsGet } from "ember-handlebars/ext"; - -export default function resolvePaths(options) { - var ret = []; - var contexts = options.contexts; - var roots = options.roots; - var data = options.data; - - for (var i=0, l=contexts.length; i<l; i++) { - ret.push(handlebarsGet(roots[i], contexts[i], { data: data })); - } - - return ret; -}
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/lib/helpers/unbound.js
@@ -6,9 +6,6 @@ import EmberHandlebars from "ember-handlebars-compiler"; import { resolveHelper } from "ember-handlebars/helpers/binding"; -import { handlebarsGet } from "ember-handlebars/ext"; - -var slice = [].slice; /** `unbound` allows you to output a property without binding. *Important:* The @@ -30,21 +27,27 @@ var slice = [].slice; @param {String} property @return {String} HTML string */ -export default function unboundHelper(property, fn) { - var options = arguments[arguments.length - 1]; - var container = options.data.view.container; - var helper, context, out, ctx; - - ctx = this; - if (arguments.length > 2) { - // Unbound helper call. +export default function unboundHelper(property) { + var argsLength = arguments.length; + var options = arguments[argsLength - 1]; + var view = options.data.view; + var container = view.container; + + if (argsLength <= 2) { + return view.getStream(property).value(); + } else { options.data.isUnbound = true; - helper = resolveHelper(container, property) || EmberHandlebars.helpers.helperMissing; - out = helper.apply(ctx, slice.call(arguments, 1)); + options.types.shift(); + + var args = new Array(argsLength - 1); + for (var i = 1; i < argsLength; i++) { + args[i - 1] = arguments[i]; + } + + var helper = resolveHelper(container, property) || EmberHandlebars.helpers.helperMissing; + var result = helper.apply(this, args); + delete options.data.isUnbound; - return out; + return result; } - - context = (fn.contexts && fn.contexts.length) ? fn.contexts[0] : ctx; - return handlebarsGet(context, property, fn); }
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/lib/helpers/view.js
@@ -8,54 +8,58 @@ import Ember from "ember-metal/core"; // Ember.warn, Ember.assert import EmberObject from "ember-runtime/system/object"; import { get } from "ember-metal/property_get"; +import keys from "ember-metal/keys"; import { IS_BINDING } from "ember-metal/mixin"; +import { readViewFactory } from "ember-views/streams/read"; import View from "ember-views/views/view"; -import { isGlobalPath } from "ember-metal/binding"; -import keys from 'ember-metal/keys'; -import { - normalizePath, - handlebarsGet, - handlebarsGetView -} from "ember-handlebars/ext"; +import SimpleStream from "ember-metal/streams/simple"; -var SELF_BINDING = /^_view\./; - -function makeBindings(thisContext, options) { +function makeBindings(options) { var hash = options.hash; - var hashType = options.hashTypes; + var hashTypes = options.hashTypes; + var view = options.data.view; for (var prop in hash) { - if (hashType[prop] === 'ID') { + var hashType = hashTypes[prop]; + var value = hash[prop]; - var value = hash[prop]; + if (IS_BINDING.test(prop)) { + // classBinding is processed separately + if (prop === 'classBinding') { + continue; + } - if (IS_BINDING.test(prop)) { + if (hashType === 'ID') { Ember.warn("You're attempting to render a view by passing " + prop + "=" + value + " to a view helper, but this syntax is ambiguous. You should either surround " + value + " in quotes or remove `Binding` from " + prop + "."); - } else { - hash[prop + 'Binding'] = value; - hashType[prop + 'Binding'] = 'STRING'; + hash[prop] = view._getBindingForStream(value); + } else if (typeof value === 'string') { + hash[prop] = view._getBindingForStream(value); + } + } else { + if (hashType === 'ID') { + hash[prop + 'Binding'] = view._getBindingForStream(value); delete hash[prop]; - delete hashType[prop]; + delete hashTypes[prop]; } } } - if (hash.hasOwnProperty('idBinding')) { + if (hash.idBinding) { // id can't be bound, so just perform one-time lookup. - hash.id = handlebarsGet(thisContext, hash.idBinding, options); - hashType.id = 'STRING'; + hash.id = hash.idBinding.value(); + hashTypes.id = 'STRING'; delete hash.idBinding; - delete hashType.idBinding; + delete hashTypes.idBinding; } } export var ViewHelper = EmberObject.create({ propertiesFromHTMLOptions: function(options) { + var view = options.data.view; var hash = options.hash; - var data = options.data; var classes = hash['class']; var extensions = { @@ -95,80 +99,38 @@ export var ViewHelper = EmberObject.create({ // 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; + var hashKeys = keys(hash); for (var i = 0, l = hashKeys.length; i < l; i++) { - var prop = hashKeys[i]; - var isBinding = IS_BINDING.test(prop); + var prop = hashKeys[i]; if (prop !== 'classNameBindings') { extensions[prop] = hash[prop]; } - - // Test if the property ends in "Binding" - if (isBinding && typeof extensions[prop] === 'string') { - path = this.contextualizeBindingPath(hash[prop], data); - if (path) { - extensions[prop] = path; - } - } } - if (extensions.classNameBindings) { - // Evaluate the context of class name bindings: - for (var j = 0, k = extensions.classNameBindings.length; j < k; j++) { - var full = extensions.classNameBindings[j]; - - 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 = View._parsePropertyPath(full); - if (parsedPath.path !== '') { - path = this.contextualizeBindingPath(parsedPath.path, data); - if (path) { - extensions.classNameBindings[j] = path + parsedPath.classNames; - } - } + var classNameBindings = extensions.classNameBindings; + if (classNameBindings) { + for (var j = 0; j < classNameBindings.length; j++) { + var parsedPath = View._parsePropertyPath(classNameBindings[j]); + if (parsedPath.path === '') { + parsedPath.stream = new SimpleStream(true); + } else { + parsedPath.stream = view.getStream(parsedPath.path); } + classNameBindings[j] = parsedPath; } } return 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. - contextualizeBindingPath: function(path, data) { - if (SELF_BINDING.test(path)) { - return path.slice(6); // Lop off "_view." - } - var normalized = normalizePath(null, path, data); - if (normalized.isKeyword) { - return 'templateData.keywords.' + path; - } else if (isGlobalPath(path)) { - return null; - } else if (path === 'this' || path === '') { - return '_parentView.context'; - } else { - return '_parentView.context.' + path; - } - }, - - helper: function(thisContext, path, options) { + helper: function(thisContext, newView, options) { var data = options.data; var fn = options.fn; - var newView; - - makeBindings(thisContext, options); - var container = this.container || (data && data.view && data.view.container); - newView = handlebarsGetView(thisContext, path, container, options.data); + makeBindings(options); var viewOptions = this.propertiesFromHTMLOptions(options, thisContext); var currentView = data.view; @@ -194,7 +156,7 @@ export var ViewHelper = EmberObject.create({ var data = options.data; var fn = options.fn; - makeBindings(thisContext, options); + makeBindings(options); Ember.assert( 'Only a instance of a view may be passed to the ViewHelper.instanceHelper', @@ -400,21 +362,36 @@ export var ViewHelper = EmberObject.create({ @param {Hash} options @return {String} HTML string */ -export function viewHelper(path, options) { +export function viewHelper(path) { Ember.assert("The view helper only takes a single argument", arguments.length <= 2); + var options = arguments[arguments.length - 1]; + var types = options.types; + var view = options.data.view; + var container = view.container || view._keywords.view.value().container; + var viewClass; + // If no path is provided, treat path param as options // and get an instance of the registered `view:toplevel` - if (path && path.data && path.data.isRenderData) { - options = path; - if (options.data && options.data.view && options.data.view.container) { - path = options.data.view.container.lookupFactory('view:toplevel'); + if (arguments.length === 1) { + if (container) { + viewClass = container.lookupFactory('view:toplevel'); + } else { + viewClass = View; + } + } else { + var pathStream; + if (typeof path === 'string' && types[0] === 'ID') { + pathStream = view.getStream(path); + Ember.deprecate('Resolved the view "'+path+'" on the global context. Pass a view name to be looked up on the container instead, such as {{view "select"}}. http://emberjs.com/guides/deprecations#toc_global-lookup-of-views-since-1-8', !pathStream.isGlobal()); } else { - path = View; + pathStream = path; } + + viewClass = readViewFactory(pathStream, container); } options.helperName = options.helperName || 'view'; - return ViewHelper.helper(this, path, options); + return ViewHelper.helper(this, viewClass, options); }
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/lib/main.js
@@ -5,15 +5,9 @@ import { runLoadHooks } from "ember-runtime/system/lazy_load"; import bootstrap from "ember-handlebars/loader"; import { - normalizePath, template, makeBoundHelper, registerBoundHelper, - resolveHash, - resolveParams, - getEscaped, - handlebarsGet, - evaluateUnboundHelper, helperMissingHelper, blockHelperMissingHelper } from "ember-handlebars/ext"; @@ -22,7 +16,6 @@ import { // side effect of extending StringUtils of htmlSafe import "ember-handlebars/string"; -import resolvePaths from "ember-handlebars/helpers/shared"; import { bind, _triageMustacheHelper, @@ -50,7 +43,6 @@ import { } from "ember-handlebars/helpers/debug"; import { EachView, - GroupedEach, eachHelper } from "ember-handlebars/helpers/each"; import templateHelper from "ember-handlebars/helpers/template"; @@ -98,19 +90,11 @@ EmberHandlebars.bootstrap = bootstrap; EmberHandlebars.template = template; EmberHandlebars.makeBoundHelper = makeBoundHelper; EmberHandlebars.registerBoundHelper = registerBoundHelper; -EmberHandlebars.resolveHash = resolveHash; -EmberHandlebars.resolveParams = resolveParams; EmberHandlebars.resolveHelper = resolveHelper; -EmberHandlebars.get = handlebarsGet; -EmberHandlebars.getEscaped = getEscaped; -EmberHandlebars.evaluateUnboundHelper = evaluateUnboundHelper; EmberHandlebars.bind = bind; EmberHandlebars.bindClasses = bindClasses; EmberHandlebars.EachView = EachView; -EmberHandlebars.GroupedEach = GroupedEach; -EmberHandlebars.resolvePaths = resolvePaths; EmberHandlebars.ViewHelper = ViewHelper; -EmberHandlebars.normalizePath = normalizePath; // Ember Globals
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/lib/views/handlebars_bound_view.js
@@ -22,14 +22,11 @@ import { } from "ember-views/views/states"; import _MetamorphView from "ember-handlebars/views/metamorph_view"; -import { handlebarsGet } from "ember-handlebars/ext"; import { uuid } from "ember-metal/utils"; -function SimpleHandlebarsView(path, pathRoot, isEscaped, templateData) { - this.path = path; - this.pathRoot = pathRoot; +function SimpleHandlebarsView(lazyValue, isEscaped) { + this.lazyValue = lazyValue; this.isEscaped = isEscaped; - this.templateData = templateData; this[Ember.GUID_KEY] = uuid(); this._lastNormalizedValue = undefined; this.state = 'preRender'; @@ -60,25 +57,11 @@ SimpleHandlebarsView.prototype = { propertyDidChange: K, normalizedValue: function() { - var path = this.path; - var pathRoot = this.pathRoot; - var escape = this.isEscaped; - var result, templateData; - - // Use the pathRoot as the result if no path is provided. This - // happens if the path is `this`, which gets normalized into - // a `pathRoot` of the current Handlebars context and a path - // of `''`. - if (path === '') { - result = pathRoot; - } else { - templateData = this.templateData; - result = handlebarsGet(pathRoot, path, { data: templateData }); - } + var result = this.lazyValue.value(); if (result === null || result === undefined) { result = ""; - } else if (!escape && !(result instanceof EmberHandlebars.SafeString)) { + } else if (!this.isEscaped && !(result instanceof EmberHandlebars.SafeString)) { result = new EmberHandlebars.SafeString(result); } @@ -209,49 +192,12 @@ var _HandlebarsBoundView = _MetamorphView.extend({ */ inverseTemplate: null, - - /** - The path to look up on `pathRoot` that is passed to - `shouldDisplayFunc` to determine which template to render. - - In addition, if `preserveContext` is `false,` the object at this path will - be passed to the template when rendering. - - @property path - @type String - @default null - */ - path: null, - - /** - The object from which the `path` will be looked up. Sometimes this is the - same as the `previousContext`, but in cases where this view has been - generated for paths that start with a keyword such as `view` or - `controller`, the path root will be that resolved object. - - @property pathRoot - @type Object - */ - pathRoot: null, + lazyValue: null, normalizedValue: function() { - var path = get(this, 'path'); - var pathRoot = get(this, 'pathRoot'); + var value = this.lazyValue.value(); var valueNormalizer = get(this, 'valueNormalizerFunc'); - var result, templateData; - - // Use the pathRoot as the result if no path is provided. This - // happens if the path is `this`, which gets normalized into - // a `pathRoot` of the current Handlebars context and a path - // of `''`. - if (path === '') { - result = pathRoot; - } else { - templateData = get(this, 'templateData'); - result = handlebarsGet(pathRoot, path, { data: templateData }); - } - - return valueNormalizer ? valueNormalizer(result) : result; + return valueNormalizer ? valueNormalizer(value) : value; }, rerenderIfNeeded: function() {
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/tests/handlebars_test.js
@@ -343,22 +343,6 @@ test("child views can be inserted using the {{view}} Handlebars helper", functio ok(view.$().text().match(/Hello world!.*Goodbye cruel world\!/), "parent view should appear before the child view"); }); -test("should accept relative paths to views", function() { - view = EmberView.create({ - template: EmberHandlebars.compile('Hey look, at {{view "view.myCool.view"}}'), - - myCool: EmberObject.create({ - view: EmberView.extend({ - template: EmberHandlebars.compile("my cool view") - }) - }) - }); - - appendView(); - - equal(view.$().text(), "Hey look, at my cool view"); -}); - test("child views can be inserted inside a bind block", function() { container.register('template:nester', EmberHandlebars.compile("<h1 id='hello-world'>Hello {{world}}</h1>{{view view.bqView}}")); container.register('template:nested', EmberHandlebars.compile("<div id='child-view'>Goodbye {{#with content}}{{blah}} {{view view.otherView}}{{/with}} {{world}}</div>")); @@ -397,25 +381,6 @@ test("child views can be inserted inside a bind block", function() { ok(view.$().text().match(/Hello world!.*Goodbye.*wot.*cruel.*world\!/), "parent view should appear before the child view"); }); -test("View should bind properties in the parent context", function() { - var context = { - content: EmberObject.create({ - wham: 'bam' - }), - - blam: "shazam" - }; - - view = EmberView.create({ - context: context, - template: EmberHandlebars.compile('<h1 id="first">{{#with content}}{{wham}}-{{../blam}}{{/with}}</h1>') - }); - - appendView(); - - equal(view.$('#first').text(), "bam-shazam", "renders parent properties"); -}); - test("using Handlebars helper that doesn't exist should result in an error", function() { var names = [{ name: 'Alex' }, { name: 'Stef' }]; var context = { content: A(names) }; @@ -430,28 +395,6 @@ test("using Handlebars helper that doesn't exist should result in an error", fun }, "Missing helper: 'group'"); }); -test("View should bind properties in the grandparent context", function() { - var context = { - content: EmberObject.create({ - wham: 'bam', - thankYou: EmberObject.create({ - value: "ma'am" - }) - }), - - blam: "shazam" - }; - - view = EmberView.create({ - context: context, - template: EmberHandlebars.compile('<h1 id="first">{{#with content}}{{#with thankYou}}{{value}}-{{../wham}}-{{../../blam}}{{/with}}{{/with}}</h1>') - }); - - appendView(); - - equal(view.$('#first').text(), "ma'am-bam-shazam", "renders grandparent properties"); -}); - test("View should update when a property changes and the bind helper is used", function() { container.register('template:foo', EmberHandlebars.compile('<h1 id="first">{{#with view.content}}{{bind "wham"}}{{/with}}</h1>')); @@ -1049,7 +992,7 @@ test("itemViewClass works in the #collection helper with a global (DEPRECATED)", exampleController: ArrayProxy.create({ content: A(['alpha']) }), - template: EmberHandlebars.compile('{{#collection content=view.exampleController itemViewClass="TemplateTests.ExampleItemView"}}beta{{/collection}}') + template: EmberHandlebars.compile('{{#collection content=view.exampleController itemViewClass=TemplateTests.ExampleItemView}}beta{{/collection}}') }); expectDeprecation(function(){ @@ -1059,21 +1002,20 @@ test("itemViewClass works in the #collection helper with a global (DEPRECATED)", ok(firstGrandchild(view).isAlsoCustom, "uses the example view class specified in the #collection helper"); }); -test("itemViewClass works in the #collection helper relatively", function() { +test("itemViewClass works in the #collection helper with a property", function() { var ExampleItemView = EmberView.extend({ isAlsoCustom: true }); - var ExampleCollectionView = CollectionView.extend({ - possibleItemView: ExampleItemView - }); + var ExampleCollectionView = CollectionView; view = EmberView.create({ + possibleItemView: ExampleItemView, exampleCollectionView: ExampleCollectionView, exampleController: ArrayProxy.create({ content: A(['alpha']) }), - template: EmberHandlebars.compile('{{#collection view.exampleCollectionView content=view.exampleController itemViewClass="possibleItemView"}}beta{{/collection}}') + template: EmberHandlebars.compile('{{#collection view.exampleCollectionView content=view.exampleController itemViewClass=view.possibleItemView}}beta{{/collection}}') }); run(function() { @@ -1168,27 +1110,6 @@ test("should not update boundIf if truthiness does not change", function() { equal(view.$('#first').text(), "bam", "renders block when condition is true"); }); -test("boundIf should support parent access", function() { - view = EmberView.create({ - template: EmberHandlebars.compile( - '<h1 id="first">{{#with view.content}}{{#with thankYou}}'+ - '{{#boundIf ../view.show}}parent{{/boundIf}}-{{#boundIf ../../view.show}}grandparent{{/boundIf}}'+ - '{{/with}}{{/with}}</h1>' - ), - - content: EmberObject.create({ - show: true, - thankYou: EmberObject.create() - }), - - show: true - }); - - appendView(); - - equal(view.$('#first').text(), "parent-grandparent", "renders boundIfs using .."); -}); - test("{{view}} id attribute should set id on layer", function() { container.register('template:foo', EmberHandlebars.compile('{{#view view.idView id="bar"}}baz{{/view}}')); @@ -1533,14 +1454,6 @@ test("should be able to bind to globals with {{bind-attr}} (DEPRECATED)", functi }, /Global lookup of TemplateTests.value from a Handlebars template is deprecated/); equal(view.$('img').attr('alt'), "Test", "renders initial value"); - - expectDeprecation(function(){ - run(function() { - TemplateTests.set('value', 'Updated'); - }); - }, /Global lookup of TemplateTests.value from a Handlebars template is deprecated/); - - equal(view.$('img').attr('alt'), "Updated", "updates value"); }); test("should not allow XSS injection via {{bind-attr}}", function() { @@ -1820,14 +1733,6 @@ test("should be able to bind classes to globals with {{bind-attr class}} (DEPREC }, /Global lookup of TemplateTests.isOpen from a Handlebars template is deprecated/); ok(view.$('img').hasClass('is-open'), "sets classname to the dasherized value of the global property"); - - expectDeprecation(function(){ - run(function() { - TemplateTests.set('isOpen', false); - }); - }, /Global lookup of TemplateTests.isOpen from a Handlebars template is deprecated/); - - ok(!view.$('img').hasClass('is-open'), "removes the classname when the global property has changed"); }); test("should be able to bind-attr to 'this' in an {{#each}} block", function() { @@ -1885,23 +1790,19 @@ test("should be able to output a property without binding", function() { var context = { content: EmberObject.create({ anUnboundString: "No spans here, son." - }), - - anotherUnboundString: "Not here, either." + }) }; view = EmberView.create({ context: context, template: EmberHandlebars.compile( - '<div id="first">{{unbound content.anUnboundString}}</div>'+ - '{{#with content}}<div id="second">{{unbound ../anotherUnboundString}}</div>{{/with}}' + '<div id="first">{{unbound content.anUnboundString}}</div>' ) }); appendView(); equal(view.$('#first').html(), "No spans here, son."); - equal(view.$('#second').html(), "Not here, either."); }); test("should allow standard Handlebars template usage", function() { @@ -2151,22 +2052,18 @@ QUnit.module("Ember.View - handlebars integration", { test("should be able to log a property", function() { var context = { - value: 'one', - valueTwo: 'two', - - content: EmberObject.create({}) + value: 'one' }; view = EmberView.create({ context: context, - template: EmberHandlebars.compile('{{log value}}{{#with content}}{{log ../valueTwo}}{{/with}}') + template: EmberHandlebars.compile('{{log value}}') }); appendView(); equal(view.$().text(), "", "shouldn't render any text"); equal(logCalls[0], 'one', "should call log with value"); - equal(logCalls[1], 'two', "should call log with valueTwo"); }); test("should be able to log a view property", function() { @@ -2592,11 +2489,11 @@ test("should teardown observers from bind-attr on rerender", function() { appendView(); - equal(observersFor(view, 'foo').length, 2); + equal(observersFor(view, 'foo').length, 1); run(function() { view.rerender(); }); - equal(observersFor(view, 'foo').length, 2); + equal(observersFor(view, 'foo').length, 1); });
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/tests/helpers/bound_helper_test.js
@@ -101,7 +101,7 @@ test("bound helpers should support options", function() { appendView(); - ok(view.$().text() === 'ababab', "helper output is correct"); + equal(view.$().text(), 'ababab', "helper output is correct"); }); test("bound helpers should support keywords", function() { @@ -116,7 +116,7 @@ test("bound helpers should support keywords", function() { appendView(); - ok(view.$().text() === 'AB', "helper output is correct"); + equal(view.$().text(), 'AB', "helper output is correct"); }); test("bound helpers should support global paths [DEPRECATED]", function() { @@ -134,7 +134,7 @@ test("bound helpers should support global paths [DEPRECATED]", function() { appendView(); }, /Global lookup of Text from a Handlebars template is deprecated/); - ok(view.$().text() === 'AB', "helper output is correct"); + equal(view.$().text(), 'AB', "helper output is correct"); }); test("bound helper should support this keyword", function() { @@ -149,7 +149,7 @@ test("bound helper should support this keyword", function() { appendView(); - ok(view.$().text() === 'AB', "helper output is correct"); + equal(view.$().text(), 'AB', "helper output is correct"); }); test("bound helpers should support bound options", function() { @@ -433,5 +433,3 @@ test("bound helpers can handle `this` keyword when it's a non-object", function( run(view.controller.things, 'pushObject', 'wallace'); equal(view.$().text(), 'wallace!', "helper output is correct"); }); - -
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/tests/helpers/each_test.js
@@ -440,7 +440,7 @@ test("it defers all normalization of itemView names to the resolver", function() test("it supports {{itemViewClass=}} with global (DEPRECATED)", function() { run(function() { view.destroy(); }); // destroy existing view view = EmberView.create({ - template: templateFor('{{each view.people itemViewClass="MyView"}}'), + template: templateFor('{{each view.people itemViewClass=MyView}}'), people: people }); @@ -473,7 +473,7 @@ test("it supports {{itemViewClass=}} via container", function() { test("it supports {{itemViewClass=}} with tagName (DEPRECATED)", function() { run(function() { view.destroy(); }); // destroy existing view view = EmberView.create({ - template: templateFor('{{each view.people itemViewClass="MyView" tagName="ul"}}'), + template: templateFor('{{each view.people itemViewClass=MyView tagName="ul"}}'), people: people });
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/tests/helpers/view_test.js
@@ -86,27 +86,6 @@ test("View lookup - App.FuView (DEPRECATED)", function() { equal(jQuery('#fu').text(), 'bro'); }); -test("View lookup - 'App.FuView' (DEPRECATED)", function() { - Ember.lookup = { - App: { - FuView: viewClass({ - elementId: "fu", - template: Ember.Handlebars.compile("bro") - }) - } - }; - - view = viewClass({ - template: Ember.Handlebars.compile("{{view 'App.FuView'}}") - }).create(); - - expectDeprecation(function(){ - run(view, 'appendTo', '#qunit-fixture'); - }, /Resolved the view "App.FuView" on the global context/); - - equal(jQuery('#fu').text(), 'bro'); -}); - test("View lookup - 'fu'", function() { var FuView = viewClass({ elementId: "fu", @@ -217,6 +196,7 @@ test("allows you to pass attributes that will be assigned to the class instance, ok(jQuery('#bar').hasClass('bar')); equal(jQuery('#bar').text(), 'Bar'); }); + test("Should apply class without condition always", function() { view = EmberView.create({ context: [], @@ -227,5 +207,4 @@ test("Should apply class without condition always", function() { run(view, 'appendTo', '#qunit-fixture'); ok(jQuery('#foo').hasClass('foo'), "Always applies classbinding without condition"); - });
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/tests/helpers/with_test.js
@@ -121,6 +121,7 @@ test("nested {{with}} blocks shadow the outer scoped variable properly.", functi equal(view.$().text(), "Limbo-Wrath-Treachery-Wrath-Limbo", "should be properly scoped after updating"); }); + QUnit.module("Handlebars {{#with}} globals helper [DEPRECATED]", { setup: function() { Ember.lookup = lookup = { Ember: Ember }; @@ -129,10 +130,6 @@ QUnit.module("Handlebars {{#with}} globals helper [DEPRECATED]", { view = EmberView.create({ template: EmberHandlebars.compile("{{#with Foo.bar as qux}}{{qux}}{{/with}}") }); - - ignoreDeprecation(function() { - appendView(view); - }); }, teardown: function() { @@ -144,14 +141,16 @@ QUnit.module("Handlebars {{#with}} globals helper [DEPRECATED]", { }); test("it should support #with Foo.bar as qux [DEPRECATED]", function() { - equal(view.$().text(), "baz", "should be properly scoped"); - expectDeprecation(function() { - run(function() { - set(lookup.Foo, 'bar', 'updated'); - }); + appendView(view); }, /Global lookup of Foo.bar from a Handlebars template is deprecated/); + equal(view.$().text(), "baz", "should be properly scoped"); + + run(function() { + set(lookup.Foo, 'bar', 'updated'); + }); + equal(view.$().text(), "updated", "should update"); });
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/tests/lookup_test.js
@@ -1,133 +0,0 @@ -QUnit.module("Ember.Handlebars.resolveParams"); - -test("Raw string parameters should be returned as Strings", function() { - var params = Ember.Handlebars.resolveParams({}, ["foo", "bar", "baz"], { types: ["STRING", "STRING", "STRING"] }); - deepEqual(params, ["foo", "bar", "baz"]); -}); - -test("Raw boolean parameters should be returned as Booleans", function() { - var params = Ember.Handlebars.resolveParams({}, [true, false], { types: ["BOOLEAN", "BOOLEAN"] }); - deepEqual(params, [true, false]); -}); - -test("Raw numeric parameters should be returned as Numbers", function() { - var params = Ember.Handlebars.resolveParams({}, [1, 1.0, 1.5, 0.5], { types: ["NUMBER", "NUMBER", "NUMBER", "NUMBER"] }); - deepEqual(params, [1, 1, 1.5, 0.5]); -}); - -test("ID parameters should be looked up on the context", function() { - var context = { - salutation: "Mr", - name: { - first: "Tom", - last: "Dale" - } - }; - - var params = Ember.Handlebars.resolveParams(context, ["salutation", "name.first", "name.last"], { types: ["ID", "ID", "ID"] }); - deepEqual(params, ["Mr", "Tom", "Dale"]); -}); - -test("ID parameters that start with capital letters fall back to Ember.lookup as their context (DEPRECATED)", function() { - Ember.lookup.Global = "I'm going global, what you ain't a local?"; - - var context = {}, params; - - expectDeprecation(function(){ - params = Ember.Handlebars.resolveParams(context, ["Global"], { types: ["ID"] }); - }, /Global lookup of Global from a Handlebars template is deprecated./); - deepEqual(params, [Ember.lookup.Global]); -}); - -test("ID parameters that start with capital letters look up on given context first", function() { - Ember.lookup.Global = "I'm going global, what you ain't a local?"; - - var context = { Global: "Steal away from lookup" }; - - var params = Ember.Handlebars.resolveParams(context, ["Global"], { types: ["ID"] }); - deepEqual(params, [context.Global]); -}); - -test("ID parameters can look up keywords", function() { - var controller = { - salutation: "Mr" - }; - - var view = { - name: { first: "Tom", last: "Dale" } - }; - - var context = { - yuno: "State Charts" - }; - - var options = { - types: ["ID", "ID", "ID", "ID"], - data: { - keywords: { - controller: controller, - view: view - } - } - }; - - var params = Ember.Handlebars.resolveParams(context, ["controller.salutation", "view.name.first", "view.name.last", "yuno"], options); - deepEqual(params, ["Mr", "Tom", "Dale", "State Charts"]); -}); - -QUnit.module("Ember.Handlebars.resolveHash"); - -test("Raw string parameters should be returned as Strings", function() { - var hash = Ember.Handlebars.resolveHash({}, { string: "foo" }, { hashTypes: { string: "STRING" } }); - deepEqual(hash, { string: "foo" }); -}); - -test("Raw boolean parameters should be returned as Booleans", function() { - var hash = Ember.Handlebars.resolveHash({}, { yes: true, no: false }, { hashTypes: { yes: "BOOLEAN", no: "BOOLEAN" } }); - deepEqual(hash, { yes: true, no: false }); -}); - -test("Raw numeric parameters should be returned as Numbers", function() { - var hash = Ember.Handlebars.resolveHash({}, { one: 1, oneFive: 1.5, ohFive: 0.5 }, { hashTypes: { one: "NUMBER", oneFive: "NUMBER", ohFive: "NUMBER" } }); - deepEqual(hash, { one: 1, oneFive: 1.5, ohFive: 0.5 }); -}); - -test("ID parameters should be looked up on the context", function() { - var context = { - salutation: "Mr", - name: { - first: "Tom", - last: "Dale" - } - }; - - var hash = Ember.Handlebars.resolveHash(context, { mr: "salutation", firstName: "name.first", lastName: "name.last" }, { hashTypes: { mr: "ID", firstName: "ID", lastName: "ID" } }); - deepEqual(hash, { mr: "Mr", firstName: "Tom", lastName: "Dale" }); -}); - -test("ID parameters can look up keywords", function() { - var controller = { - salutation: "Mr" - }; - - var view = { - name: { first: "Tom", last: "Dale" } - }; - - var context = { - yuno: "State Charts" - }; - - var options = { - hashTypes: { mr: "ID", firstName: "ID", lastName: "ID", yuno: "ID" }, - data: { - keywords: { - controller: controller, - view: view - } - } - }; - - var hash = Ember.Handlebars.resolveHash(context, { mr: "controller.salutation", firstName: "view.name.first", lastName: "view.name.last", yuno: "yuno" }, options); - deepEqual(hash, { mr: "Mr", firstName: "Tom", lastName: "Dale", yuno: "State Charts" }); -});
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/tests/views/collection_view_test.js
@@ -350,6 +350,28 @@ test("should give its item views the property specified by itemPropertyBinding", equal(view.$('ul li:first').text(), "yobaz", "change property of sub view"); }); +test("should unsubscribe stream bindings", function() { + view = EmberView.create({ + baz: "baz", + content: A([EmberObject.create(), EmberObject.create(), EmberObject.create()]), + template: EmberHandlebars.compile('{{#collection contentBinding="view.content" itemPropertyBinding="view.baz"}}{{view.property}}{{/collection}}') + }); + + run(function() { + view.appendTo('#qunit-fixture'); + }); + + var barStreamBinding = view._streamBindings['view.baz']; + + equal(barStreamBinding.subscribers.length, 3*2, "adds 3 subscribers"); + + run(function() { + view.get('content').popObject(); + }); + + equal(barStreamBinding.subscribers.length, 2*2, "removes 1 subscriber"); +}); + test("should work inside a bound {{#if}}", function() { var testData = A([EmberObject.create({ isBaz: false }), EmberObject.create({ isBaz: true }), EmberObject.create({ isBaz: true })]); var IfTestCollectionView = CollectionView.extend({
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/tests/views/handlebars_bound_view_test.js
@@ -1,14 +1,16 @@ +import Stream from "ember-metal/streams/stream"; import { SimpleHandlebarsView } from 'ember-handlebars/views/handlebars_bound_view'; QUnit.module('SimpleHandlebarsView'); test('does not render if update is triggured by normalizedValue is the same as the previous normalizedValue', function(){ var value = null; - var path = 'foo'; - var pathRoot = { 'foo': 'bar' }; + var obj = { 'foo': 'bar' }; + var lazyValue = new Stream(function() { + return obj.foo; + }); var isEscaped = true; - var templateData; - var view = new SimpleHandlebarsView(path, pathRoot, isEscaped, templateData); + var view = new SimpleHandlebarsView(lazyValue, isEscaped); view._morph = { update: function(newValue) { value = newValue; @@ -26,7 +28,8 @@ test('does not render if update is triggured by normalizedValue is the same as t equal(value, null, 'expected no call to morph.update'); - pathRoot.foo = 'baz'; // change property + obj.foo = 'baz'; // change property + lazyValue.notify(); view.update();
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-handlebars/tests/views/metamorph_view_test.js
@@ -141,7 +141,7 @@ test("a metamorph view calls its childrens' willInsertElement and didInsertEleme } }), - template: EmberHandlebars.compile('{{#if view.condition}}{{view "view.ViewWithCallback"}}{{/if}}'), + template: EmberHandlebars.compile('{{#if view.condition}}{{view view.ViewWithCallback}}{{/if}}'), condition: false });
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-metal/lib/mixin.js
@@ -13,6 +13,8 @@ import { import { create as o_create } from "ember-metal/platform"; +import { get } from "ember-metal/property_get"; +import { set, trySet } from "ember-metal/property_set"; import { guidFor, meta as metaFor, @@ -31,7 +33,8 @@ import { addObserver, removeObserver, addBeforeObserver, - removeBeforeObserver + removeBeforeObserver, + _suspendObserver } from "ember-metal/observer"; import { addListener, @@ -307,6 +310,31 @@ function detectBinding(obj, key, value, m) { } } +function connectStreamBinding(obj, key, stream) { + var onNotify = function(stream) { + _suspendObserver(obj, key, null, didChange, function() { + trySet(obj, key, stream.value()); + }); + }; + + var didChange = function() { + stream.setValue(get(obj, key), onNotify); + }; + + // Initialize value + set(obj, key, stream.value()); + + addObserver(obj, key, null, didChange); + + stream.subscribe(onNotify); + + if (obj._streamBindingSubscriptions === undefined) { + obj._streamBindingSubscriptions = Object.create(null); + } + + obj._streamBindingSubscriptions[key] = onNotify; +} + function connectBindings(obj, m) { // TODO Mixin.apply(instance) should disconnect binding if exists var bindings = m.bindings; @@ -316,7 +344,10 @@ function connectBindings(obj, m) { binding = bindings[key]; if (binding) { to = key.slice(0, -7); // strip Binding off end - if (binding instanceof Binding) { + if (binding.isStream) { + connectStreamBinding(obj, to, binding); + continue; + } else if (binding instanceof Binding) { binding = binding.copy(); // copy prototypes' instance binding.to(to); } else { // binding is string path
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-metal/lib/path_cache.js
@@ -4,16 +4,34 @@ var IS_GLOBAL = /^([A-Z$]|([0-9][A-Z$]))/; var IS_GLOBAL_PATH = /^([A-Z$]|([0-9][A-Z$])).*[\.]/; var HAS_THIS = 'this.'; -var isGlobalCache = new Cache(1000, function(key) { return IS_GLOBAL.test(key); }); -var isGlobalPathCache = new Cache(1000, function(key) { return IS_GLOBAL_PATH.test(key); }); -var hasThisCache = new Cache(1000, function(key) { return key.indexOf(HAS_THIS) !== -1; }); -var isPathCache = new Cache(1000, function(key) { return key.indexOf('.') !== -1; }); +var isGlobalCache = new Cache(1000, function(key) { return IS_GLOBAL.test(key); }); +var isGlobalPathCache = new Cache(1000, function(key) { return IS_GLOBAL_PATH.test(key); }); +var hasThisCache = new Cache(1000, function(key) { return key.indexOf(HAS_THIS) !== -1; }); +var firstDotIndexCache = new Cache(1000, function(key) { return key.indexOf('.'); }); + +var firstKeyCache = new Cache(1000, function(path) { + var index = firstDotIndexCache.get(path); + if (index === -1) { + return path; + } else { + return path.slice(0, index); + } +}); + +var tailPathCache = new Cache(1000, function(path) { + var index = firstDotIndexCache.get(path); + if (index !== -1) { + return path.slice(index + 1); + } +}); export var caches = { - isGlobalCache: isGlobalCache, - isGlobalPathCache: isGlobalPathCache, - hasThisCache: hasThisCache, - isPathCache: isPathCache + isGlobalCache: isGlobalCache, + isGlobalPathCache: isGlobalPathCache, + hasThisCache: hasThisCache, + firstDotIndexCache: firstDotIndexCache, + firstKeyCache: firstKeyCache, + tailPathCache: tailPathCache }; export function isGlobal(path) { @@ -29,5 +47,13 @@ export function hasThis(path) { } export function isPath(path) { - return isPathCache.get(path); + return firstDotIndexCache.get(path) !== -1; +} + +export function getFirstKey(path) { + return firstKeyCache.get(path); +} + +export function getTailPath(path) { + return tailPathCache.get(path); }
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-metal/lib/streams/read.js
@@ -0,0 +1,24 @@ +export function read(object) { + if (object && object.isStream) { + return object.value(); + } else { + return object; + } +} + +export function readArray(array) { + var length = array.length; + var ret = new Array(length); + for (var i = 0; i < length; i++) { + ret[i] = read(array[i]); + } + return ret; +} + +export function readHash(object) { + var ret = {}; + for (var key in object) { + ret[key] = read(object[key]); + } + return ret; +}
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-metal/lib/streams/simple.js
@@ -0,0 +1,51 @@ +import merge from "ember-metal/merge"; +import Stream from "ember-metal/streams/stream"; +import { create } from "ember-metal/platform"; +import { read } from "ember-metal/streams/read"; + +function SimpleStream(source) { + this.source = source; + + if (source && source.isStream) { + source.subscribe(this._didChange, this); + } +} + +SimpleStream.prototype = create(Stream.prototype); + +merge(SimpleStream.prototype, { + valueFn: function() { + return read(this.source); + }, + + setSource: function(nextSource) { + var prevSource = this.source; + if (nextSource !== prevSource) { + if (prevSource && prevSource.isStream) { + prevSource.unsubscribe(this._didChange, this); + } + + if (nextSource && nextSource.isStream) { + nextSource.subscribe(this._didChange, this); + } + + this.source = nextSource; + this.notify(); + } + }, + + _didChange: function() { + this.notify(); + }, + + destroy: function() { + if (this.source && this.source.isStream) { + this.source.unsubscribe(this._didChange, this); + } + + this.source = undefined; + Stream.prototype.destroy.call(this); + } +}); + +export default SimpleStream;
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-metal/lib/streams/stream.js
@@ -0,0 +1,129 @@ +import { + getFirstKey, + getTailPath +} from "ember-metal/path_cache"; + +var NIL = function NIL(){}; + +function Stream(fn) { + this.valueFn = fn; + this.cache = NIL; + this.subscribers = undefined; + this.children = undefined; + this.destroyed = false; +} + +Stream.prototype = { + isStream: true, + + cache: NIL, + + get: function(path) { + var firstKey = getFirstKey(path); + var tailPath = getTailPath(path); + + if (this.children === undefined) { + this.children = Object.create(null); + } + + var keyStream = this.children[firstKey]; + + if (keyStream === undefined) { + keyStream = this._makeChildStream(firstKey, path); + this.children[firstKey] = keyStream; + } + + if (tailPath === undefined) { + return keyStream; + } else { + return keyStream.get(tailPath); + } + }, + + value: function() { + if (this.cache !== NIL) { + return this.cache; + } else { + return this.cache = this.valueFn(); + } + }, + + setValue: function() { + throw new Error("Stream error: setValue not implemented"); + }, + + notifyAll: function() { + this.notify(); + }, + + notify: function(callbackToSkip, contextToSkip) { + if (this.cache !== NIL) { + this.cache = NIL; + this.notifySubscribers(callbackToSkip, contextToSkip); + } + }, + + subscribe: function(callback, context) { + if (this.subscribers === undefined) { + this.subscribers = [callback, context]; + } else { + this.subscribers.push(callback, context); + } + }, + + unsubscribe: function(callback, context) { + var subscribers = this.subscribers; + + if (subscribers !== undefined) { + for (var i = 0, l = subscribers.length; i < l; i += 2) { + if (subscribers[i] === callback && subscribers[i+1] === context) { + subscribers.splice(i, 2); + return; + } + } + } + }, + + notifySubscribers: function(callbackToSkip, contextToSkip) { + var subscribers = this.subscribers; + + if (subscribers !== undefined) { + for (var i = 0, l = subscribers.length; i < l; i += 2) { + var callback = subscribers[i]; + var context = subscribers[i+1]; + + if (callback === callbackToSkip && context === contextToSkip) { + continue; + } + + if (context === undefined) { + callback(this); + } else { + callback.call(context, this); + } + } + } + }, + + destroy: function() { + if (this.destroyed) return; + this.destroyed = true; + + var children = this.children; + for (var key in children) { + children[key].destroy(); + } + }, + + isGlobal: function() { + var stream = this; + while (stream !== undefined) { + if (stream._isRoot) { + return stream._isGlobal; + } + stream = stream.source; + } + } +}; + +export default Stream;
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-metal/lib/streams/stream_binding.js
@@ -0,0 +1,74 @@ +import { create } from "ember-metal/platform"; +import merge from "ember-metal/merge"; +import run from "ember-metal/run_loop"; +import Stream from "ember-metal/streams/stream"; + +function StreamBinding(stream) { + Ember.assert("StreamBinding error: tried to bind to object that is not a stream", stream && stream.isStream); + + this.stream = stream; + this.senderCallback = undefined; + this.senderContext = undefined; + this.senderValue = undefined; + this.destroyed = false; + + stream.subscribe(this._onNotify, this); +} + +StreamBinding.prototype = create(Stream.prototype); + +merge(StreamBinding.prototype, { + valueFn: function() { + return this.stream.value(); + }, + + _onNotify: function() { + this._scheduleSync(undefined, undefined, this); + }, + + setValue: function(value, callback, context) { + this._scheduleSync(value, callback, context); + }, + + _scheduleSync: function(value, callback, context) { + if (this.senderCallback === undefined && this.senderContext === undefined) { + this.senderCallback = callback; + this.senderContext = context; + this.senderValue = value; + run.schedule('sync', this, this._sync); + } else if (this.senderContext !== this) { + this.senderCallback = callback; + this.senderContext = context; + this.senderValue = value; + } + }, + + _sync: function() { + if (this.destroyed) { + return; + } + + if (this.senderContext !== this) { + this.stream.setValue(this.senderValue); + } + + var senderCallback = this.senderCallback; + var senderContext = this.senderContext; + this.senderCallback = undefined; + this.senderContext = undefined; + this.senderValue = undefined; + + this.notify(senderCallback, senderContext); + }, + + destroy: function() { + if (this.destroyed) { + return; + } + + this.destroyed = true; + this.stream.unsubscribe(this._onNotify, this); + } +}); + +export default StreamBinding;
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-metal/tests/streams/stream_binding_test.js
@@ -0,0 +1,121 @@ +import { get } from "ember-metal/property_get"; +import { set } from "ember-metal/property_set"; +import { mixin } from "ember-metal/mixin"; +import run from 'ember-metal/run_loop'; +import Stream from "ember-metal/streams/stream"; +import StreamBinding from "ember-metal/streams/stream_binding"; + +var source, value; + +QUnit.module('Stream Binding', { + setup: function() { + value = "zlurp"; + + source = new Stream(function() { + return value; + }); + + source.setValue = function(_value, callback, context) { + value = _value; + this.notify(callback, context); + }; + }, + teardown: function() { + value = undefined; + source = undefined; + } +}); + +test('basic', function() { + var binding = new StreamBinding(source); + + equal(binding.value(), "zlurp"); + + run(function() { + source.setValue("blorg"); + }); + + equal(binding.value(), "blorg"); + + binding.destroy(); // destroy should not fail +}); + +test('the source stream can send values to a single subscriber)', function() { + var binding = new StreamBinding(source); + var obj = mixin({}, { toBinding: binding }); + + equal(get(obj, 'to'), "zlurp", "immediately syncs value forward on init"); + + run(function() { + source.setValue("blorg"); + equal(get(obj, 'to'), "zlurp", "does not immediately sync value on set"); + }); + + equal(get(obj, 'to'), "blorg", "value has synced after run loop"); +}); + +test('the source stream can send values to multiple subscribers', function() { + var binding = new StreamBinding(source); + var obj1 = mixin({}, { toBinding: binding }); + var obj2 = mixin({}, { toBinding: binding }); + + equal(get(obj1, 'to'), "zlurp", "immediately syncs value forward on init"); + equal(get(obj2, 'to'), "zlurp", "immediately syncs value forward on init"); + + run(function() { + source.setValue("blorg"); + equal(get(obj1, 'to'), "zlurp", "does not immediately sync value on set"); + equal(get(obj2, 'to'), "zlurp", "does not immediately sync value on set"); + }); + + equal(get(obj1, 'to'), "blorg", "value has synced after run loop"); + equal(get(obj2, 'to'), "blorg", "value has synced after run loop"); +}); + +test('a subscriber can set the value on the source stream and notify the other subscribers', function() { + var binding = new StreamBinding(source); + var obj1 = mixin({}, { toBinding: binding }); + var obj2 = mixin({}, { toBinding: binding }); + + run(function() { + set(obj1, 'to', "blorg"); + equal(get(obj2, 'to'), "zlurp", "does not immediately sync value on set"); + equal(source.value(), "zlurp", "does not immediately sync value on set"); + }); + + equal(get(obj2, 'to'), "blorg", "value has synced after run loop"); + equal(source.value(), "blorg", "value has synced after run loop"); +}); + +test('if source and subscribers sync value, source wins', function() { + var binding = new StreamBinding(source); + var obj1 = mixin({}, { toBinding: binding }); + var obj2 = mixin({}, { toBinding: binding }); + var obj3 = mixin({}, { toBinding: binding }); + + run(function() { + set(obj1, 'to', "blorg"); + source.setValue("hoopla"); + set(obj2, 'to', "flarp"); + equal(get(obj3, 'to'), "zlurp", "does not immediately sync value on set"); + }); + + equal(source.value(), "hoopla", "value has synced after run loop"); + equal(get(obj1, 'to'), "hoopla", "value has synced after run loop"); + equal(get(obj2, 'to'), "hoopla", "value has synced after run loop"); + equal(get(obj3, 'to'), "hoopla", "value has synced after run loop"); +}); + +test('the last value sent by the source wins', function() { + var binding = new StreamBinding(source); + var obj = mixin({}, { toBinding: binding }); + + run(function() { + source.setValue("blorg"); + source.setValue("hoopla"); + equal(get(obj, 'to'), "zlurp", "does not immediately sync value on set"); + }); + + equal(source.value(), "hoopla", "value has synced after run loop"); + equal(get(obj, 'to'), "hoopla", "value has synced after run loop"); +});
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-routing-handlebars/lib/helpers/action.js
@@ -3,30 +3,33 @@ import { forEach } from "ember-metal/array"; import { uuid } from "ember-metal/utils"; import run from "ember-metal/run_loop"; +import { readUnwrappedModel } from "ember-views/streams/read"; import { isSimpleClick } from "ember-views/system/utils"; import ActionManager from "ember-views/system/action_manager"; - import EmberHandlebars from "ember-handlebars"; -import { handlebarsGet } from "ember-handlebars/ext"; -import { - resolveParams -} from "ember-routing-handlebars/helpers/shared"; /** @module ember @submodule ember-routing */ -var a_slice = Array.prototype.slice; - -function args(options, actionName) { - var ret = []; - if (actionName) { ret.push(actionName); } +function actionArgs(parameters, actionName) { + var ret, i; - var types = options.options.types.slice(1); - var data = options.options.data; + if (actionName === undefined) { + ret = new Array(parameters.length); + for (i = 0; i < parameters.length; i++) { + ret[i] = readUnwrappedModel(parameters[i]); + } + } else { + ret = new Array(parameters.length + 1); + ret[0] = actionName; + for (i = 0; i < parameters.length; i++) { + ret[i + 1] = readUnwrappedModel(parameters[i]); + } + } - return ret.concat(resolveParams(options.context, options.params, { types: types, data: data })); + return ret; } var ActionHelper = {}; @@ -75,11 +78,13 @@ function ignoreKeyEvent(eventName, event, keyCode) { return isKeyEvent(eventName) && keyCode !== any && keyCode !== event.which.toString(); } -ActionHelper.registerAction = function(actionNameOrPath, options, allowedKeys) { +ActionHelper.registerAction = function(actionNameOrStream, options, allowedKeys) { var actionId = uuid(); + var eventName = options.eventName; + var parameters = options.parameters; ActionManager.registeredActions[actionId] = { - eventName: options.eventName, + eventName: eventName, handler: function handleRegisteredAction(event) { if (!isAllowedEvent(event, allowedKeys)) { return true; } @@ -91,44 +96,37 @@ ActionHelper.registerAction = function(actionNameOrPath, options, allowedKeys) { event.stopPropagation(); } - var target = options.target; - var parameters = options.parameters; - var eventName = options.eventName; - var actionName; + var target = options.target.value(); if (Ember.FEATURES.isEnabled("ember-routing-handlebars-action-with-key-code")) { if (ignoreKeyEvent(eventName, event, options.withKeyCode)) { return; } } - if (target.target) { - target = handlebarsGet(target.root, target.target, target.options); - } else { - target = target.root; - } + var actionName; - if (options.boundProperty) { - actionName = resolveParams(parameters.context, [actionNameOrPath], { types: ['ID'], data: parameters.options.data })[0]; + if (actionNameOrStream.isStream) { + actionName = actionNameOrStream.value(); if (typeof actionName === 'undefined' || typeof actionName === 'function') { + actionName = actionNameOrStream._originalPath; Ember.deprecate("You specified a quoteless path to the {{action}} helper '" + - actionNameOrPath + "' which did not resolve to an actionName." + - " Perhaps you meant to use a quoted actionName? (e.g. {{action '" + actionNameOrPath + "'}})."); - actionName = actionNameOrPath; + actionName + "' which did not resolve to an actionName." + + " Perhaps you meant to use a quoted actionName? (e.g. {{action '" + actionName + "'}})."); } } if (!actionName) { - actionName = actionNameOrPath; + actionName = actionNameOrStream; } run(function runRegisteredAction() { if (target.send) { - target.send.apply(target, args(parameters, actionName)); + target.send.apply(target, actionArgs(parameters, actionName)); } else { Ember.assert("The action '" + actionName + "' did not exist on " + target, typeof target[actionName] === 'function'); - target[actionName].apply(target, args(parameters)); + target[actionName].apply(target, actionArgs(parameters)); } }); } @@ -306,34 +304,42 @@ ActionHelper.registerAction = function(actionNameOrPath, options, allowedKeys) { @param {Hash} options */ export function actionHelper(actionName) { - var options = arguments[arguments.length - 1]; - var contexts = a_slice.call(arguments, 1, -1); + var length = arguments.length; + var options = arguments[length - 1]; + var view = options.data.view; var hash = options.hash; - var controller = options.data.keywords.controller; + var types = options.types; // create a hash to pass along to registerAction - var action = { + var parameters = []; + + var actionOptions = { eventName: hash.on || "click", - parameters: { - context: this, - options: options, - params: contexts - }, + parameters: parameters, view: options.data.view, bubbles: hash.bubbles, preventDefault: hash.preventDefault, - target: { options: options }, - withKeyCode: hash.withKeyCode, - boundProperty: options.types[0] === "ID" + target: view.getStream(hash.target || 'controller'), + withKeyCode: hash.withKeyCode }; - if (hash.target) { - action.target.root = this; - action.target.target = hash.target; - } else if (controller) { - action.target.root = controller; + var actionNameStream; + + if (types[0] === "ID") { + actionNameStream = view.getStream(actionName); + actionNameStream._originalPath = actionName; + } else { + actionNameStream = actionName; + } + + for (var i = 1; i < length - 1; i++) { + if (types[i] === "ID") { + parameters.push(view.getStream(arguments[i])); + } else { + parameters.push(arguments[i]); + } } - var actionId = ActionHelper.registerAction(actionName, action, hash.allowedKeys); + var actionId = ActionHelper.registerAction(actionNameStream, actionOptions, hash.allowedKeys); return new EmberHandlebars.SafeString('data-ember-action="' + actionId + '"'); }
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-routing-handlebars/lib/helpers/link_to.js
@@ -6,16 +6,14 @@ import { computed } from "ember-metal/computed"; import { fmt } from "ember-runtime/system/string"; import EmberObject from "ember-runtime/system/object"; +import ControllerMixin from "ember-runtime/mixins/controller"; import keys from "ember-metal/keys"; import { isSimpleClick } from "ember-views/system/utils"; import EmberComponent from "ember-views/views/component"; -import EmberHandlebars from "ember-handlebars"; import { viewHelper } from "ember-handlebars/helpers/view"; import { routeArgs } from "ember-routing/utils"; -import { - resolveParams, - resolvePaths -} from "ember-routing-handlebars/helpers/shared"; +import { stringifyValue } from "ember-handlebars/ext"; +import { read } from "ember-metal/streams/read"; import 'ember-handlebars'; @@ -41,14 +39,6 @@ var QueryParams = EmberObject.extend({ values: null }); -function getResolvedPaths(options) { - - var types = options.options.types; - var data = options.options.data; - - return resolvePaths(options.context, options.params, { types: types, data: data }); -} - /** `Ember.LinkView` renders an element whose `click` event triggers a transition of the application's instance of `Ember.Router` to @@ -235,40 +225,33 @@ var LinkView = Ember.LinkView = EmberComponent.extend({ @since 1.3.0 **/ _setupPathObservers: function(){ - var helperParameters = this.parameters; - var linkTextPath = helperParameters.options.linkTextPath; - var paths = getResolvedPaths(helperParameters); - var length = paths.length; - var path, i, normalizedPath; - - if (linkTextPath) { - normalizedPath = getNormalizedPath(linkTextPath, helperParameters); - this.registerObserver(normalizedPath.root, normalizedPath.path, this, this.rerender); + var params = this.params; + + var scheduledRerender = this._wrapAsScheduled(this.rerender); + var scheduledParamsChanged = this._wrapAsScheduled(this._paramsChanged); + + if (this.linkTitle) { + this.linkTitle.subscribe(scheduledRerender, this); } - for(i=0; i < length; i++) { - path = paths[i]; - if (null === path) { - // A literal value was provided, not a path, so nothing to observe. - continue; + for (var i = 0; i < params.length; i++) { + var param = params[i]; + if (param && param.isStream) { + param.subscribe(scheduledParamsChanged, this); } - - normalizedPath = getNormalizedPath(path, helperParameters); - this.registerObserver(normalizedPath.root, normalizedPath.path, this, this._paramsChanged); } var queryParamsObject = this.queryParamsObject; if (queryParamsObject) { var values = queryParamsObject.values; - - // Install observers for all of the hash options - // provided in the (query-params) subexpression. for (var k in values) { - if (!values.hasOwnProperty(k)) { continue; } + if (!values.hasOwnProperty(k)) { + continue; + } - if (queryParamsObject.types[k] === 'ID') { - normalizedPath = getNormalizedPath(values[k], helperParameters); - this.registerObserver(normalizedPath.root, normalizedPath.path, this, this._paramsChanged); + var value = values[k]; + if (value && value.isStream) { + value.subscribe(scheduledParamsChanged, this); } } } @@ -499,20 +482,20 @@ var LinkView = Ember.LinkView = EmberComponent.extend({ @return {Array} */ resolvedParams: computed('router.url', function() { - var parameters = this.parameters; - var options = parameters.options; - var types = options.types; - var data = options.data; - var targetRouteName, models; - var onlyQueryParamsSupplied = (parameters.params.length === 0); + var params = this.params; + var targetRouteName; + var models = []; + var onlyQueryParamsSupplied = (params.length === 0); if (onlyQueryParamsSupplied) { var appController = this.container.lookup('controller:application'); targetRouteName = get(appController, 'currentRouteName'); - models = []; } else { - models = resolveParams(parameters.context, parameters.params, { types: types, data: data }); - targetRouteName = models.shift(); + targetRouteName = read(params[0]); + + for (var i = 1; i < params.length; i++) { + models.push(read(params[i])); + } } var suppliedQueryParams = getResolvedQueryParams(this, targetRouteName); @@ -875,24 +858,33 @@ if (Ember.FEATURES.isEnabled("ember-routing-linkto-target-attribute")) { function linkToHelper(name) { var options = slice.call(arguments, -1)[0]; var params = slice.call(arguments, 0, -1); + var view = options.data.view; var hash = options.hash; + var hashTypes = options.hashTypes; + var types = options.types; + var shouldEscape = !hash.unescaped; + var queryParamsObject; Ember.assert("You must provide one or more parameters to the link-to helper.", params.length); if (params[params.length - 1] instanceof QueryParams) { - hash.queryParamsObject = params.pop(); + hash.queryParamsObject = queryParamsObject = params.pop(); } - hash.disabledBinding = hash.disabledWhen; + if (hash.disabledWhen) { + hash.disabledBinding = hash.disabledWhen; + hashTypes.disabledBinding = hashTypes.disabledWhen; + delete hash.disabledWhen; + delete hashTypes.disabledWhen; + } if (!options.fn) { var linkTitle = params.shift(); - var linkType = options.types.shift(); - var context = this; - if (linkType === 'ID') { - options.linkTextPath = linkTitle; + var linkTitleType = types.shift(); + if (linkTitleType === 'ID') { + hash.linkTitle = linkTitle = view.getStream(linkTitle); options.fn = function() { - return EmberHandlebars.getEscaped(context, linkTitle, options); + return stringifyValue(linkTitle.value(), shouldEscape); }; } else { options.fn = function() { @@ -901,11 +893,24 @@ function linkToHelper(name) { } } - hash.parameters = { - context: this, - options: options, - params: params - }; + // Setup route & param streams + for (var i = 0; i < params.length; i++) { + var paramPath = params[i]; + if (types[i] === 'ID') { + var lazyValue = view.getStream(paramPath); + + // TODO: Consider a better approach to unwrapping controllers. + if (paramPath !== 'controller') { + while (ControllerMixin.detect(lazyValue.value())) { + paramPath = (paramPath === '') ? 'model' : paramPath + '.model'; + lazyValue = view.getStream(paramPath); + } + } + params[i] = lazyValue; + } + } + + hash.params = params; options.helperName = options.helperName || 'link-to'; @@ -928,9 +933,18 @@ function linkToHelper(name) { export function queryParamsHelper(options) { Ember.assert(fmt("The `query-params` helper only accepts hash parameters, e.g. (query-params queryParamPropertyName='%@') as opposed to just (query-params '%@')", [options, options]), arguments.length === 1); + var view = options.data.view; + var hash = options.hash; + var hashTypes = options.hashTypes; + + for (var k in hash) { + if (hashTypes[k] === 'ID') { + hash[k] = view.getStream(hash[k]); + } + } + return QueryParams.create({ - values: options.hash, - types: options.hashTypes + values: options.hash }); } @@ -950,30 +964,18 @@ function deprecatedLinkToHelper() { } function getResolvedQueryParams(linkView, targetRouteName) { - var helperParameters = linkView.parameters; var queryParamsObject = linkView.queryParamsObject; var resolvedQueryParams = {}; if (!queryParamsObject) { return resolvedQueryParams; } - var rawParams = queryParamsObject.values; - - for (var key in rawParams) { - if (!rawParams.hasOwnProperty(key)) { continue; } - var value = rawParams[key]; - var type = queryParamsObject.types[key]; - - if (type === 'ID') { - var normalizedPath = getNormalizedPath(value, helperParameters); - value = EmberHandlebars.get(normalizedPath.root, normalizedPath.path, helperParameters.options); - } - resolvedQueryParams[key] = value; + var values = queryParamsObject.values; + for (var key in values) { + if (!values.hasOwnProperty(key)) { continue; } + resolvedQueryParams[key] = read(values[key]); } - return resolvedQueryParams; -} -function getNormalizedPath(path, helperParameters) { - return EmberHandlebars.normalizePath(helperParameters.context, path, helperParameters.options.data); + return resolvedQueryParams; } function paramsAreLoaded(params) {
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-routing-handlebars/lib/helpers/outlet.js
@@ -1,4 +1,5 @@ import Ember from "ember-metal/core"; // assert +import { set } from "ember-metal/property_set"; import ContainerView from "ember-views/views/container_view"; import { _Metamorph } from "ember-handlebars/views/metamorph_view"; import { viewHelper } from "ember-handlebars/helpers/view"; @@ -80,7 +81,6 @@ export { OutletView }; */ export function outletHelper(property, options) { var outletSource; - var container; var viewName; var viewClass; var viewFullName; @@ -90,12 +90,14 @@ export function outletHelper(property, options) { property = 'main'; } - container = options.data.view.container; + var view = options.data.view; + var container = view.container; - outletSource = options.data.view; + outletSource = view; while (!outletSource.get('template.isTop')) { outletSource = outletSource.get('_parentView'); } + set(view, 'outletSource', outletSource); // provide controller override viewName = options.hash.view; @@ -108,9 +110,10 @@ export function outletHelper(property, options) { } viewClass = viewName ? container.lookupFactory(viewFullName) : options.hash.viewClass || OutletView; + options.types = [ 'ID' ]; - options.hash.outletSource = outletSource; options.hash.currentViewBinding = '_view.outletSource._outlets.' + property; + options.hashTypes.currentViewBinding = 'STRING'; options.helperName = options.helperName || 'outlet';
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-routing-handlebars/lib/helpers/render.js
@@ -5,7 +5,6 @@ import { generateControllerFactory, default as generateController } from "ember-routing/system/generate_controller"; -import { handlebarsGet } from "ember-handlebars/ext"; import { ViewHelper } from "ember-handlebars/helpers/view"; /** @@ -85,9 +84,9 @@ You could render it inside the `post` template using the `render` helper. */ export default function renderHelper(name, contextString, options) { var length = arguments.length; - var container, router, controller, view, context; + var container, router, controller, view, initialContext; - container = (options || contextString).data.keywords.controller.container; + container = (options || contextString).data.view._keywords.controller.value().container; router = container.lookup('router:main'); if (length === 2) { @@ -98,7 +97,7 @@ export default function renderHelper(name, contextString, options) { " second argument, as in {{render \"post\" post}}.", !router || !router._lookupActiveView(name)); } else if (length === 3) { // create a new controller - context = handlebarsGet(options.contexts[1], contextString, options); + initialContext = options.data.view.getStream(contextString).value(); } else { throw new EmberError("You must pass a templateName to render"); } @@ -122,15 +121,15 @@ export default function renderHelper(name, contextString, options) { "' did not resolve to a controller.", container.has(controllerFullName)); } - var parentController = options.data.keywords.controller; + var parentController = options.data.view._keywords.controller.value(); // choose name if (length > 2) { var factory = container.lookupFactory(controllerFullName) || - generateControllerFactory(container, controllerName, context); + generateControllerFactory(container, controllerName, initialContext); controller = factory.create({ - model: context, + modelBinding: options.data.view._getBindingForStream(contextString), parentController: parentController, target: parentController }); @@ -148,14 +147,6 @@ export default function renderHelper(name, contextString, options) { }); } - var root = options.contexts[1]; - - if (root) { - view.registerObserver(root, contextString, function() { - controller.set('model', handlebarsGet(root, contextString, options)); - }); - } - options.hash.viewName = camelize(name); var templateName = 'template:' + name; @@ -165,7 +156,7 @@ export default function renderHelper(name, contextString, options) { options.hash.controller = controller; - if (router && !context) { + if (router && !initialContext) { router._connectActiveView(name, view); }
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-routing-handlebars/lib/helpers/shared.js
@@ -1,41 +0,0 @@ -import { get } from "ember-metal/property_get"; -import { map } from "ember-metal/array"; -import ControllerMixin from "ember-runtime/mixins/controller"; -import { - resolveParams as handlebarsResolve, - handlebarsGet -} from "ember-handlebars/ext"; - -export function resolveParams(context, params, options) { - return map.call(resolvePaths(context, params, options), function(path, i) { - if (null === path) { - // Param was string/number, not a path, so just return raw string/number. - return params[i]; - } else { - return handlebarsGet(context, path, options); - } - }); -} - -export function resolvePaths(context, params, options) { - var resolved = handlebarsResolve(context, params, options); - var types = options.types; - - return map.call(resolved, function(object, i) { - if (types[i] === 'ID') { - return unwrap(object, params[i]); - } else { - return null; - } - }); - - function unwrap(object, path) { - if (path === 'controller') { return path; } - - if (ControllerMixin.detect(object)) { - return unwrap(get(object, 'model'), path ? path + '.model' : 'model'); - } else { - return path; - } - } -}
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-routing-handlebars/lib/main.js
@@ -8,12 +8,6 @@ Ember Routing Handlebars import Ember from "ember-metal/core"; import EmberHandlebars from "ember-handlebars"; -import Router from "ember-routing/system/router"; - -import { - resolvePaths, - resolveParams -} from "ember-routing-handlebars/helpers/shared"; import { deprecatedLinkToHelper, @@ -34,9 +28,6 @@ import { actionHelper } from "ember-routing-handlebars/helpers/action"; -Router.resolveParams = resolveParams; -Router.resolvePaths = resolvePaths; - Ember.LinkView = LinkView; EmberHandlebars.ActionHelper = ActionHelper; EmberHandlebars.OutletView = OutletView;
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-routing-handlebars/tests/helpers/action_test.js
@@ -15,7 +15,6 @@ import EmberView from "ember-views/views/view"; import EmberComponent from "ember-views/views/component"; import jQuery from "ember-views/system/jquery"; -import "ember-routing-handlebars/helpers/shared"; import { ActionHelper, actionHelper @@ -99,7 +98,7 @@ test("should by default target the view's controller", function() { var controller = {}; ActionHelper.registerAction = function(actionName, options) { - registeredTarget = options.target; + registeredTarget = options.target.value(); }; view = EmberView.create({ @@ -109,7 +108,7 @@ test("should by default target the view's controller", function() { appendView(); - equal(registeredTarget.root, controller, "The controller was registered as the target"); + equal(registeredTarget, controller, "The controller was registered as the target"); ActionHelper.registerAction = originalRegisterAction; }); @@ -153,7 +152,7 @@ test("should target the current controller inside an {{each}} loop", function() var registeredTarget; ActionHelper.registerAction = function(actionName, options) { - registeredTarget = options.target; + registeredTarget = options.target.value(); }; var itemController = EmberObjectController.create(); @@ -176,7 +175,7 @@ test("should target the current controller inside an {{each}} loop", function() appendView(); - equal(registeredTarget.root, itemController, "the item controller is the target of action"); + equal(registeredTarget, itemController, "the item controller is the target of action"); ActionHelper.registerAction = originalRegisterAction; }); @@ -185,7 +184,7 @@ test("should target the with-controller inside an {{#with controller='person'}}" var registeredTarget; ActionHelper.registerAction = function(actionName, options) { - registeredTarget = options.target; + registeredTarget = options.target.value(); }; var PersonController = EmberObjectController.extend(); @@ -205,7 +204,7 @@ test("should target the with-controller inside an {{#with controller='person'}}" appendView(); - ok(registeredTarget.root instanceof PersonController, "the with-controller is the target of action"); + ok(registeredTarget instanceof PersonController, "the with-controller is the target of action"); ActionHelper.registerAction = originalRegisterAction; }); @@ -248,7 +247,7 @@ test("should allow a target to be specified", function() { var registeredTarget; ActionHelper.registerAction = function(actionName, options) { - registeredTarget = options.target; + registeredTarget = options.target.value(); }; var anotherTarget = EmberView.create(); @@ -261,8 +260,7 @@ test("should allow a target to be specified", function() { appendView(); - equal(registeredTarget.options.data.keywords.view, view, "The specified target was registered"); - equal(registeredTarget.target, 'view.anotherTarget', "The specified target was registered"); + equal(registeredTarget, anotherTarget, "The specified target was registered"); ActionHelper.registerAction = originalRegisterAction; @@ -302,7 +300,9 @@ test("should lazily evaluate the target", function() { equal(firstEdit, 1); - set(controller, 'theTarget', second); + run(function() { + set(controller, 'theTarget', second); + }); run(function() { jQuery('a').trigger('click'); @@ -691,6 +691,30 @@ test("should unwrap controllers passed as a context", function() { equal(passedContext, model, "the action was passed the unwrapped model"); }); +test("should not unwrap controllers passed as `controller`", function() { + var passedContext; + var model = EmberObject.create(); + var controller = EmberObjectController.extend({ + model: model, + actions: { + edit: function(context) { + passedContext = context; + } + } + }).create(); + + view = EmberView.create({ + controller: controller, + template: EmberHandlebars.compile('<button {{action "edit" controller}}>edit</button>') + }); + + appendView(); + + view.$('button').trigger('click'); + + equal(passedContext, controller, "the action was passed the controller"); +}); + test("should allow multiple contexts to be specified", function() { var passedContexts; var models = [EmberObject.create(), EmberObject.create()]; @@ -922,7 +946,9 @@ test("a quoteless parameter should allow dynamic lookup of the actionName", func }); var testBoundAction = function(propertyValue){ - controller.set('hookMeUp', propertyValue); + run(function() { + controller.set('hookMeUp', propertyValue); + }); run(function(){ view.$("#woot-bound-param").click();
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-views/lib/streams/context_stream.js
@@ -0,0 +1,44 @@ +import Ember from 'ember-metal/core'; + +import merge from "ember-metal/merge"; +import { create } from "ember-metal/platform"; +import { isGlobal } from "ember-metal/path_cache"; +import Stream from "ember-metal/streams/stream"; +import SimpleStream from "ember-metal/streams/simple"; + +function ContextStream(view) { + Ember.assert("ContextStream error: the argument is not a view", view && view.isView); + this.view = view; +} + +ContextStream.prototype = create(Stream.prototype); + +merge(ContextStream.prototype, { + value: function() {}, + + _makeChildStream: function(key, _fullPath) { + var stream; + + if (key === '' || key === 'this') { + stream = this.view._baseContext; + } else if (isGlobal(key) && Ember.lookup[key]) { + Ember.deprecate("Global lookup of " + _fullPath + " from a Handlebars template is deprecated."); + stream = new SimpleStream(Ember.lookup[key]); + stream._isGlobal = true; + } else if (key in this.view._keywords) { + stream = new SimpleStream(this.view._keywords[key]); + } else { + stream = new SimpleStream(this.view._baseContext.get(key)); + } + + stream._isRoot = true; + + if (key === 'controller') { + stream._isController = true; + } + + return stream; + } +}); + +export default ContextStream;
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-views/lib/streams/key_stream.js
@@ -0,0 +1,103 @@ +import Ember from 'ember-metal/core'; + +import merge from "ember-metal/merge"; +import { create } from "ember-metal/platform"; +import { get } from "ember-metal/property_get"; +import { set } from "ember-metal/property_set"; +import { + addObserver, + removeObserver +} from "ember-metal/observer"; +import Stream from "ember-metal/streams/stream"; +import { read } from "ember-metal/streams/read"; + +function KeyStream(source, key) { + Ember.assert("KeyStream error: key must be a non-empty string", typeof key === 'string' && key.length > 0); + Ember.assert("KeyStream error: key must not have a '.'", key.indexOf('.') === -1); + + this.source = source; + this.obj = undefined; + this.key = key; + + if (source && source.isStream) { + source.subscribe(this._didChange, this); + } +} + +KeyStream.prototype = create(Stream.prototype); + +merge(KeyStream.prototype, { + valueFn: function() { + var prevObj = this.obj; + var nextObj = read(this.source); + + if (nextObj !== prevObj) { + if (prevObj && typeof prevObj === 'object') { + removeObserver(prevObj, this.key, this, this._didChange); + } + + if (nextObj && typeof nextObj === 'object') { + addObserver(nextObj, this.key, this, this._didChange); + } + + this.obj = nextObj; + } + + if (nextObj) { + return get(nextObj, this.key); + } + }, + + setValue: function(value) { + if (this.obj) { + set(this.obj, this.key, value); + } + }, + + setSource: function(nextSource) { + Ember.assert("KeyStream error: source must be an object", typeof nextSource === 'object'); + + var prevSource = this.source; + + if (nextSource !== prevSource) { + if (prevSource && prevSource.isStream) { + prevSource.unsubscribe(this._didChange, this); + } + + if (nextSource && nextSource.isStream) { + nextSource.subscribe(this._didChange, this); + } + + this.source = nextSource; + this.notify(); + } + }, + + _didChange: function() { + this.notify(); + }, + + destroy: function() { + if (this.source && this.source.isStream) { + this.source.unsubscribe(this._didChange, this); + } + + if (this.obj && typeof this.obj === 'object') { + removeObserver(this.obj, this.key, this, this._didChange); + } + + this.source = undefined; + this.obj = undefined; + + Stream.prototype.destroy.call(this); + } +}); + +export default KeyStream; + +// The transpiler does not resolve cycles, so we export +// the `_makeChildStream` method onto `Stream` here. + +Stream.prototype._makeChildStream = function(key) { + return new KeyStream(this, key); +};
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-views/lib/streams/read.js
@@ -0,0 +1,45 @@ +import Ember from "ember-metal/core"; +import { get } from "ember-metal/property_get"; +import { isGlobal } from "ember-metal/path_cache"; +import { fmt } from "ember-runtime/system/string"; +import { read } from "ember-metal/streams/read"; +import View from "ember-views/views/view"; +import ControllerMixin from "ember-runtime/mixins/controller"; + +export function readViewFactory(object, container) { + var value = read(object); + var viewClass; + + if (typeof value === 'string') { + if (isGlobal(value)) { + viewClass = get(null, value); + Ember.deprecate('Resolved the view "'+value+'" on the global context. Pass a view name to be looked up on the container instead, such as {{view "select"}}. http://emberjs.com/guides/deprecations#toc_global-lookup-of-views-since-1-8', !viewClass); + } else { + Ember.assert("View requires a container to resolve views not passed in through the context", !!container); + viewClass = container.lookupFactory('view:'+value); + } + } else { + viewClass = value; + } + + Ember.assert(fmt(value+" must be a subclass of Ember.View, not %@", [viewClass]), View.detect(viewClass)); + + return viewClass; +} + +export function readUnwrappedModel(object) { + if (object && object.isStream) { + var result = object.value(); + + // If the path is exactly `controller` then we don't unwrap it. + if (!object._isController) { + while (ControllerMixin.detect(result)) { + result = get(result, 'model'); + } + } + + return result; + } else { + return object; + } +}
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-views/lib/views/collection_view.js
@@ -16,9 +16,7 @@ import { observer, beforeObserver } from "ember-metal/mixin"; -import { - handlebarsGetView -} from "ember-handlebars/ext"; +import { readViewFactory } from "ember-views/streams/read"; import EmberArray from "ember-runtime/mixins/array"; /** @@ -351,7 +349,7 @@ var CollectionView = ContainerView.extend({ if (len) { itemViewClass = get(this, 'itemViewClass'); - itemViewClass = handlebarsGetView(content, itemViewClass, this.container); + itemViewClass = readViewFactory(itemViewClass, this.container); for (idx = start; idx < start+added; idx++) { item = content.objectAt(idx);
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-views/lib/views/component.js
@@ -112,7 +112,6 @@ var Component = View.extend(TargetActionSupport, ComponentTemplateDeprecation, { init: function() { this._super(); - set(this, 'origContext', get(this, 'context')); set(this, 'context', this); set(this, 'controller', this); }, @@ -160,12 +159,8 @@ var Component = View.extend(TargetActionSupport, ComponentTemplateDeprecation, { */ templateName: null, - // during render, isolate keywords - cloneKeywords: function() { - return { - view: this, - controller: this - }; + _setupKeywords: function() { + this._keywords.view.setSource(this); }, _yield: function(context, options) { @@ -181,9 +176,9 @@ var Component = View.extend(TargetActionSupport, ComponentTemplateDeprecation, { tagName: '', _contextView: parentView, template: template, - context: options.data.insideGroup ? get(this, 'origContext') : get(parentView, 'context'), + context: get(parentView, 'context'), controller: get(parentView, 'controller'), - templateData: { keywords: parentView.cloneKeywords(), insideGroup: options.data.insideGroup } + templateData: { keywords: {} } }); } },
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-views/lib/views/container_view.js
@@ -385,7 +385,9 @@ merge(states.inBuffer, { merge(states.hasElement, { childViewsWillChange: function(view, views, start, removed) { for (var i=start; i<start+removed; i++) { - views[i].remove(); + var _view = views[i]; + _view._unsubscribeFromStreamBindings(); + _view.remove(); } },
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-views/lib/views/view.js
@@ -12,11 +12,14 @@ import { set } from "ember-metal/property_set"; import setProperties from "ember-metal/set_properties"; import run from "ember-metal/run_loop"; import { addObserver, removeObserver } from "ember-metal/observer"; - import { defineProperty } from "ember-metal/properties"; import { guidFor } from "ember-metal/utils"; import { computed } from "ember-metal/computed"; import { observer } from "ember-metal/mixin"; +import SimpleStream from "ember-metal/streams/simple"; +import KeyStream from "ember-views/streams/key_stream"; +import StreamBinding from "ember-metal/streams/stream_binding"; +import ContextStream from "ember-views/streams/context_stream"; import { typeOf, @@ -37,8 +40,6 @@ import { } from "ember-metal/enumerable_utils"; import { beforeObserver } from "ember-metal/mixin"; -import copy from "ember-runtime/copy"; -import { isGlobalPath } from "ember-metal/binding"; import { propertyWillChange, @@ -50,6 +51,7 @@ import "ember-views/system/ext"; // for the side effect of extending Ember.run. import CoreView from "ember-views/views/core_view"; + /** @module ember @submodule ember-views @@ -992,6 +994,7 @@ var View = CoreView.extend({ _parentViewDidChange: observer('_parentView', function() { if (this.isDestroying) { return; } + this._setupKeywords(); this.trigger('parentViewDidChange'); if (get(this, 'parentView.controller') && !get(this, 'controller')) { @@ -1009,14 +1012,22 @@ var View = CoreView.extend({ }); }), - cloneKeywords: function() { - var templateData = get(this, 'templateData'); + _setupKeywords: function() { + var keywords = this._keywords; + var contextView = this._contextView || this._parentView; + + if (contextView) { + var parentKeywords = contextView._keywords; - var keywords = templateData ? copy(templateData.keywords) : {}; - set(keywords, 'view', this.isVirtual ? keywords.view : this); - set(keywords, 'controller', get(this, 'controller')); + keywords.view.setSource(this.isVirtual ? parentKeywords.view : this); - return keywords; + for (var name in parentKeywords) { + if (keywords[name]) continue; + keywords[name] = parentKeywords[name]; + } + } else { + keywords.view.setSource(this.isVirtual ? null : this); + } }, /** @@ -1039,15 +1050,12 @@ var View = CoreView.extend({ 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') + isRenderData: true }; // Invoke the template with the provided template context, which @@ -1103,20 +1111,30 @@ var View = CoreView.extend({ // ('content.isUrgent') forEach(classBindings, function(binding) { - Ember.assert("classNameBindings must not have spaces in them. Multiple class name bindings can be provided as elements of an array, e.g. ['foo', ':bar']", binding.indexOf(' ') === -1); + var parsedPath; + + if (typeof binding === 'string') { + Ember.assert("classNameBindings must not have spaces in them. Multiple class name bindings can be provided as elements of an array, e.g. ['foo', ':bar']", binding.indexOf(' ') === -1); + parsedPath = View._parsePropertyPath(binding); + if (parsedPath.path === '') { + parsedPath.stream = new SimpleStream(true); + } else { + parsedPath.stream = this.getStream('_view.' + parsedPath.path); + } + } else { + parsedPath = 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 = View._parsePropertyPath(binding); // Set up an observer on the context. If the property changes, toggle the // class name. - var observer = function() { + var observer = this._wrapAsScheduled(function() { // Get the current value of the property - newClass = this._classStringForProperty(binding); + newClass = this._classStringForProperty(parsedPath); elem = this.$(); // If we had previously added a class to the element, remove it. @@ -1135,10 +1153,10 @@ var View = CoreView.extend({ } else { oldClass = null; } - }; + }); // Get the class name for the property at its current value - dasherizedClass = this._classStringForProperty(binding); + dasherizedClass = this._classStringForProperty(parsedPath); if (dasherizedClass) { // Ensure that it gets into the classNames array @@ -1151,7 +1169,7 @@ var View = CoreView.extend({ oldClass = dasherizedClass; } - this.registerObserver(this, parsedPath.path, observer); + parsedPath.stream.subscribe(observer, this); // Remove className so when the view is rerendered, // the className is added based on binding reevaluation this.one('willClearRender', function() { @@ -1249,16 +1267,8 @@ var View = CoreView.extend({ @param property @private */ - _classStringForProperty: function(property) { - var parsedPath = View._parsePropertyPath(property); - var path = parsedPath.path; - - var val = get(this, path); - if (val === undefined && isGlobalPath(path)) { - val = get(Ember.lookup, path); - } - - return View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName); + _classStringForProperty: function(parsedPath) { + return View._classStringForValue(parsedPath.path, parsedPath.stream.value(), parsedPath.className, parsedPath.falsyClassName); }, // .......................................................... @@ -1694,6 +1704,17 @@ var View = CoreView.extend({ // setup child views. be sure to clone the child views array first this._childViews = this._childViews.slice(); + this._baseContext = undefined; + this._contextStream = undefined; + this._streamBindings = undefined; + + if (!this._keywords) { + this._keywords = Object.create(null); + } + this._keywords.view = new SimpleStream(); + this._keywords._view = this; + this._keywords.controller = new KeyStream(this, 'controller'); + this._setupKeywords(); Ember.assert("Only arrays are allowed for 'classNameBindings'", typeOf(this.classNameBindings) === 'array'); this.classNameBindings = emberA(this.classNameBindings.slice()); @@ -1959,22 +1980,78 @@ var View = CoreView.extend({ return; } - var view = this; - var stateCheckedObserver = function() { - view.currentState.invokeObserver(this, observer); - }; - var scheduledObserver = function() { - run.scheduleOnce('render', this, stateCheckedObserver); - }; + var scheduledObserver = this._wrapAsScheduled(observer); addObserver(root, path, target, scheduledObserver); this.one('willClearRender', function() { removeObserver(root, path, target, scheduledObserver); }); - } + }, + + _wrapAsScheduled: function(fn) { + var view = this; + var stateCheckedFn = function() { + view.currentState.invokeObserver(this, fn); + }; + var scheduledFn = function() { + run.scheduleOnce('render', this, stateCheckedFn); + }; + return scheduledFn; + }, + + getStream: function(path) { + return this._getContextStream().get(path); + }, + + _getBindingForStream: function(path) { + if (this._streamBindings === undefined) { + this._streamBindings = Object.create(null); + this.one('willDestroyElement', this, this._destroyStreamBindings); + } + + if (this._streamBindings[path] !== undefined) { + return this._streamBindings[path]; + } else { + var stream = this._getContextStream().get(path); + return this._streamBindings[path] = new StreamBinding(stream); + } + }, + _destroyStreamBindings: function() { + var streamBindings = this._streamBindings; + for (var path in streamBindings) { + streamBindings[path].destroy(); + } + this._streamBindings = undefined; + }, + + _getContextStream: function() { + if (this._contextStream === undefined) { + this._baseContext = new KeyStream(this, 'context'); + this._contextStream = new ContextStream(this); + this.one('willDestroyElement', this, this._destroyContextStream); + } + + return this._contextStream; + }, + + _destroyContextStream: function() { + this._baseContext.destroy(); + this._baseContext = undefined; + this._contextStream.destroy(); + this._contextStream = undefined; + }, + + _unsubscribeFromStreamBindings: function() { + for (var key in this._streamBindingSubscriptions) { + var streamBinding = this[key + 'Binding']; + var callback = this._streamBindingSubscriptions[key]; + streamBinding.unsubscribe(callback); + } + } }); + deprecateProperty(View.prototype, 'state', '_state'); deprecateProperty(View.prototype, 'states', '_states'); @@ -2042,6 +2119,7 @@ View.reopenClass({ } return { + stream: undefined, path: propertyPath, classNames: classNames, className: (className === '') ? undefined : className,
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-views/tests/views/container_view_test.js
@@ -280,11 +280,9 @@ test("if a ContainerView starts with a currentView, it is rendered as a child vi controller: controller }); var context = null; - var templateData = null; var mainView = View.create({ template: function(ctx, opts) { context = ctx; - templateData = opts.data; return "This is the main view."; } }); @@ -300,17 +298,15 @@ test("if a ContainerView starts with a currentView, it is rendered as a child vi equal(container.objectAt(0), mainView, "should have the currentView as the only child view"); equal(mainView.get('parentView'), container, "parentView is setup"); equal(context, container.get('context'), 'context preserved'); - equal(templateData.keywords.controller, controller, 'templateData is setup'); - equal(templateData.keywords.view, mainView, 'templateData is setup'); + equal(mainView._keywords.controller.value(), controller, 'controller keyword is setup'); + equal(mainView._keywords.view.value(), mainView, 'view keyword is setup'); }); test("if a ContainerView is created with a currentView, it is rendered as a child view", function() { var context = null; - var templateData = null; var mainView = View.create({ template: function(ctx, opts) { context = ctx; - templateData = opts.data; return "This is the main view."; } }); @@ -331,17 +327,15 @@ test("if a ContainerView is created with a currentView, it is rendered as a chil equal(container.objectAt(0), mainView, "should have the currentView as the only child view"); equal(mainView.get('parentView'), container, "parentView is setup"); equal(context, container.get('context'), 'context preserved'); - equal(templateData.keywords.controller, controller, 'templateData is setup'); - equal(templateData.keywords.view, mainView, 'templateData is setup'); + equal(mainView._keywords.controller.value(), controller, 'controller keyword is setup'); + equal(mainView._keywords.view.value(), mainView, 'view keyword is setup'); }); test("if a ContainerView starts with no currentView and then one is set, the ContainerView is updated", function() { var context = null; - var templateData = null; var mainView = View.create({ template: function(ctx, opts) { context = ctx; - templateData = opts.data; return "This is the main view."; } }); @@ -368,17 +362,15 @@ test("if a ContainerView starts with no currentView and then one is set, the Con equal(container.objectAt(0), mainView, "should have the currentView as the only child view"); equal(mainView.get('parentView'), container, "parentView is setup"); equal(context, container.get('context'), 'context preserved'); - equal(templateData.keywords.controller, controller, 'templateData is setup'); - equal(templateData.keywords.view, mainView, 'templateData is setup'); + equal(mainView._keywords.controller.value(), controller, 'controller keyword is setup'); + equal(mainView._keywords.view.value(), mainView, 'view keyword is setup'); }); test("if a ContainerView starts with a currentView and then is set to null, the ContainerView is updated", function() { var context = null; - var templateData = null; var mainView = View.create({ template: function(ctx, opts) { context = ctx; - templateData = opts.data; return "This is the main view."; } }); @@ -400,8 +392,8 @@ test("if a ContainerView starts with a currentView and then is set to null, the equal(container.objectAt(0), mainView, "should have the currentView as the only child view"); equal(mainView.get('parentView'), container, "parentView is setup"); equal(context, container.get('context'), 'context preserved'); - equal(templateData.keywords.controller, controller, 'templateData is setup'); - equal(templateData.keywords.view, mainView, 'templateData is setup'); + equal(mainView._keywords.controller.value(), controller, 'controller keyword is setup'); + equal(mainView._keywords.view.value(), mainView, 'view keyword is setup'); run(function() { set(container, 'currentView', null); @@ -413,11 +405,9 @@ test("if a ContainerView starts with a currentView and then is set to null, the test("if a ContainerView starts with a currentView and then is set to null, the ContainerView is updated and the previous currentView is destroyed", function() { var context = null; - var templateData = null; var mainView = View.create({ template: function(ctx, opts) { context = ctx; - templateData = opts.data; return "This is the main view."; } }); @@ -439,8 +429,8 @@ test("if a ContainerView starts with a currentView and then is set to null, the equal(container.objectAt(0), mainView, "should have the currentView as the only child view"); equal(mainView.get('parentView'), container, "parentView is setup"); equal(context, container.get('context'), 'context preserved'); - equal(templateData.keywords.controller, controller, 'templateData is setup'); - equal(templateData.keywords.view, mainView, 'templateData is setup'); + equal(mainView._keywords.controller.value(), controller, 'controller keyword is setup'); + equal(mainView._keywords.view.value(), mainView, 'view keyword is setup'); run(function() { set(container, 'currentView', null);
true
Other
emberjs
ember.js
f839dcd89ad5ecc50d5403a06f507449380557b0.json
Streamify template bindings
packages/ember-views/tests/views/view/template_test.js
@@ -142,7 +142,7 @@ test("should provide a controller to the template if a controller is specified o controller: controller1, template: function(buffer, options) { - optionsDataKeywordsControllerForView = options.data.keywords.controller; + optionsDataKeywordsControllerForView = options.data.view._keywords.controller.value(); } }); @@ -165,10 +165,10 @@ test("should provide a controller to the template if a controller is specified o templateData: options.data, template: function(context, options) { contextForView = context; - optionsDataKeywordsControllerForChildView = options.data.keywords.controller; + optionsDataKeywordsControllerForChildView = options.data.view._keywords.controller.value(); } })); - optionsDataKeywordsControllerForView = options.data.keywords.controller; + optionsDataKeywordsControllerForView = options.data.view._keywords.controller.value(); } }); @@ -191,10 +191,10 @@ test("should provide a controller to the template if a controller is specified o templateData: options.data, template: function(context, options) { contextForControllerlessView = context; - optionsDataKeywordsControllerForChildView = options.data.keywords.controller; + optionsDataKeywordsControllerForChildView = options.data.view._keywords.controller.value(); } })); - optionsDataKeywordsControllerForView = options.data.keywords.controller; + optionsDataKeywordsControllerForView = options.data.view._keywords.controller.value(); } });
true
Other
emberjs
ember.js
ba1fcb82fe5cde4e40eac7a29f2623f9f38a4aaf.json
remove unused toDOM method
packages/ember-views/lib/system/render_buffer.js
@@ -64,10 +64,6 @@ ClassSet.prototype = { this.seen[string] = true; this.list.push(string); - }, - - toDOM: function() { - return this.list.join(" "); } };
false
Other
emberjs
ember.js
53ec667245c4a79d1e76e1d257b13ee716acb74b.json
update back burner Diff: https://github.com/ebryn/backburner.js/compare/919861fa9f3a5504c37f05607b1b02421af04167...baef3625dd4374e3803288652cd0aab68775cc62 * [Cleanup]unify deferredActionQueue.flush and queue.flush * [Perf] reduce cost of flushing and dramatically reduce cost of flushing empty queues.
bower.json
@@ -7,7 +7,7 @@ "qunit-phantom-runner": "jonkemp/qunit-phantomjs-runner#1.2.0" }, "devDependencies": { - "backburner": "https://github.com/ebryn/backburner.js.git#24ff580bef0f2d402474cc3d221da73ac82f09c9", + "backburner": "https://github.com/ebryn/backburner.js.git#baef3625dd4374e3803288652cd0aab68775cc62", "rsvp": "https://github.com/tildeio/rsvp.js.git#3.0.14", "router.js": "https://github.com/tildeio/router.js.git#f7b4b11543222c52d91df861544592a8c1dcea8a", "route-recognizer": "https://github.com/tildeio/route-recognizer.git#8e1058e29de741b8e05690c69da9ec402a167c69",
false
Other
emberjs
ember.js
906d5297c2ec22d6410e0b0f65d4eca47fecf098.json
Add a . to increase readability I added a . on line 33 to separate two sentences for increase readability.
README.md
@@ -30,7 +30,7 @@ See [CONTRIBUTING.md](https://github.com/emberjs/ember.js/blob/master/CONTRIBUTI 3. Then visit <http://localhost:4200/>. This will run all tests. -4. To test a specific package visit `http://localhost:4200/tests/index.html?package=PACKAGE_NAME` Replace +4. To test a specific package visit `http://localhost:4200/tests/index.html?package=PACKAGE_NAME`. Replace `PACKAGE_NAME` with the name of the package you want to test. For example:
false
Other
emberjs
ember.js
cc04f14e2be5c790c4036251793b4ceab2093a03.json
Fix regex to match Windows line endings Fixes #5662
lib/broccoli-ember-inline-template-precompiler.js
@@ -15,7 +15,7 @@ function EmberInlineTemplatePrecompiler (inputTree, options) { this.inlineTemplateRegExp = /precompileTemplate\(['"](.*)['"]\)/; // Used for replacing the original variable declaration to satisfy JSHint. // For example, removes `var precompileTemplate = Ember.Handlebars.compile;`. - this.precompileTemplateVarRegex = /var precompileTemplate =.*\n/g; + this.precompileTemplateVarRegex = /var precompileTemplate =.*\r?\n/g; } EmberInlineTemplatePrecompiler.prototype.extensions = ['js'];
false
Other
emberjs
ember.js
48ecdd707e226315bb4750ff0c91a6fcb56e2637.json
Remove documentation for {{template}} {{template}} was deprecated in favor or {[partial}} before 1.0 in ea5456ac on 2013-07-19.
packages/ember-handlebars/lib/helpers/template.js
@@ -1,5 +1,4 @@ -import Ember from "ember-metal/core"; -// var emberDeprecate = Ember.deprecate; +import Ember from "ember-metal/core"; // Ember.deprecate; import EmberHandlebars from "ember-handlebars-compiler"; /** @@ -8,43 +7,6 @@ import EmberHandlebars from "ember-handlebars-compiler"; */ /** - `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 - <script type="text/x-handlebars" data-template-name="logged_in_user"> - {{#with loggedInUser}} - Last Login: {{lastLogin}} - User Info: {{template "user_info"}} - {{/with}} - </script> - ``` - - ```html - <script type="text/x-handlebars" data-template-name="user_info"> - Name: <em>{{name}}</em> - Karma: <em>{{karma}}</em> - </script> - ``` - - ```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 `<script>` tags to your page with the `data-template-name` attribute set, - they will be compiled and placed in this hash automatically. - - You can also manually register templates by adding them to the hash: - - ```javascript - Ember.TEMPLATES["my_cool_template"] = Ember.Handlebars.compile('<b>{{user}}</b>'); - ``` - @deprecated @method template @for Ember.Handlebars.helpers
false
Other
emberjs
ember.js
b7e6adb90c134593d33268b7c3a1bd15e7d627b4.json
Remove duplicate _MetamorphView
packages/ember-handlebars/lib/helpers/each.js
@@ -27,10 +27,8 @@ import { removeBeforeObserver } from "ember-metal/observer"; -import { - _Metamorph, - _MetamorphView -} from "ember-handlebars/views/metamorph_view"; +import _MetamorphView from "ember-handlebars/views/metamorph_view"; +import { _Metamorph } from "ember-handlebars/views/metamorph_view"; var EachView = CollectionView.extend(_Metamorph, {
true
Other
emberjs
ember.js
b7e6adb90c134593d33268b7c3a1bd15e7d627b4.json
Remove duplicate _MetamorphView
packages/ember-handlebars/lib/main.js
@@ -79,9 +79,9 @@ import { _HandlebarsBoundView, SimpleHandlebarsView } from "ember-handlebars/views/handlebars_bound_view"; +import _MetamorphView from "ember-handlebars/views/metamorph_view"; import { _SimpleMetamorphView, - _MetamorphView, _Metamorph } from "ember-handlebars/views/metamorph_view";
true
Other
emberjs
ember.js
b7e6adb90c134593d33268b7c3a1bd15e7d627b4.json
Remove duplicate _MetamorphView
packages/ember-handlebars/lib/views/metamorph_view.js
@@ -37,7 +37,7 @@ export var _Metamorph = Mixin.create({ @uses Ember._Metamorph @private */ -export var _MetamorphView = View.extend(_Metamorph); +export default View.extend(_Metamorph); /** @class _SimpleMetamorphView @@ -47,4 +47,3 @@ export var _MetamorphView = View.extend(_Metamorph); @private */ export var _SimpleMetamorphView = CoreView.extend(_Metamorph); -export default View.extend(_Metamorph);
true
Other
emberjs
ember.js
b7e6adb90c134593d33268b7c3a1bd15e7d627b4.json
Remove duplicate _MetamorphView
packages/ember-routing-handlebars/tests/helpers/outlet_test.js
@@ -17,7 +17,7 @@ import EmberRouter from "ember-routing/system/router"; import HashLocation from "ember-routing/location/hash_location"; import EmberHandlebars from "ember-handlebars"; -import {_MetamorphView} from "ember-handlebars/views/metamorph_view"; +import _MetamorphView from "ember-handlebars/views/metamorph_view"; import EmberView from "ember-routing/ext/view"; import EmberContainerView from "ember-views/views/container_view"; import jQuery from "ember-views/system/jquery";
true
Other
emberjs
ember.js
f4ea6733ee3e0d8bbc9e481a660693381f0f7f34.json
Update changelog for 1.8.0-beta.2 and 1.8.0-beta.3.
CHANGELOG.md
@@ -1,5 +1,40 @@ # Ember Changelog +### Ember 1.8.0-beta.3 (September, 27, 2014) + +* [BUGFIX] Use contextualElements to properly handle omitted optional start tags. +* [BUGFIX] Ensure that `Route.prototype.activate` is not retriggered when the model for the current route changes. +* [PERF] Fix optimization bailouts for `{{view}}` helper. +* [BUGFIX] Add `attributeBindings` for `lang` and `dir` (for bidirectional language support) in `Ember.TextField` and `Ember.TextAra`. +* [BUGFIX] Fix finishChains for all chains that reference an obj not just the ones rooted at that object. +* [BUGFIX] Refactor ES3 `Ember.keys` implementation. +* Rewrite Ember.Map to be faster and closer to ES6 implementation: + * [PERF + ES6] No longer clone array before enumeration (dramatically reduce allocations) + * [PERF] Don’t Rebind the callback of forEach if not needed + * [PERF + ES6] No longer allow Map#length to be bindable + * [PERF] Don’t double guid keys, as they are passed from map to ordered set (add/remove) + * [ES6] Deprecate Map#remove in-favor of the es6 Map#delete + * [ES6] Error if callback is not a function + * [ES6] Map#set should return the map. This enables chaining map.`map.set(‘foo’,1).set(‘bar’,3);` etc. + * [ES6] Remove length in-favor of size. + * [ES6] Throw if constructor is invoked without new + * [ES6] Make inheritance work correctly + + +### Ember 1.8.0-beta.2 (September, 20, 2014) + +* [BUGFIX] Allow for bound property {{input}} type. +* [BUGFIX] Ensure pushUnique targetQueue is cleared by flush. +* [BUGFIX] instrument should still call block even without subscribers. +* [BUGFIX] Remove uneeded normalization in query param controller lookup. +* [BUGFIX] Do not use defineProperty on each View instance. +* [PERF] Speedup `watchKey` by preventing for in related deopt. +* [PERF] Change `ENV.MANDATORY_SETTER` to FEATURES so it can be compiled out of production builds. +* [PERF] Object.create(null) in Ember.inspect. +* [PERF] Extracts computed property set into a separate function. +* [BUGFIX] Make `GUID_KEY = intern(GUID_KEY)` actually work on ES3. +* [BUGFIX] Ensure nested routes can inherit model from parent. + ### Ember 1.8.0-beta.1 (August 20, 2014) * Remove `metamorph` in favor of `morph` package (removes the need for `<script>` tags in the DOM).
false
Other
emberjs
ember.js
99a7c9dd7dbeff4f11b4125c73f7d677d410db7f.json
Remove repeated "esnext" jshint rule
.jshintrc
@@ -41,7 +41,6 @@ "debug": false, "devel": false, "eqeqeq": true, - "esnext": true, "evil": true, "forin": false, "immed": false,
false
Other
emberjs
ember.js
def2d723be222addbc2b35942f07c10a89c7d7c6.json
prefer new Map() syntax
packages/ember-metal/lib/binding.js
@@ -2,7 +2,7 @@ import Ember from "ember-metal/core"; // Ember.Logger, Ember.LOG_BINDINGS, asser import { get } from "ember-metal/property_get"; import { trySet } from "ember-metal/property_set"; import { guidFor } from "ember-metal/utils"; -import { Map } from "ember-metal/map"; +import Map from "ember-metal/map"; import { addObserver, removeObserver, @@ -58,7 +58,7 @@ function Binding(toPath, fromPath) { this._direction = 'fwd'; this._from = fromPath; this._to = toPath; - this._directionMap = Map.create(); + this._directionMap = new Map(); this._readyToSync = undefined; this._oneWay = undefined; }
true
Other
emberjs
ember.js
def2d723be222addbc2b35942f07c10a89c7d7c6.json
prefer new Map() syntax
packages/ember-metal/lib/map.js
@@ -474,6 +474,7 @@ MapWithDefault.prototype.copy = function() { })); }; +export default Map; export { OrderedSet, Map,
true
Other
emberjs
ember.js
00c650cc5443679ff33491be1db183c68b85429d.json
Use separate FEATURES for dev vs prod builds.
Brocfile.js
@@ -204,7 +204,22 @@ var testConfig = pickFiles('tests', { testConfig = replace(testConfig, { files: [ 'tests/ember_configuration.js' ], patterns: [ - { match: /\{\{FEATURES\}\}/g, replacement: JSON.stringify(defeatureifyConfig().enabled) } + { match: /\{\{DEV_FEATURES\}\}/g, + replacement: function() { + var features = defeatureifyConfig().enabled; + + return JSON.stringify(features); + } + }, + { match: /\{\{PROD_FEATURES\}\}/g, + replacement: function() { + var features = defeatureifyConfig({ + environment: 'production' + }).enabled; + + return JSON.stringify(features); + } + }, ] });
true
Other
emberjs
ember.js
00c650cc5443679ff33491be1db183c68b85429d.json
Use separate FEATURES for dev vs prod builds.
tests/ember_configuration.js
@@ -5,7 +5,6 @@ testing: true }; window.ENV = window.ENV || {}; - ENV.FEATURES = {{FEATURES}}; // Test for "hooks in ENV.EMBER_LOAD_HOOKS['hookName'] get executed" ENV.EMBER_LOAD_HOOKS = ENV.EMBER_LOAD_HOOKS || {}; @@ -15,6 +14,8 @@ ENV.__test_hook_count__ += object; }); + window.ENV.FEATURES = !!QUnit.urlParams.prod ? {{PROD_FEATURES}} : {{DEV_FEATURES}}; + // Handle extending prototypes ENV['EXTEND_PROTOTYPES'] = !!QUnit.urlParams.extendprototypes;
true
Other
emberjs
ember.js
b3f0f6ce68833ffc53a72ebc6249908b6fff199d.json
Fix argument order for handleMandatorySetter.
packages/ember-metal/lib/watch_key.js
@@ -38,7 +38,7 @@ export function watchKey(obj, keyName, meta) { if (Ember.FEATURES.isEnabled('mandatory-setter')) { - var handleMandatorySetter = function handleMandatorySetter(m, keyName, obj) { + var handleMandatorySetter = function handleMandatorySetter(m, obj, keyName) { // this x in Y deopts, so keeping it in this function is better; if (keyName in obj) { m.values[keyName] = obj[keyName];
false
Other
emberjs
ember.js
ca6d60018bd342387c96f0a96af57771e98eae93.json
Allow development only feature flags. When a flag with `development-only` is found in `features.json` it will be enabled (flags stripped) for `ember.js`, and disabled (flags stripped) for `ember.prod.js`.
Brocfile.js
@@ -20,7 +20,13 @@ var calculateVersion = require('./lib/calculate-version'); var env = process.env.EMBER_ENV || 'development'; var disableJSHint = !!process.env.NO_JSHINT || false; -var disableDefeatureify = !!process.env.NO_DEFEATUREIFY || env === 'development' || false; +var disableDefeatureify; + +if (process.env.DEFEATUREIFY === 'true') { + disableDefeatureify = false; +} else { + disableDefeatureify = env === 'development'; +} var generateTemplateCompiler = require('./lib/broccoli-ember-template-compiler-generator'); var inlineTemplatePrecompiler = require('./lib/broccoli-ember-inline-template-precompiler'); @@ -43,12 +49,19 @@ function defeatureifyConfig(options) { var stripDebug = false; var options = options || {}; var configJson = JSON.parse(fs.readFileSync("features.json").toString()); + var features = options.features || configJson.features; if (configJson.hasOwnProperty('stripDebug')) { stripDebug = configJson.stripDebug; } if (options.hasOwnProperty('stripDebug')) { stripDebug = options.stripDebug; } + for (var flag in features) { + if (features[flag] === 'development-only') { + features[flag] = options.environment !== 'production'; + } + } + return { - enabled: options.features || configJson.features, + enabled: features, debugStatements: options.debugStatements || configJson.debugStatements, namespace: options.namespace || configJson.namespace, enableStripDebug: stripDebug @@ -605,7 +618,10 @@ prodCompiledSource = concatES6(prodCompiledSource, { vendorTrees: vendorTrees, inputFiles: ['**/*.js'], destFile: '/ember.prod.js', - defeatureifyOptions: {stripDebug: true} + defeatureifyOptions: { + stripDebug: true, + environment: 'production' + } }); // Take prod output and minify. This reduces filesize (as you'd expect)
true
Other
emberjs
ember.js
ca6d60018bd342387c96f0a96af57771e98eae93.json
Allow development only feature flags. When a flag with `development-only` is found in `features.json` it will be enabled (flags stripped) for `ember.js`, and disabled (flags stripped) for `ember.prod.js`.
features.json
@@ -11,7 +11,8 @@ "property-brace-expansion-improvement": true, "ember-routing-handlebars-action-with-key-code": null, "ember-runtime-item-controller-inline-class": null, - "ember-metal-injected-properties": null + "ember-metal-injected-properties": null, + "mandatory-setter": "development-only" }, "debugStatements": [ "Ember.warn",
true
Other
emberjs
ember.js
a72152f90f84e3793e05ca04d84f35e3782d0eb6.json
fix failing test on IE11. turns out the internal escaping stragety can differ between browsers. We should defer to the browsers defaults
Brocfile.js
@@ -89,7 +89,7 @@ function vendoredPackage(packageName) { destFile: '/' + packageName + '.js' }); - if (env !== 'development') { + if (true) { sourceTree = es3recast(sourceTree); } @@ -599,7 +599,7 @@ var prodCompiledSource = removeFile(sourceTrees, { // Generates prod build. defeatureify increases the overall runtime speed of ember.js by // ~10%. See defeatureify. prodCompiledSource = concatES6(prodCompiledSource, { - es3Safe: env !== 'development', + es3Safe: true, // env !== 'development', includeLoader: true, bootstrapModule: 'ember', vendorTrees: vendorTrees, @@ -620,7 +620,7 @@ minCompiledSource = uglifyJavaScript(minCompiledSource, { // Take testsTrees and compile them for consumption in the browser test suite. var compiledTests = concatES6(testTrees, { - es3Safe: env !== 'development', + es3Safe: true, //env !== 'development', includeLoader: true, inputFiles: ['**/*.js'], destFile: '/ember-tests.js'
true
Other
emberjs
ember.js
a72152f90f84e3793e05ca04d84f35e3782d0eb6.json
fix failing test on IE11. turns out the internal escaping stragety can differ between browsers. We should defer to the browsers defaults
packages/ember-views/tests/system/render_buffer_test.js
@@ -70,7 +70,16 @@ test("prevents XSS injection via `style`", function() { buffer.generateElement(); var el = buffer.element(); - equal(el.getAttribute('style'), 'color:blue;" xss="true" style="color:red;'); + var div = document.createElement('div'); + + // some browsers have different escaping strageties + // we should ensure the outcome is consistent. Ultimately we now use + // setAttribute under the hood, so we should always do the right thing. But + // this test should be kept to ensure we do. Also, I believe/hope it is + // alright to assume the browser escapes setAttribute correctly... + div.setAttribute('style', 'color:blue;" xss="true" style="color:red;'); + + equal(el.getAttribute('style'), div.getAttribute('style')); }); test("prevents XSS injection via `tagName`", function() {
true
Other
emberjs
ember.js
9b3e1eca1f9b0e9e649adcfea15e50b8d895e29f.json
improve throughput of actionsFor by 30%-40% hasOwnProperty is unfortunately slow so we should guard it with checks that the property is even something like what we want first. Also go back to embers roots and maintain __source__ on listeners.
packages/ember-metal/lib/events.js
@@ -52,21 +52,26 @@ function indexOf(array, target, method) { function actionsFor(obj, eventName) { var meta = metaFor(obj, true); var actions; + var listeners = meta.listeners; - if (!meta.listeners) { meta.listeners = {}; } - - if (!meta.hasOwnProperty('listeners')) { + if (!listeners) { + listeners = meta.listeners = create(null); + listeners.__source__ = obj; + } else if (listeners.__source__ !== obj) { // setup inherited copy of the listeners object - meta.listeners = create(meta.listeners); + listeners = meta.listeners = create(listeners); + listeners.__source__ = obj; } - actions = meta.listeners[eventName]; + actions = listeners[eventName]; // if there are actions, but the eventName doesn't exist in our listeners, then copy them from the prototype - if (actions && !meta.listeners.hasOwnProperty(eventName)) { - actions = meta.listeners[eventName] = meta.listeners[eventName].slice(); + if (actions && actions.__source__ !== obj) { + actions = listeners[eventName] = listeners[eventName].slice(); + actions.__source__ = obj; } else if (!actions) { - actions = meta.listeners[eventName] = []; + actions = listeners[eventName] = []; + actions.__source__ = obj; } return actions; @@ -287,8 +292,11 @@ export function watchedEvents(obj) { var listeners = obj['__ember_meta__'].listeners, ret = []; if (listeners) { - for(var eventName in listeners) { - if (listeners[eventName]) { ret.push(eventName); } + for (var eventName in listeners) { + if (eventName !== '__source__' && + listeners[eventName]) { + ret.push(eventName); + } } } return ret;
false
Other
emberjs
ember.js
34a0d6a561d3e18e1aef8e856064dec33740120f.json
Use svg instead of png to get better image quality
README.md
@@ -1,4 +1,4 @@ -# Ember.js [![Build Status](https://secure.travis-ci.org/emberjs/ember.js.png?branch=master)](http://travis-ci.org/emberjs/ember.js) [![Code Climate](https://codeclimate.com/github/emberjs/ember.js.png)](https://codeclimate.com/github/emberjs/ember.js) +# Ember.js [![Build Status](https://secure.travis-ci.org/emberjs/ember.js.svg?branch=master)](http://travis-ci.org/emberjs/ember.js) [![Code Climate](https://codeclimate.com/github/emberjs/ember.js.svg)](https://codeclimate.com/github/emberjs/ember.js) Ember.js is a JavaScript framework that does all of the heavy lifting that you'd normally have to do by hand. There are tasks that are common
false
Other
emberjs
ember.js
bfd75e4f464e702608ed2bc3842a6b4d5b41eefa.json
remove unused vars and enforce in jshint
.jshintrc
@@ -59,5 +59,6 @@ "strict": false, "white": false, "eqnull": true, - "trailing": true + "trailing": true, + "unused": "vars" }
true