I have a knockout component which looks something like this:
define(['knockout', 'text!./my-component.html', 'pubsub'], function(ko, htmlString, pubsub) {
function viewModel(params) { }
return {
viewModel: {
createViewModel: function(params, componentInfo) {
var vm = new viewModel(params);
pubsub('updateViewModel').subscribe(function(){
// update vm
});
return vm;
}
},
template: htmlString
};
});
I use the createViewModel function to subscribe to an update event, which I use later on to trigger an update of the components viewmodel from other components.
I include the compnent on my page like this:
<!-- ko component: "my-component" -->
<!-- /ko -->
What I would like some verification on is the load order of things. I want to be sure that the createViewModel has been invoked before I might trigger the event.
This is my current order of calls:
// register my-component here
ko.applyBindings(myMainViewModel);
// code that might trigger the component update event here
I've read that ko.applyBindings is sychronous. But does that also include an implicit applybindings to all registered components, like my-component above? Do I need to set the synchronous property to true on the component in order to achieve this? If I understand it correctly, that flag is only related to rendering.
What I want to avoid is a race condition where I trigger the update event before it has been subscribed.
ko.applyBindings can act synchronously if the following conditions are satisfied BEFORE calling:
All components are registered
ALL component viewmodels are loaded in memory (fetched from network..)
ALL component templates are loaded in memory
Its when the component viewmodel and templates are not in memory that applyBindings becomes async (event if you set the synchronous=true).
This synchronous flag comes in to play in applybindings from the component binding. Notice that component binding does a ko.components.get call and passes a call back which will render the component on the DOM.
knockout/src/components/loaderRegistry.js has the definition of ko.components.get. The synchronous flag says that if the component is already cached (in memory) DON'T relinquish control of the thread. Its only when you release control of the thread (setTimeout, DOM insert/wait, ..) that applyBindings will return.
The only thing I'm not too sure about is how RequireJS will interact in here. There is code in knockout which will try to resolve the component using require first.
In any case the following steps will bring you closer (NOT PERFECT. See notes bellow)
//Load component vm, template and register it with synchronous=true
ko.appplyBinding(....)
ko.components.get("my-component" , function() {
//trigger component update event
})
There are few problems with this, and there are solutions to all of them.
Need to wait for multiple components to finish loading
[to solve this you can create a promise array for each component and resolve each of them via ko.components.get. Finally you can $.when(mypromiseArray, myCallback) to synch up all the promises]
ko.component.get does NOT tell you when the component is finally rendered on the DOM.
This is a much more challenging problem. I will share the solution if you need this level of precision (you need to know with in 50ms of when the component is loaded, and rendered on the UI).
Related
So here's a weird KnockoutJS problem I've never actually come across before.
I'm working on an application that uses Knockout Components very heavily.
In one part of the app, I have an editor page that's built dynamically from a JSON driven backend, and which populates a front end page with a number of widgets, depending on what it's told from the back end data.
Example
The back end might send
[{"widget": "textBox"},{"widget": "textBox"},{"widget": "comboBox"},{"widget": "checkBox"}]
Which would cause the front end to build up a page containing
<html>
....
<textbox></textbox>
<textbox></textbox>
<combobox></combobox>
<checkbox></checkbox>
....
</html>
Each of the custom tags is an individual KnockoutJS component, compiled as an AMD module and loaded using RequireJS, each component is based on the same boiler plate:
/// <amd-dependency path="text!application/components/pagecontrols/template.html" />
define(["require", "exports", "knockout", 'knockout.postbox', "text!application/components/pagecontrols/template.html"], function (require, exports, ko, postbox) {
var Template = require("text!application/components/pagecontrols/template.html");
var ViewModel = (function () {
function ViewModel(params) {
var _this = this;
this.someDataBoundVar = ko.observable("");
}
ViewModel.prototype.somePublicFunction = function () {
postbox.publish("SomeMessage", { data: "some data" });
};
return ViewModel;
})();
return { viewModel: ViewModel, template: Template };
});
The components communicate with each other and with the page using "Knockout Postbox" in a pub sub fashion.
And when I put them into the page I do so in the following manor:
<div data-bind="foreach: pageComponentsToDisplay">
<!-- ko if: widget == "textBox" -->
<textBox params="details: $data"></textBox>
<!-- /ko -->
<!-- ko if: widget == "comboBox" -->
<comboBox params="details: $data"></comboBox>
<!-- /ko -->
<!-- ko if: widget == "checkBox" -->
<checkBox params="details: $data"></checkBox>
<!-- /ko -->
</div>
and where pageComponentsToDisplay is a simple knockout observable array that I just push the objects received from the backend onto:
pageComponentsToDisplay = ko.observableArray([]);
pageComponentsToDisplay(data);
Where 'data' is as shown in JSON above
Now all of this works great, but here-in now lies the ODD part.
If I have to do a "reload" of the page, I simply
pageComponentsToDisplay = ko.observableArray([]);
to clear the array, and consequently, all my components also disappear from the page, as expected, however when I load the new data in, again using:
pageComponentsToDisplay(data);
I get my new components on screen as expected, BUT the old ones appear to be still present and active in memory, even though there not visible.
The reason I know the controls are still there, because when I issue one of my PubSub messages to ask the controls for some state info, ALL of them reply.
It seems to me that when I clear the array, and when KO clears the view model, it actually does not seem to be destroying the old copies.
Further more, if I refresh again, I then get 3 sets of components responding, refresh again and it's 4, and this keeps increasing as expected.
This is the first time I've encountered this behaviour with knockout, and I've used this kind of pattern for years without an issue.
If you want a good overview of how the entire project is set up, I have a sample skeleton layout on my github page:
https://github.com/shawty/dotnetnotts15
If anyone has any ideas on what might be happening here I'd love to hear them.
As a final note, I'm actually developing all this using Typescript, but since this is a runtime problem, I'm documenting it from a JS point of view.
Regards
Shawty
Update 1
So after digging further (and with a little 'new thinking' thanks to cl3m's answer) I'm a little bit further forward.
In my initial post, I did mention that I was using Ryan Niemeyer's excelent PubSub extension for Knockout 'ko postbox'.
It turn's out, that my 'Components' are being disposed of and torn down BUT the subscription handlers that are being created to respond to postbox are not.
The result is, that the VM (or more specifically the values that the subscription uses in the VM) are being kept in memory, along with the postbox subscription handler.
This means when my master broadcasts a message asking for component values, the held reference responds, followed by the visibly active component.
What I need to now do is figure out a way to dispose these subscriptions, which because I'm using postbox directly, and NOT assigning them to an observable in my model, means I don't actually have a var or object reference to target them with.
The quest continues.
Update 2
See my self answer to the question below.
I'm not sure this will help but, as per my comment, here is how I use the ko.utils.domNodeDisposal.addDisposeCallback() in my custom bindings. Perhaps there is a way to use it in knockout components:
ko.bindingHandlers.tooltip = {
init: function(element, valueAccessor) {
$(element).tooltip(options);
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).tooltip('destroy');
});
}
}
More reading on Ryan Niemeyer's website
The problem it seems was due to Knockout hanging onto subscriptions set up by postbox when the actual components where active.
In my case, I use postbox purely as a messaging platform, so all i'm doing is
ko.postbox.subscribe("foo", function(payload) { ... });
all the time, since I was only ever using single shot subscriptions in this fashion, I was never paying ANY Attention to the values returned by the postbox subscription call.
I did things this way, simply because in many of the components I create there is a common API that they all use, but to which they all respond in different ways, so all I ever needed was a simple this is what to do when your called handler that was component specific, but not application specific.
It turns out however that when you use postbox in this manner, there is no observable for you to target, and as such there is nothing to dispose. (Your not saving the return, so you have nothing to work with)
What the Knockout and Postbox documentation does not mention, is that the return value from postbox.subscribe is a general Knockout subscription function, and by assigning the return from it to a property within your model, you then have a means to call the functionality available on it, one of those functions provides the ability to "dispose" the instance, which NOT ONLY removes the physical manifestation of the component from it's collection, BUT ALSO ensures that any subscriptions or event handlers connected to it are also correctly torn down.
Couple with that, the fact that you can pass a dispose handler to your VM when you register it, the final solution is to make sure you do the following
/// <amd-dependency path="text!application/components/pagecontrols/template.html" />
define(["require", "exports", "knockout", 'knockout.postbox', "text!application/components/pagecontrols/template.html"], function (require, exports, ko, postbox) {
var Template = require("text!application/components/pagecontrols/template.html");
var ViewModel = (function () {
function ViewModel(params) {
var _this = this;
this.someDataBoundVar = ko.observable("");
this.mySubscriptionHandler = ko.postbox.subscribe("foo", function(){
// do something here to handle subscription message
});
}
ViewModel.prototype.somePublicFunction = function () {
postbox.publish("SomeMessage", { data: "some data" });
};
return ViewModel;
ViewModel.prototype.dispose = function () {
this.mySubscriptionHandler.dispose();
};
return ViewModel;
})();
return { viewModel: ViewModel, template: Template, dispose: this.dispose };
});
You'll notice that the resulting class has a "dispose" function too, this is something that KnockoutJS provides on component classes, and if your class is managed as a component by the main KO library, KO will look for and execute if found, that function when your component class goes out of scope.
As you can see in my example, Iv'e saved the return from the subscription handler as previously mentioned, then in this hook point that we know will get called, used that to ensure that I also call dispose on each subscription.
Of course this ONLY shows one subscription, if you have multiple subscriptions, then you need multiple saves, and multiple calls at the end. An easy way of achieving this, especially if your using Typescript as I am, is to use Typescripts generics functionality and save all your subscriptions into a typed array, meaning at the end all you need to do is loop over that array and call dispose on every entry in it.
Is there any event fired stating the transition/rendering has completed (and the dom is visible/ready).
setupcontroller/activate are before the dom is built/rendered
didInsertElement gets fired only the first time when I've already inserted an element and I'm just switching the model out underneath it.
What I'm really looking for is the transition is complete event
I guess I can do this, but I was kind of hoping it was already built in...
Ember.Router.reopen({
didTransition:function(infos) {
this._super(infos);
console.log('transition complete');
}
});
Even cooler would be a callback to the route that the transition completed for it, I may have to write this and submit a pull request.
There are a couple of different ways you can solve this
didInsertElement
This is fired when the view is inserted on the first time, but not fired if the model is switched out under the view (because Ember likes to reuse items, since it's cheaper than rebuilding the entire DOM). Example below.
Simple
If you only need to do it once, the first time the view is inserted, use didInsertElement
App.FooView = Em.View.extend({
setupSomething: function(){
console.log('the dom is in place, manipulate');
}.on('didInsertElement')
});
Example: http://emberjs.jsbin.com/wuxemo/1/edit
Complex
If you need to schedule something after the DOM has been rendered from the route itself, you can use schedule and insert it into the afterRender queue.
App.FooRoute = Em.Route.extend({
setupController: function(controller, model){
this._super('controller', model);
Ember.run.schedule('afterRender', this, function () {
//Do it here
});
}
});
Example: http://emberjs.jsbin.com/wuxemo/2/edit
Transition promise
The transition's promise will complete before it's finished rendering items. But it gives you a hook for when it's done with fetching all of the models and controllers and hooking them up.
If you want to hook up to the transition event you can do it like so:
var self = this;
transitionTo('foo').then(function(){
Ember.run.schedule('afterRender', self, function () {
//Do it here
});
})
The afterModel hook might work for you:
App.MyRoute = Ember.Route.extend({
afterModel: function(model, transition) {
transition.then(function() {
// Done transitioning
});
}
});
I tested this using RC-7 with routes that both do and don't have dynamic segments (i.e., a route with a model and a route without a model). It seems to work either way.
See this JSBin for an RC-6 example:
Output: http://jsbin.com/OteC/1/
Source: http://jsbin.com/OteC/1/edit?html,js
setupController is the last thing that the Router calls before finalizing the transition. And if it completes without errors, as far as Ember is concerned the transition is complete. You actually see this in action by enabling LOG_TRANSITIONS_INTERNAL.
At that point, It doesn't matter if the controller has thrown an error, view has thrown an error, etc. The router has completed transitioning into the target route.
So setupController is the last place in terms of the Router that corresponds to didTransition.
When the content/model backing the controller changes on an existing View, the bindings kick in. Most of the changes that happen to the view at that point are via Metamorphing.
The closest place I can think of to hook into would be View.render which pushes changes into the RenderBuffer. But you still need to account for Metamorphing via mixins that happens here.
didTransition does exist as you hoped -- but its an action and not a hook
XXRouter
actions: {
didTransition: function() {
this.controller.set("hasTransitioned", true); // or whatever is needed?!
return true; // Bubble the didTransition event
},
}
XXController
observeTransition: function() {
alert('complete Transition');
}.observes('hasTransitioned'),
I have a hierarchy of nested KnockoutJS Components using 3.2.0. It's working very well but I'm looking to execute some code once my entire hierarchy of components has been loaded and rendered. It's a rough equivalent of afterRender(), needed for the same common uses cases as afterRender.
I've tried a few approaches but no luck so far:
Added the following to the root template but it gets called before the nested components are loaded, so too early.
<!--ko template: {afterRender: onLoad.bind($data)} -->
Using the latest 3.3.0-alpha and specifying synchronous:true on all components. But I believe since I'm using AMD, the components are still 'loaded' asynchronously which mean that just because my root applyBindings() returns, doesn't mean that all components have been loaded and rendered.
Even tried building a collection of deferred objects that get resolved only when their corresponding components are loaded. This got overly complicated and still didn't work for reasons I won't go into.
Is there a way to get a callback called once a complete hierarchy of knockoutjs components have been loaded and rendered? Thanks!
I just came across these two threads so it seems others are looking for this as well. The key differentiator from the existing workarounds are they don't work with nested components.
https://github.com/knockout/knockout/issues/1533
https://github.com/knockout/knockout/issues/1475
I've written a knockout library that triggers an event when all components have been loaded and bound. It uses reference counting, similar to referencing counting used for garbage collection. I extensively use components in my project(s), including nesting many levels deep, and I can't live without knowing when everything is "ready to go". I haven't spend much time on documentation of usage, but the basics are there.
Git Hub wiki:
https://github.com/ericraider33/ko.component.loader/wiki
Fiddle:
https://jsfiddle.net/ericeschenbach/487hp5zf/embedded/result/
Usage HTML:
<div id="ko-div">
Status: <span data-bind="text: loading() ? 'Loading' : 'Done'"></span>
<br><br>
<test-panel></test-panel>
</div>
Usage JS:
var pageModel = {
loading: ko.observable(true),
completedCallback: function (childRef) {
pageModel.loading(false);
childRef.testValue(childRef.testValue()+1);
}
};
var tpRef = ko.componentLoader.ref.child({ completedCallback: pageModel.completedCallback});
var tpModel = {
attached: function(element) { return tpRef; },
testValue: ko.observable(5)
};
ko.components.register('test-panel', {
viewModel: function() { return tpModel; },
template: '<div data-bind="attached: true">Test Panel<br>From Code <span data-bind="text: testValue"></span></div>'
});
ko.componentLoader.setOptions({ verbose: true });
ko.applyBindings(pageModel, $('#ko-div')[0]);
Here is what worked for me. I did not try it in all possible variations such as mixing sync and async components, or using custom component loaders.
There is a method in KO 3.3.0 that all components loading goes through:
ko.components = { get: function(componentName, callback) { ...
the get method is invoked with a desired componentName and when component has been loaded - a callback is invoked.
So all you need to do is wrap ko.components.get and callback and increment pendingComponentsCount on each call, and decrement it after callback is executed. When count reaches zero it means that all components were loaded.
25 lines of JS code (using underscorejs).
You also need to handle a special case where ko.applyBindings did not encounter any components, in which it also means that all components (all zero of them) were loaded.
Again, not sure if this works in every situation, but it seems to be working in my case. I can think of few scenarios where this can easily break (for example if somebody would cache a reference to ko.components.get before you get to wrap it).
If you'r working with ko.components this might be of use:
1) Create a deferred object to keep track of each component loading
var statusX = $.Deferred()
var statusY = $.Deferred()
2) Inform knockout to tell you when the component is loaded and ready
ko.components.get('x-component', statusX.resolve) //Note: not calling resolve, but passing the function
ko.components.get('y-component', statusY.resolve)
3) Synch up both status deferreds
$.when(statusX.promise(), statusY.promise())
.done( function allComponentsLoaded(componentX, componentY){
//Both components are ready here
//Note the arguments from the function comes via
//ko->jquery deferred resolve
});
I would like to include multiple mixins within a view in Ember.js and more than one of the mixins and/or the view uses a same event (e.g. willInsertElement). I'm running Ember 1.4.0-beta.5.
I understand that the event in each mixin will be overridden by the view. However, I have read that it is possible to use the same event hook in the mixin and view, or multiple mixins included in the same view, by calling this._super(); at the start of the mixin's aforementioned event method. However, I have not been able to successfully make this happen. My question is, thus, how can I write logic within the same event hook in a view and mixin (or multiple mixins included in the same view) so that all the logic within each occurrence of the event hook will be called.
Here is an example:
App.StatsView = Em.View.extend(
App.DateFormatting, {
willInsertElement: function() {
// Some view-specific logic I want to call here
},
});
App.DateFormatting = Em.Mixin.create({
willInsertElement: function() {
this._super(); // This doesn't work.
// Some mixin logic I want to call here
},
});
N.B. One approach here might be to not use a mixin and extend a view instead (because willInsertElement is specific to Em.View), but that isn't maintainable in our apps.
If the different functions you're using are not dependent on each other, it's the best solution to not override the willInsertElement hook, but to tell the function to be raised when the event/hook gets called.
Like:
App.StatsView = Em.View.extend(App.DateFormatting, {
someSpecificFunction: function () {
console.log('beer me');
}.on('willInsertElement')
});
App.DateFormatting = Em.Mixin.create({
dateFormattingFunction: function () {
console.log('beer you');
}.on('willInsertElement')
});
Is there any event fired stating the transition/rendering has completed (and the dom is visible/ready).
setupcontroller/activate are before the dom is built/rendered
didInsertElement gets fired only the first time when I've already inserted an element and I'm just switching the model out underneath it.
What I'm really looking for is the transition is complete event
I guess I can do this, but I was kind of hoping it was already built in...
Ember.Router.reopen({
didTransition:function(infos) {
this._super(infos);
console.log('transition complete');
}
});
Even cooler would be a callback to the route that the transition completed for it, I may have to write this and submit a pull request.
There are a couple of different ways you can solve this
didInsertElement
This is fired when the view is inserted on the first time, but not fired if the model is switched out under the view (because Ember likes to reuse items, since it's cheaper than rebuilding the entire DOM). Example below.
Simple
If you only need to do it once, the first time the view is inserted, use didInsertElement
App.FooView = Em.View.extend({
setupSomething: function(){
console.log('the dom is in place, manipulate');
}.on('didInsertElement')
});
Example: http://emberjs.jsbin.com/wuxemo/1/edit
Complex
If you need to schedule something after the DOM has been rendered from the route itself, you can use schedule and insert it into the afterRender queue.
App.FooRoute = Em.Route.extend({
setupController: function(controller, model){
this._super('controller', model);
Ember.run.schedule('afterRender', this, function () {
//Do it here
});
}
});
Example: http://emberjs.jsbin.com/wuxemo/2/edit
Transition promise
The transition's promise will complete before it's finished rendering items. But it gives you a hook for when it's done with fetching all of the models and controllers and hooking them up.
If you want to hook up to the transition event you can do it like so:
var self = this;
transitionTo('foo').then(function(){
Ember.run.schedule('afterRender', self, function () {
//Do it here
});
})
The afterModel hook might work for you:
App.MyRoute = Ember.Route.extend({
afterModel: function(model, transition) {
transition.then(function() {
// Done transitioning
});
}
});
I tested this using RC-7 with routes that both do and don't have dynamic segments (i.e., a route with a model and a route without a model). It seems to work either way.
See this JSBin for an RC-6 example:
Output: http://jsbin.com/OteC/1/
Source: http://jsbin.com/OteC/1/edit?html,js
setupController is the last thing that the Router calls before finalizing the transition. And if it completes without errors, as far as Ember is concerned the transition is complete. You actually see this in action by enabling LOG_TRANSITIONS_INTERNAL.
At that point, It doesn't matter if the controller has thrown an error, view has thrown an error, etc. The router has completed transitioning into the target route.
So setupController is the last place in terms of the Router that corresponds to didTransition.
When the content/model backing the controller changes on an existing View, the bindings kick in. Most of the changes that happen to the view at that point are via Metamorphing.
The closest place I can think of to hook into would be View.render which pushes changes into the RenderBuffer. But you still need to account for Metamorphing via mixins that happens here.
didTransition does exist as you hoped -- but its an action and not a hook
XXRouter
actions: {
didTransition: function() {
this.controller.set("hasTransitioned", true); // or whatever is needed?!
return true; // Bubble the didTransition event
},
}
XXController
observeTransition: function() {
alert('complete Transition');
}.observes('hasTransitioned'),