knockout.js, afterrender function doesnt work as expected - templates

I got an issue with my code, im using hljs to highlight my code snippets which im using. I wrote a template system, as example the general input would be this:
<codeexample params="type: html">
<div style="example_class">Example code</div>
</codeexample>
My template interpreter:
<template id="codeexample">
<div class="code">
<pre><code data-bind="attr: {class: type}, template: { nodes: $componentTemplateNodes, afterRender: $root.handleCode}, visible: false ">
</code></pre>
</div>
</template>
My handleCode function:
this.handleCode = function(element) {
var preCodeTags = $(element).find('pre code');
preCodeTags.each(function(i, block) {
hljs.highlightBlock(block);
block.show(100);
});
}
The problem is that the afterRender function is called already before the template is rendered to my actual template, i used to add a console.log($(element).find('pre code')); which had the result that the length was 0.
[prevObject: jQuery.fn.jQuery.init[3], context: undefined, selector:
"pre code", constructor: function, init: function…]
context: undefined
length: 0
Shouldnt the function afterRender run exactly after the render process?
Is there a known work around? When I use a timeout for 200ms, it works fine, but this is the worst solution in my opinion.

Your afterRender handler isn't quite right. The parameter (element in your case) is actually an array of all elements rendered. From the documentation:
viewModel.myPostProcessingLogic = function(elements) {
// "elements" is an array of DOM nodes just rendered by the template
// You can add custom post-processing logic here
}
So it's not finding the code element successfuly. You could do this instead:
this.handleCode = function(elements) {
var preCodeTags = $(elements).filter('div').find('pre code');
preCodeTags.each(function(i, block) {
hljs.highlightBlock(block);
block.show(100);
});
}

Related

ember-resources trackedTask with cached value

I've recently started looking into the nice ember-resources library because I came to the point my data fetching routine required some reactivity. Since we tend to use the ember-concurrency tasks in our project I wanted to follow the common pattern and I was happy to realise that ember-resources support ember-concurrency tasks out of the box.
Now i've got a dependant tracked property which is basically a timer and it's being updated every minute. What I want to do is to be able to run my task say every two minutes. The question is how to achieve this?
Here goes my pseudo-code:
// that's my component
#restartableTask
*fetchFeed() {
yield timeout(1);
return yield this.store.queryRecord('item', {...});
}
get currentTime() {
// this one returns a tracked variable which is updated every minute
}
feedResource = trackedTask(this, this.fetchFeed, () => [this.currentTime]);
// this is the corresponding hbs
{{#if this.feedResource.isRunning}}
<LoadingSpinner />
{{else}}
{{this.feedResource.value}}
{{/if}}
what I want to do is basically
get every2Minutes() {
return Math.trunc(this.currentTime.second() / 2)
}
feedResource = trackedTask(this, this.fetchFeed, () => [this.every2Minutes]);
but it's still run on every minute. I've tried using the #cached attribute and a custom cache solution but it didn't help - despite that the cache gave me the correct value, i.e. only even ones, the task was still fired every minute. Can I tell the trackedTask to not fire if the dependency wasn't changed?
👋 Hi, I'm the author of ember-resources! glad you're having fun with the library!
this one returns a tracked variable which is updated every minute
While this is clever, if the variable isn't used in the task, it "feels weird". I don't have better words for this. 🙃
But, to directly answer your question, I'd define currentTime like this:
const ClockEveryOtherMinute = resource(({ on }) => {
let time = cell(new Date());
let interval = setInterval(
() => time.current = new Date(),
2 * 60 * 1000, // 2 minutes
);
on.cleanup(() => clearInterval(interval));
return () => time.current;
});
class Foo {
// `#use` is required when a resource returns a single value
#use currentTime = ClockEveryOtherMinute;
feedResource = trackedTask(this, this.fetchFeed, () => [this.currentTime]);
// ...etc
}
Here is an interactive demo of something very similar
However, I think there may be a more ergonomic way --
In a scenario where you want recurring behavior, there are a couple approaches you could take:
invoke the task once and use a while loop to do something periodically
use a constructor/destructor combo with setInterval
These are somewhat separate from the trackedTask helper utility, as the trackedTask helper utility "only" does lazy invocation of the .perform method on a task when a property on the TaskInstance would be accessed. So... I'm not actually sure if your getter's return would be updated if the task is re-performed every couple minutes manually. I'm maybe.. 60% sure it would? (this is something I don't have tests for).
Anywho back to the options:
invoke the task once
class Foo extends Component {
#tracked items;
#task
*fetchFeed() {
yield timeout(1);
while(true) {
this.items = yield this.store.queryRecord('item', {...});
yield timeout(1000 * 60 * 2); // 2 minutes
}
}
get hasItems() {
return Boolean(this.items?.length);
}
}
// this is the corresponding hbs
{{#if this.hasItems}}
{{this.items}}
{{else}}
<LoadingSpinner />
{{/if}}
using setInterval
import { registerDestructor } from '#ember/destroyable';
class Foo extends Component {
#tracked items;
constructor(owner, args) {
super(owner, args);
let interval = setInterval(() => {
if (isDestroyed(this) || isDestroying(this)) return;
this.fetchFeed.perform();
}, 2 * 60 * 1000);
registerDestructor(this, () => {
clearTimeout(interval);
});
// initial perform
this.fetchFeed.perform();
}
#task
*fetchFeed() {
yield timeout(1);
return yield this.store.queryRecord('item', {...});
}
get hasItems() {
return Boolean(this.fetchFeed.lastSuccessful?.value?.length);
}
}
// this is the corresponding hbs
{{#if this.hasItems}}
{{this.fetchFeed.lastSuccessful.value}}
{{else}}
<LoadingSpinner />
{{/if}}
A "do something every 2 minutes API"
I'm 🤷‍♂️ on this approach, but for completeness, it's probably reasonable to know that it's possible (I'm going to hand-wave over the implementation, as that could be other stack-overflow questions):
const doEveryTwoMinutes = resourceFactory((callback) => {
// ...
return resource(({ on }) => {
// ...
});
});
class Foo extends Component {
#use feed = doEveryTwoMinutes(() => {
return this.fetchFeed.perform(); // returns a task
});
#task
*fetchFeed() {
yield timeout(1);
return yield this.store.queryRecord('item', {...});
}
get hasItems() {
return Boolean(this.feed.length);
}
}
// this is the corresponding hbs
{{#if this.hasItems}}
{{this.feed}}
{{else}}
<LoadingSpinner />
{{/if}}
(no trackedTask needed, we rely on the internal tracked-state of a TaskInstance)
Why do these approaches not need trackedTask?
because we have "events" that we know about that cause the task to be performed -- and ember-concurrency is really good at being "an event handler", of sorts -- whereas ember-resources is more about deriving data (maybe eventually), with cleanup.

angular2 - adding 'pattern' for form builder

I have a pattern for a form builder and I have this:
this.userForm = this.formBuilder.group({
'postalCode': ['', Validators.pattern('/[A-Za-z][0-9][A-Za-z] [0-9][A-Za-z][0-9]/i')]
});
I have a ValidationService which I've added a function "getValidatorErrorMessage".
static getValidatorErrorMessage(validatorName: string, validatorValue?: any) {
let config = {
'pattern': 'invalid pattern'
};
return config[validatorName];
}
My template has:
<div>
<label for="postalCode">Postal code (A1A 2J3)</label>
<input formControlName="postalCode" id="postalCode" />
<control-messages [control]="userForm.controls.postalCode"></control-messages>
</div>
But for some odd reason, the validation messages arent displaying if I dont follow the regex code.
You can view the plunkr here.
That's because you set a condition in your ControlMessagesComponent that input field has to be touched in order for error message to be displayed:
get errorMessage() {
for (let propertyName in this.control.errors) {
if (this.control.errors.hasOwnProperty(propertyName) &&
this.control.touched) { // this line
return ValidationService.getValidatorErrorMessage(propertyName, this.control.errors[propertyName]);
}
}
return null;
}
If you remove this.control.touched, validation will be performed as you type. But this also will result in required messages being displayed right away. Combination I prefer most is to display error message in two cases: when user clicks on input field and then clicks somewhere else or when user starts typing which can be achieved with following condition:
if (this.control.errors.hasOwnProperty(propertyName) &&
this.control.dirty ||
this.control.touched)

UI-grid grouping auto expand

Does anybody know how to automatically expand a UI-grid that is performing a grouping? I need the grid to open up and start up with it being completely expanded.
Their API and Tutorial reference doesn't explain explicitly enough for me to understand.
My HTML div
<code>
<div id="grid1" ui-grid="resultsGrid" class="myGrid" ui-grid-grouping></div>
</code>
My Javascript
$scope.resultsGrid = {
,columnDefs: [
{ field:'PhoneNum', name:'Phone'},
{ field:'Extension', name:'Extension'},
{ name:'FirstName'},
{ field:'DeptDesc', grouping: {groupPriority: 0}}
]
,onRegisterApi: function(gridApi)
{
$scope.gridApi = gridApi;
}
}
you just need to add
//expand all rows when loading the grid, otherwise it will only display the totals only
$scope.gridApi.grid.registerDataChangeCallback(function() {
$scope.gridApi.treeBase.expandAllRows();
});
in your onRegisterApi: function(gridApi)that should be updated like this onRegisterApi: function(gridApi) so your function will be like this
$scope.resultsGrid.onRegisterApi = function(gridApi) {
//set gridApi on scope
$scope.gridApi = gridApi;
//expand all rows when loading the grid, otherwise it will only display the totals only
$scope.gridApi.grid.registerDataChangeCallback(function() {
$scope.gridApi.treeBase.expandAllRows();
});
};
or you can add botton to expand data like shown in this plunker
My Module - I had to add ui.gridl.selection
<pre>
<code>
angular.module('ddApp',['ngRoute','ngSanitize','ngCookies','ngResource','ui.grid.selection'])
</code>
</pre>
My Controller - Amongh the other Dependency Injected items, I also had to add $timeout
<pre>
<code>
.controller('myCtrl', function(`$`timeout)){}
</code>
</pre>
<pre>
<code>
$timeout(function(){
if($scope.gridApi.grouping.expandAllRows){
$scope.gridApi.grouping.expandAllRows();
}
});
</code>
</pre>
The closest analogy would the selection tutorial, in which we select the first row after the data finishes loading: http://ui-grid.info/docs/#/tutorial/210_selection
$http.get('/data/500_complex.json')
.success(function(data) {
$scope.gridOptions.data = data;
$timeout(function() {
if($scope.gridApi.selection.selectRow){
$scope.gridApi.selection.selectRow($scope.gridOptions.data[0]);
}
});
});
The key understanding is that you can't select (or expand) data that hasn't been loaded yet. So you wait for the data to return from $http, then you give it to the grid, and you wait for 1 digest cycle for the grid to ingest the data and render it - this is what the $timeout does. Then you can call the api to select (or in your case, expand) the data.
So for you, you'd probably have:
$http.get('/data/500_complex.json')
.success(function(data) {
$scope.gridOptions.data = data;
$timeout(function() {
if($scope.gridApi.grouping.expandAllRows){
$scope.gridApi.grouping.expandAllRows();
}
});
});
If you're on the latest unstable, that call will change to $scope.gridApi.treeBase.expandAllRows.

How do you know when templates have been initialized in polymer dart?

The polymer js docs say you have to listen for the WebComponentsReady event to know when the polymer elements have been set up. What's the equivalent in Dart?
Here's my template:
<template id="order_name" bind repeat>
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#order_list" href="#collapseOne">
{{commonName}} ({{scientificName}})
</a>
</div>
<div id="collapseOne" class="accordion-body collapse">
<div class="accordion-inner">
...
</div>
</div>
</div>
</template>
And here's main:
void main() {
OrderList().then((order_data) {
query("#order_name").model = order_data;
print (queryAll(".accordion-heading")); //null
}).catchError((err) => print(err));
query("#my-button").onClick.listen((Event e) {
print (queryAll(".accordion-heading")); //[div,div]
});
}
OrderList is a wrapper around HttpRequest.getString() and returns a future. My thought was to use an event like WebComponenentsReady to know when the template had been fully instantiated. The base question is how can I get at the .accordion-heading divs in main so I can attach listeners to them?
I assume that you are using boot.js. if you are, they should be initialized by the time you program enters main().
According to the spec (https://www.dartlang.org/articles/web-ui/spec.html#main-script):
...you cannot query for children of conditional and iteration nodes. ...To retrieve a component instance you need to defer queries until the end of the event loop, for example using a Timer.run(f).
So the code above needs to be modified like this:
void main() {
OrderList().then((order_data) {
query("#order_name").model = order_data;
print (queryAll(".accordion-heading")); //null
Timer.run( () => print (queryAll(".accordion-heading"))); //[div,div]
}).catchError((err) => print(err));
query("#my-button").onClick.listen((Event e) {
print (queryAll(".accordion-heading")); //[div,div]
});
}

angularjs if statements?

So I'm running through the tutorial for AngularJS:
I have an array defined in the controller and i'm returning different points in the array by calling when i'm looping through ng-repeat {{feature.name}} {{feature.description}}
What i don't understand is lets say i have a third point in the array called "importance" and it's a number from 1 to 10. I don't want to display that number in the html but what i do want to do is apply a different color to the feature if that "importance" number in the array is 10 vs 1
so how do i write an if statement to do this:
i.e.
<p style="**insert if statement: {{if feature.importance == 10}} color:red; {{/if}} **">{{feature.description}}</p>
no idea if that's right but that's what i want to do
I do not think there is if statement available.
For your styling purpose, ng-class can be used.
<p ng-class="{important: feature.importance == 10 }">
ng-switch is also convenient.
-- update --
take a look at:
https://stackoverflow.com/a/18021855/1238847
angular1.2.0RC seems to have ng-if support.
Actually there is a ternary operator in Angular 1.2.0.
<p style="{{feature.importance == 10 ? 'color:red' : ''}}">{{feature.description}}</p>
I think the answer needs an update.
Previously you could use ngIf directive from AngularUI project (code here if you still want to download it), bad news is that it's not maintained any more.
The good news is that it has been added to the official AngularJS repo (unstable branch) and soon will be available in the stable one.
<div ng-if="something"> Foo bar </div>
Will not just hide the DIV element, but remove it from DOM as well (when something is falsy).
ng-class is probably the best answer to your issue, but AngularUI has an "if" directive:
http://angular-ui.github.com/
search for:
Remove elements from the DOM completely instead of just hiding it.
I used "ui-if" to decide if I should render a data value as a label or an input, relative to the current month:
<tbody id="allocationTableBody">
<tr ng-repeat="a in data.allocations">
<td>{{a.monthAbrv}}</td>
<td ui-if="$index < currentMonth">{{a.amounts[0]}}</td>
</tr>
</tbody>
In the case where your priority would be a label, you could create a switch filter to use inside of ng-class as shown in a previous SO answer : https://stackoverflow.com/a/8309832/1036025 (for the switch filter code)
<p ng-class="feature.importance|switch:{'Urgent':'red', 'Warning': 'orange', 'Normal': 'green'}">...</p>
You can also try this line of code below
<div class="{{is_foo && foo.bar}}">
which shows foo.bar if is_foo is true.
This first one is a directive that evaluates whether something should be in the DOM only once and adds no watch listeners to the page:
angular.module('setIf',[]).directive('setIf',function () {
return {
transclude: 'element',
priority: 1000,
terminal: true,
restrict: 'A',
compile: function (element, attr, linker) {
return function (scope, iterStartElement, attr) {
if(attr.waitFor) {
var wait = scope.$watch(attr.waitFor,function(nv,ov){
if(nv) {
build();
wait();
}
});
} else {
build();
}
function build() {
iterStartElement[0].doNotMove = true;
var expression = attr.setIf;
var value = scope.$eval(expression);
if (value) {
linker(scope, function (clone) {
iterStartElement.after(clone);
clone.removeAttr('set-if');
clone.removeAttr('wait-for');
});
}
}
};
}
};
});
This second one is a directive that conditionally applies attributes to elements only once without watch listeners:
i.e.
<div set-attr="{ data-id : post.id, data-name : { value : post.name, condition : post.name != 'FOO' } }"></div>
angular.module('setAttr',[]).directive('setAttr', function() {
return {
restrict: 'A',
priority: 100,
link: function(scope,elem,attrs) {
if(attrs.setAttr.indexOf('{') != -1 && attrs.setAttr.indexOf('}') != -1) {
//you could just angular.isObject(scope.$eval(attrs.setAttr)) for the above but I needed it this way
var data = scope.$eval(attrs.setAttr);
angular.forEach(data, function(v,k){
if(angular.isObject(v)) {
if(v.value && v.condition) {
elem.attr(k,v.value);
elem.removeAttr('set-attr');
}
} else {
elem.attr(k,v);
elem.removeAttr('set-attr');
}
});
}
}
}
});
Of course your can use dynamic versions built into angular:
<div ng-class="{ 'myclass' : item.iscool }"></div>
You can also use the new ng-if added by angularjs which basically replaces ui-if created by the angularui team these will conditionally add and remove things from the DOM and add watch listeners to keep evaluating:
<div ng-if="item.iscool"></div>
What also works is:
<span>{{ varWithValue || 'If empty use this string' }}</span>