Looking at the Ember.js documentation, it is rather vague about when to make use of Ember.run() (my emphasis).
Normally you should not need to invoke this method yourself. However if you are implementing raw event handlers when interfacing with other libraries or plugins, you should probably wrap all of your code inside this call.
From looking through the source and reading posts on this topic, my understanding is that when you call Ember.run(), the following occurs.
The given callback is immediately run.
The run loop algorithm is executed, flushing all queues and thus ensuring bindings are synchronized, etc.
I'm trying to understand why it would be recommended to handle other libraries' events inside of a call to Ember.run(). Take the following example where I create a jQuery UI slider and handle the slide event.
<script type="text/x-handlebars" data-template-name="index">
<div id="slider"></div>
<h2>{{value}}</h2>
<h3>{{valueProse}}</h3>
</script>
App = Ember.Application.create();
App.IndexController = Ember.Controller.extend({
actions: {
valueChange: function (newValue) {
this.set('value', newValue);
}
},
valueProse: function () {
var value = this.get('value');
if (Ember.isNone(value)) {
return '';
}
if (value <= 25) {
return 'pretty small';
}
if (value <= 50) {
return 'getting bigger';
}
if (value <= 75) {
return 'whoa watch out';
}
if (value < 100) {
return 'can\'t handle it!';
}
return 'ahhhgghuarghblarp!';
}.property('value')
});
App.IndexView = Ember.View.extend({
didInsertElement: function () {
var controller = this.get('controller')
this.$('#slider').slider({
min: 0,
max: 100,
slide: function (event, ui) {
// Ember.run(function () {
controller.send('valueChange', ui.value);
// });
}
});
}
});
Here is a working fiddle: http://jsfiddle.net/ahaurw01/Kwze5/2/
Whether or not the slide event is handled inside of a call to Ember.run(), the expected behavior occurs. I'd like to understand what optimizations or insurance this offers. Either way, I see that value is getting set and valueProse is updated appropriately. Is this one of the cases the documentation is talking about when suggesting my code be wrapped in Ember.run()?
I believe the idea of running Ember.run is so that anything async events, such as event listeners from 3rd party libraries, can be synced up with the ember run loop.
I learned a ton about Ember.run and why it's useful when I started integrating QUnit into my project, because when you start testing your app, the automatic ember.run loop feature code is taken out and it's all up to you.
Related
I am loading a large model (2500 entries) in Ember Data from an API.
It also takes 3 HTTP Requests since the server will only return 1000 results at a time.
My whole web browser freezes for a moment while it is loading, which begs the question:
What is the best way to load large models without blocking the UI?
I tried beginPropertyChanges, endPropertyChanges:
Ember.RSVP.resolve(store.beginPropertyChanges())
.then(getAllTeams) // this loads the model
.then(function() { return Ember.RSVP.resolve(store.endPropertyChanges()); });
var getAllTeams = function(teams, skip) {
if (!teams) {
return store.find('team', {limit:1000, skip: 0}).then(function(foundTeams) {
var teams = foundTeams;
return getAllTeams(foundTeams,teams.get('length'));
});
}
else if (teams.get('length') < 1000) {
return store.find('team');
}
else {
return store.find('team', {limit: 1000, skip:skip}).then(function(foundTeams) {
return getAllTeams(foundTeams,skip+teams.get('length'));
});
}
}
Doing beginPropertyChanges on the store is not going to accomplish anything useful at all.
The default behavior of Ember is that yes, it will block on large downloads. Here is a possible approach.
// route
export default Ember.Route.extend({
model: function() {
var all = return this.store.all('team');
function get_more(n) {
return store.find('team', {limit:1000, skip: n}) .
then(function(teams) {
if (teams.length === 1000) return get_more(n+1000);
})
}(0));
return all;
});
We return a live collection of teams in the store, which initially might be zero. Asynchronously to that, we start a loop which gets items 1000 at a time. As the new items come in, the live collection will be updated and the relevant UI will as well.
Untested.
Ember provides a mechanism for handling long route render times. I believe what you are looking for is Loading / Error Substates.
Check out official EmberJS guide pages.
Happy coding :)
Here's a simple component:
App.FooBarComponent = Ember.Component.extend({
tagName: "button",
status: "Ready",
revertStatusPeriodMs: 2000,
click: function() {
this.set('status', 'Pending');
// A fake ajax
this.run()
.then( function() {
this.updateStatus('Finished');
}.bind(this))
.catch( function() {
this.updateStatus('Error');
}.bind(this));
},
run: function() {
return new Ember.RSVP.Promise( function(resolve) {
Ember.run.later( function() {
resolve();
}, 500);
});
},
updateStatus: function(statusText) {
this.set('status', statusText);
var periodMs = this.get('revertStatusPeriodMs') || 1000;
Ember.run.later( function() {
this.set('status', 'Ready');
}.bind(this), periodMs);
}
});
It does a simple thing: when clicked, it displays some text. Later replaces the text with another one. Even later, it reverts the text to the initial one.
The code works fine. My problem is that i'm unable to write a test for it.
test('clicking the button should set the label', function(assert) {
expect(4);
visit('/');
assert.equal( find('button').text().trim(), 'Ready', 'Should initially be "Ready"');
andThen(function() {
click('button');
assert.equal( find('button').text().trim(), 'Pending', 'Should "Pending" right after click');
});
// This one fires too late!
andThen(function() {
assert.equal( find('button').text().trim(), 'Finished', 'Should become "Finished" after promise fulfills');
});
andThen(function() {
assert.equal( find('button').text().trim(), 'Ready', 'Should eventually return to the "Ready" state');
});
});
I have two problems:
I'm unable to test the Finished state. It seems that andThen waits for all promises and run.laters to finish, while i want to test an intermediate state. How do i run an assertion between two sequential promises/run.laters?
Times can be long, and tests can take forever to complete. I generally don't mind refactoring the code for better testability, but i refuse to adjust times in the app based on the environment (e. g. 2000 for dev/prod, 0 for test). Instead, i would like to use a timer mock or some other solution.
I've tried Sinon and failed: when i mock the timer, andThen never returns. Neither of these solutions helped me.
JSBin: http://emberjs.jsbin.com/fohava/2/edit?html,js,output (Sinon is included)
None of your test code seems to use asynch – which would seem to be crucial since without anything to distinguish them, the last 2 tests will execute in the same tick (tests 3 & 4 can't both be true at the same time). I'm not familiar with QUnit, but I did find it's async method, which would seem to be pertinent. However when I tried calling assert.async, it blew up. I tried updating QUnit 1.17, still no dice.
So I don't have a solution for you. The problem, though, is that Ember will only execute both andThen tests once all the asynchronous execution has finished – this means that test 3 will never be true.
I did some code where I basically got it working but it seems really finicky and not something you would want to be do be doing..
I did this a few days ago but never replied because I wasn't happy with it - it doesn't give you enough control..
The reason I'm replying now however is because I've found a PR that may be of use to you: PR 10463
I didn't look into too much detail but apparently it "allows custom async test helpers to pause execution by returning a promise"
I'm not sure what version of Ember you're using - but if you can hold out for this PR it may help you..
I have written this simple demo component to demonstrate a problem. The component code is below
App.FocusOutComponent = Em.Component.extend({
attributeBindings: ['tabindex'],
tagName: 'focus-out',
setFocus: function() {
console.log('clicked focus-out container');
this.$().find('button').focus();
console.log('focus set to button');
}.on('click'),
focussedOut: function() {
console.log('focussedOut from outer container');
}.on('focusOut'),
});
{{#focus-out id="focus-container" tabindex="-1"}}
<button id="text-button">Test Button</button>
{{/focus-out}}
When I run this and click on the focus-out element, this is the order of the logs. Link to demo
clicked focus-out container
focussedOut from outer container
focus set to button
Now when I am trying to write acceptance tests for this with the following code.
test('test visit / and click button', function() {
expect(0);
visit('/').then(function() {
find('focus-out').click();
console.log('after click in test');
});
});
The order of the logs are different. Link to demo.
clicked focus-out container
focus set to button
after click in test
focussedOut from outer container
The focusOut log got printed at the very end instead before the after click log. I was expecting the same order for the logs with just an additional log(after click) in the end.
Im not sure if this is a bug or something wrong with my code.
I also noticed another problem while executing tests. If I have focus on the chrome dev-tools while the tests are running, the focusOut event will not trigger at all.
Some help with this is much appreciated.
the click event doesn't set focus (being a back door route). You'll need to manually set focus then click if you want the same results.
Ember's Click Helper (sends mousedown/mouseup, then click)
function click(app, selector, context) {
var $el = app.testHelpers.findWithAssert(selector, context);
run($el, 'mousedown');
if ($el.is(':input')) {
var type = $el.prop('type');
if (type !== 'checkbox' && type !== 'radio' && type !== 'hidden') {
run($el, function(){
// Firefox does not trigger the `focusin` event if the window
// does not have focus. If the document doesn't have focus just
// use trigger('focusin') instead.
if (!document.hasFocus || document.hasFocus()) {
this.focus();
} else {
this.trigger('focusin');
}
});
}
}
run($el, 'mouseup');
run($el, 'click');
return app.testHelpers.wait();
}
Modified Test
test('test visit / and click button', function() {
expect(0);
visit('/').then(function() {
var el = find('focus-out');
el.focus();
click(el);
console.log('after click in test');
});
});
http://emberjs.jsbin.com/lefazevozi/1/edit?js,console,output
It's also important to note, that tearing down will also call the focus out event. So the main reason you were seeing the focusout at all was because on teardown it was losing focus from the button child.
Maybe focus should be set before mousedown on the click helper in the ember test, though I'm not sure what else that might affect, or if people wouldn't generally be expecting that since jquery doesn't do that.
I have a component which is inserted into the DOM as a '' tag (e.g., default behaviour). The component's job is to wrap a 3rd party jQuery tool and I'm trying to ensure it is responsive to "resize" events so I would like to explicitly set width and height style attributes.
In the component, it is easy enough to being to the style attribute:
attributeBindings: ['style'],
style: function() {
return "width: auto";
}.property('widthCalc'),
In this case, this works but doesn't do anything useful because style just returns a static string (width: auto).
Instead what I want to do is -- based on any change to the computed property widthCalc -- set the width based on the new value. So here's the next logical step:
style: function() {
var width = $('body')[0].offsetWidth;
return 'width: ' + width + 'px';
}.property('widthCalc'),
This too works, dynamically setting the DIV to the width of the body's width (note: this isn't really what I want but it does prove that this simple binding works). Now what I really want is to get the value of width from a computed property on the component but I don't even have to go that far to run into trouble; notice that instead of a global jQuery selector I switch to a localised component-scoped selector:
style: function() {
var width = this.$().offsetWidth;
return 'width: ' + width + 'px';
}.property('widthCalc'),
Unfortunately this causes the page NOT to load and gives the following error:
Uncaught Error: Something you did caused a view to re-render after it rendered but before it was inserted into the DOM.
I imagine this is Ember run-loop juju but I'm not sure how to proceed. Any help would be appreciated.
Since it is not possible to call this.$() in the component before it has been added to the dom, provide an initial value until the component is ready.
For example,
Setting a default value to the property style and on didInsertElement event reopen the class and define style as a calculated property using this.$()
http://emberjs.jsbin.com/delexoqize/1/edit?html,js,output
js
App.MyCompComponent = Em.Component.extend({
attributeBindings:["style"],
style:"visibility:hidden",
prop1:null,
initializeThisStyle:function(){
this.set("style","visibility:visible");
this.reopen({
style:function(){
// var thisOffsetWidth = this.$().get(0).offsetWidth;
return "visibility:visible;color:red;background-color:lightgrey;width:"+this.get("prop1")+"px";
}.property("prop1")
});
}.on("didInsertElement")
});
Alternatively handle the error raised by this.$() and provide a default value. Afterwards when the component will be added the property will be calculated as planned.
http://emberjs.jsbin.com/hilalapoce/1/edit?html,js,output
js
App.MyCompComponent = Em.Component.extend({
attributeBindings:["style"],
style:function(){
try{
this.$();//this will throw an erro initialy
return "visibility:visible;color:red;background-color:lightgrey;width:"+this.get("prop1")+"px";
}catch(e){
return "color:blue";
}
}.property("prop1"),
prop1:null
});
With the component I was trying to solve for I ended coming up with an solution that seems effective to me which I will share below. For an understanding of the why I was getting the error and how one might more directly address that error please see the comment from #melc above.
My Solution
What I'm solving for is resizing a jQuery component wrapped in an Ember component. In many cases, resizing is handled gracefully by CSS alone but some jQuery components -- including the very nice knob component from aterrien -- has JS which gets directly involved and therefore needs the containers width and height properties to be set explicitly by the Ember component so that it reacts appropriately.
When solving for this I realised my use-case had two problems:
Solving for a page resize event
Adjusting to the fact that my knob component was -- at times -- in the DOM but in a part of the DOM which was not visible (more explicitly it was in Bootstrap tab which wasn't visible).
The Resize Listener
The first part of the solution is to listen for a page-level resize of the page. I do this with the following:
resizeListener: function() {
var self = this;
self.$(window).on('resize', Ember.run.bind(self, self.resizeDidHappen));
}.on('didInsertElement'),
Page Resize Handler
When a resize is done at the "page" level I now want my component to inspect what the resize impact has been on the component:
resizeDidHappen: function() {
Ember.run.debounce(this, function() {
// get dimensions
var newWidth = Number(this.$().parent().get(0).offsetWidth);
var newHeight = Number(this.$().parent().get(0).offsetHeight);
// set instance variables
this.set('width', newWidth);
this.set('height', newWidth);
// reconfigure knob
this.$('.knob').trigger(
'configure',
{
width: newWidth,
height: newWidth
}
);
}, 300);
}
This solves the page resize problem if it exists in isolation but to make the component it is probably a good idea to solve for the visibility use case as well (certainly in my case it was critical).
Visibility Handler
Why? Well, for two reasons that I can think of:
Many jQuery components refuse to load or perform badly if they aren't loaded
The ember component appears to not be able to establish a "resize" event when it is not visible in the DOM
The one problem is that there is no DOM-level event for visibility changes, so how do we react to a change in visibility without polling on an interval? Well in most cases there will be a UI element which is controlling the state of visibility. In my case it's Bootstrap's tab bar and in this case they have events that fire on the tabs when they become visible. Great. Here's a selector for Bootstrap's selector (assuming you're inside the content area of the newly visible tab):
visibilityEventEmitter: function(context) {
// since there is no specific DOM event for a change in visibility we must rely on
// whatever component is creating this change to notify us via a bespoke event
// this function is setup for a Bootstrap tab pane; for other event emmitters you will have to build your own
try {
var thisTabPane = context.$().closest('.tab-pane').attr('id');
var $emitter = context.$().closest('.tab-content').siblings('[role=tabpanel]').find('li a[aria-controls=' + thisTabPane + ']');
return $emitter;
} catch(e) {
console.log('Problem getting event emitter: %o', e);
}
return false;
},
visibilityEventName: 'shown.bs.tab',
then we just need to add the following code:
_init: function() {
var isVisible = this.$().get(0).offsetWidth > 0;
if (isVisible) {
this.visibilityDidHappen();
}
}.on('didInsertElement'),
visibilityListener: function() {
// Listen for visibility event and signal a resize when it happens
// note: this listener is placed on a DOM element which is assumed
// to always be visibile so no need to wait on placing this listener
var self = this;
Ember.run.schedule('afterRender', function() {
var $selector = self.get('visibilityEventEmitter')(self);
$selector.on(self.get('visibilityEventName'), Ember.run.bind(self, self.visibilityDidHappen ));
});
}.on('didInsertElement'),
visibilityDidHappen: function() {
// On the first visibility event, the component must be initialised
if(!this.get('isInitialised')) {
this.initiateKnob();
} else {
// force a resize assessment as window sizing may have changed
// since last time component was visible
this.resizeDidHappen();
}
},
Note that this also results in a tiny refactor of our resize listener, removing it's trigger from the didInsertElement event and instead being triggered by initiateKnob which will happen not when the Ember component loads but instead lazy load at the first point of visibility in the DOM.
initiateKnob: function() {
var self = this;
this.set('isInitialised', true);
var options = this.buildOptions();
this.$('.knob').knob(options);
this.syncValue();
this.resizeDidHappen(); // get dimensions initialised on load
console.log('setting resize listener for %s', self.elementId);
self.resizeListener(); // add a listener for future resize events
},
resizeListener: function() {
this.$(window).on('resize', Ember.run.bind(this, this.resizeDidHappen));
},
Does it work?
To a large degree but not completely. Here's what works:
the first 'tab' which is visible at load resizes on demand
all tabs resize when they are switched to (aka, when they gain visibility)
what doesn't work is:
tabs other than the first tab do not resize (aka, the onresize callback appears broken)
The error I get is:
vendor.js:13693 Uncaught TypeError: undefined is not a function
Backburner.run vendor.js:13716
Backburner.join vendor.js:34296
run.join vendor.js:34349
run.bind vendor.js:4759
jQuery.event.dispatch vendor.js:4427
jQuery.event.add.elemData.handle
Not sure what to make of this ... any help would be appreciated. Full code can be found here:
https://gist.github.com/295e7e05c3f2ec92fb45.git
I am creating a sample application using ember 1.0 and ember-data 1.0 Beta 2.0. with RESTAdapter to connect to backend server.
When I try to save a record, it always invoke failure handler at the first submission. But the record actually gets saved at backend without fail. From the server the response for submission contains the created entity set with id.
When I try to debug the code in developer tools, it actually goes through the code for route transition, but then it returns back to Add view before completing the transition. It seems to be some callbacks from jQuery global event handlers are causing the problem.
Here is the code I am using
App.AddResourceRoute = App.ResourceManagerRoute.extend(
{
model: function () {
return this.store.createRecord('Resource');
},
actions: {
save: function () {
this.modelFor('AddResource').save().then(function (resource) {
App.Router.router.transitionToRoute('Resources');
}, function (reason) {
alert('Failure reason:' + reason);
});
}
}
});
Please help me to find out what is wrong with my code.
Thanks in advance
I think that you are receiving an error from App.Router.router.transitionToRoute('Resources'); invocation, try to update to the following:
App.AddResourceRoute = App.ResourceManagerRoute.extend(
{
model: function () {
return this.store.createRecord('Resource');
},
actions: {
save: function () {
var route = this;
this.modelFor('AddResource').save().then(function (resource) {
route.transitionTo('Resources');
}, function (reason) {
alert('Failure reason:' + reason);
});
}
}
});
You should use transitionTo(someRoute) inside of a route, or transitionToRoute(someRoute) when inside of a controller