When does a listView itemTemplate get inserted into the DOM? - javascript

I have created a custom itemTemplateFunction as described here. However I want to access attributes (such as height, or clientHeight) which are defined upon rendering in the DOM. This is to allow for a child element to be offset dynamically in the layout.
I've currently looked into two methods:
renderComplete - returned as an element in the itemPromise then return object. The event fired as expected, however the attributes (such as height) did not have set values, so it looks as though the item is not in the DOM at this point.
setInterval - although this would work it's a bad solution as I am relying on a constant time offset, something which ideally I don't want to do.
function itemTemplateFunction(itemPromise) {
return itemPromise.then(function (item) {
var div = document.createElement("div");
var img = document.createElement("img");
img.src = item.data.picture;
img.alt = item.data.title;
div.appendChild(img);
var childDiv = document.createElement("div");
var title = document.createElement("h4");
title.className += "title";
title.innerText = item.data.title;
childDiv.appendChild(title);
var desc = document.createElement("h6");
desc.innerText = item.data.text;
childDiv.appendChild(desc);
div.appendChild(childDiv);
return {
element: div,
renderComplete: itemPromise.then(function (item){
return item.ready;
}).then(function (item){
var height_a = div.querySelector(".title").clientHeight;
var height_b = WinJS.Utilities.query(".title", div).clientHeight;
})
}
});
};
With the first item created the attributes still haven't been finalised, despite the promise being passed back. If however I wrap the return of item.ready in a second promise with a timeout interval of 0 this does return as expected.
return {
element: div,
renderComplete: itemPromise.then(function (item){
return WinJS.Promise.timeout(0).then(function () {
return item.ready;
});
}).then(function (item){
var height_a = div.querySelector(".title").clientHeight;
var height_b = WinJS.Utilities.query(".title", div).clientHeight;
})
}

The hook you're looking for is the item.ready property, once you're inside the completed handler for itemPromise.then().
item.ready is itself a promise that's fulfilled when the item gets rendered, at which point all the layout-dependent attributes should be set.
To use it, return item.ready from your first completed handler for itemPromise.then, and then add another .then(function (item) {} ) to the chain. Inside that complete handler is where you can check the attributes.
I go into some detail on this in Chapter 7 of my free ebook, Programming Windows Store Apps in HTML, CSS, and JavaScript, 2nd Edition, specifically in the section at the end of the chapter called "Template Functions (Part 2): Optimized Item Rendering" and the discussion of multistage rendering. The same content also appeared on the older Windows 8 developer blog, although note that the "recycling placeholder" option discussed on the blog is for WinJS 1.0 only.

Related

Creating new elements at runtime using Mithril

Using Mithril, a Javascript framework, I am trying to add new elements after the initial body has been created and rendered.
Here is my problem in it's most basic form:
let divArray = [];
let newDivButton = m('button', { onclick: ()=> {
divArray.push(m('div', "NEW DIV PUSHED"));
}}, "Add new div");
divArray.push(newDivButton);
divArray.push(m('div', "NEW DIV PUSHED"));
let mainDiv = {
view: () => {
return divArray;
}
}
m.mount(document.body, mainDiv);
The code above will create a button and one line of text saying NEW DIV PUSHED. The button adds one new text element exactly like the 1st one. The problem here is that those additional elements are simply not rendered even if the view function is called. I stepped in the code and clearly see that my divArray is being populated even if they are not rendered.
One thing I noticed is that the initial text element (the one that is rendered) has it's dom property populated by actual div object. All the subsequent text elements in my array have their dom property set to undefined. I don't know how to fix this but I am convinced it is related to my problem.
Mithril has an optimization built into the render lifecycle - it won't re-render a DOM tree if the tree is identical to the last tree. Since divArray === divArray is always true the nodes are never re-rendering.
The simple, but non-ideal solution is to slice your array so you're always returning a new array from mainDiv#view and therefore, Mithril will always re-render the top-level array:
let mainDiv = {
view: () => {
return divArray.slice();
}
};
The more correct way to do this is to map over the data, creating vnodes at the view layer, rather than keeping a list of vnodes statically in your module scope:
let data = ["Data Available Here"];
let mainDiv = {
view: () => {
return [
m(
'button',
{ onclick: () => data.push("Data Pushed Here") },
"Add new div"
);
].concat(
data.map(datum => m('div', datum))
);
}
};

How do I sort the existing stream in rxjs?

I'm new to RxJs. I have a response stream which is getting data from ajax. Also, I have another button to sort by. I can sort without any problem. My question is if I do the sorting and updating properly? What I'm doing is essentially just empty the child nodes and append new result.
(function($, _) {
var fetchRepoButton = $('.fetch');
var sortByButton = $('.sort-by');
var fetchRepoClickStream = Rx.Observable.fromEvent(fetchRepoButton, 'click');
var sortByClickStream = Rx.Observable.fromEvent(sortByButton, 'click');
var requestStream = fetchRepoClickStream.map(function() {
return '/api';
});
var responseStream = requestStream.flatMap(function (requestUrl) {
return Rx.Observable.fromPromise($.getJSON(requestUrl));
});
responseStream.subscribe(function (es) {
var repositories = $('.container');
repositories.empty();
var names = es.map(function (e) {
return {name: e.name};
}).forEach(function (e) {
var rep = $('<div>');
rep.html(e.name);
repositories.append(rep);
});
});
var sortByStream = sortByClickStream.combineLatest(responseStream, function (click, es) {
return _.sortBy(es, function(e) {
return e.count;
}).reverse().map(function (e) {
return {name: e.name, count: e.count};
});
});
sortByStream.subscribe(function(es) {
var repositories = $('.container');
repositories.empty();
var names = es.map(function (e) {
return {name: e.name};
}).forEach(function (e) {
var rep = $('<div>');
rep.html(e.name);
repositories.append(e);
});
});
})($, _);
I'm playing with the code right now. So there might be duplication.
There is nothing incorrect with your code, and your RxJS usage looks fine, though your DOM usage is not as optimized as it could be. Creating/deleting all those DOM elements is a relatively expensive process, so ideally you want to resume elements where possible. Your sorting code seems ripe for optimizing in this respect.
When you sort your list, you know that DOM elements already exist for each. Instead of deleting all of them, then recreating them in the right order, I would instead use detach() to remove the element from the page and return it, then later use container.append(element) to add them in the right order.
If I was implementing it, I'd do something like rep.data('listCount', e.count) when I originally create the element, so we can sort the jQuery elements directly, then sort the list with:
sortByClickStream.subscribe(function() {
var container = $('.container');
// `.children()` returns raw DOM elements, so wrap each in jQuery
_.map(container.children(), function(el) { return $(el); })
.sortBy(function(item) { return item.data('listCount'); })
.reverse()
.forEach(function(item) {
item.detach();
container.append(item);
});
});
Doing something similar with the response stream list is possible, but a lot more work, since you can't guarantee that each element in the latest list already has an element.
Overall, what you have will work fine, and should be fast enough for small/medium-sized lists. If it appears to get sluggish with your expected list size, then I'd start optimizing DOM code. Frameworks like Angular have entire libraries dedicated to 'DOM diffing' to figure out the minimal number of changes needed to modify the DOM for updated content. If you are doing a lot of this sort of content updates, I'd look into using a library/framework that has this built-in.

Protractor clicking nested elements based on a condition, error - Async callback was not invoked within timeout specified

I am trying to create a Page Object for one of the Reusable UI Controls we are using in our application, which is a table having bunch of headers(th) with buttons to filter. I want to click the button of a particular th element. Here is my code
this.gridAllColumns = browser.element(by.css('[grid-service=envGridService]')).all(by.tagName('th'));
this.filterColumn = function(columnName){
gridAllColumns.each(function(element){
var text = element.getText();
if( text = columnName){
console.log(text);
var buttonElement = element.element(by.tagName('button'));
buttonElement.click();
}
});
}
I am getting the below error
Error: Timeout - Async callback was not invoked within timeout
specified
What I am doing wrong? Could any one point me in right direction please?
You need to refer to the gridAllColumns using this and you need to use filter():
this.filterColumn = function(columnName) {
this.gridAllColumns.filter(function(header) {
return header.getText().then(function (headerText) {
return headerText === columnName;
});
}).first().element(by.tagName('button')).click();
}

KnockoutJS custom binding calling click event during bind, not on click

I`m attempting to bind an observable array of people two a two column responsive layout with click events using knockoutjs.
I have created a custom binding called TwoCol that loops through the array, and appends nodes to the DOM to create my suggested layout, but the click events are giving me trouble when I try to apply them in a custom binding nested in a loop.
I have played with it quite a bit, and encountered all types of results, but where I`m at now is calling my ~click~ event during binding, rather than on click.
http://jsfiddle.net/5SPVm/6/
HTML:
<div data-bind="TwoCol: Friends" id="" style="padding: 20px">
JAVASCRIPT:
function FriendsModel() {
var self = this;
this.Friends = ko.observableArray();
this.SelectedFriend = "";
this.SetSelected = function (person) {
alert(person);
self.SelectedFriend = person;
}
}
function isOdd(num) {
return num % 2;
}
ko.bindingHandlers.TwoCol = {
update: function (elem, valueAccessor) {
var i = 0;
var rowDiv;
var vFriends = ko.utils.unwrapObservable(valueAccessor());
$(elem).html('');
while (i < vFriends.length) {
//create row container every other iteration
if (!isOdd(i)) {
rowDiv = document.createElement("div");
$(rowDiv).addClass("row-fluid");
elem.appendChild(rowDiv);
}
//add column for every iteration
var colDiv = document.createElement("div");
$(colDiv).addClass("span6");
rowDiv.appendChild(colDiv);
//actual code has fairly complex button html here
var htmlDiv = document.createElement("div");
var htmlButton = vFriends[i]
htmlDiv.innerHTML = htmlButton;
colDiv.appendChild(htmlDiv);
//i think i need to add the event to the template too?
//$(htmlDiv).attr("data-bind", "click: { alert: $data }")
//it seems that the SetSelected Method is called while looping
ko.applyBindingsToDescendants(htmlDiv, { click: friends.SetSelected(vFriends[i]) });
i++;
}
return { controlsDescendantBindings: true };
}
}
var friends = new FriendsModel();
friends.Friends.push('bob');
friends.Friends.push('rob');
friends.Friends.push('mob');
friends.Friends.push('lob');
ko.applyBindings(friends);
I don't think you're using ko.applyBindingsToDescendants correctly. I admit I'm a little confused as to the meaning of some of the values in your code, so I may have interpreted something incorrectly.
Here's a fiddle where I think it's working the way you intended:
http://jsfiddle.net/5SPVm/7/
http://jsfiddle.net/5SPVm/8/
Notice if manually control descendant bindings (return { controlsDescendantBindings: true };), you need to set that up in the init callback, instead of update. The update callback is too late for that.
Quick rundown of the changes (edited):
Moved the controlsDescendantBindings into the init binding callback
Added the necessary parameter names to the binding param list to access additional values.
I re-enabled the html.attr call. Notice that now, because the binding context is set to the actual item, the SetSelected method doesn't exist at that level anymore, so it is necessary to use $parent.SetSelected.
$(htmlDiv).attr("data-bind", "click: $parent.SetSelected")
Fixed the ko.applyBindingsToDescendants call. This method takes a binding context, which is created from the current binding context, and also takes the element to apply the binding to. You don't want to reapply the binding, which is why this whole thing needs to be in the init handler.
var childBindingContext = bindingContext.createChildContext(vFriends[i]);
ko.applyBindingsToDescendants(childBindingContext, colDiv);

Functional object basics. How to go beyond simple containers?

On the upside I'm kinda bright, on the downside I'm wracked with ADD. If I have a simple example, that fits with what I already understand, I get it. I hope someone here can help me get it.
I've got a page that, on an interval, polls a server, processes the data, stores it in an object, and displays it in a div. It is using global variables, and outputing to a div defined in my html. I have to get it into an object so I can create multiple instances, pointed at different servers, and managing their data seperately.
My code is basically structured like this...
HTML...
<div id="server_output" class="data_div"></div>
JavaScript...
// globals
var server_url = "http://some.net/address?client=Some+Client";
var data = new Object();
var since_record_id;
var interval_id;
// window onload
window.onload(){
getRecent();
interval_id = setInterval(function(){
pollForNew();
}, 300000);
}
function getRecent(){
var url = server_url + '&recent=20';
// do stuff that relies on globals
// and literal reference to "server_output" div.
}
function pollForNew(){
var url = server_url + '&since_record_id=' + since_record_id;
// again dealing with globals and "server_output".
}
How would I go about formatting that into an object with the globals defined as attributes, and member functions(?) Preferably one that builds its own output div on creation, and returns a reference to it. So I could do something like...
dataOne = new MyDataDiv('http://address/?client');
dataOne.style.left = "30px";
dataTwo = new MyDataDiv('http://different/?client');
dataTwo.style.left = "500px";
My code is actually much more convoluted than this, but I think if I could understand this, I could apply it to what I've already got. If there is anything I've asked for that just isn't possible please tell me. I intend to figure this out, and will. Just typing out the question has helped my ADD addled mind get a better handle on what I'm actually trying to do.
As always... Any help is help.
Thanks
Skip
UPDATE:
I've already got this...
$("body").prepend("<div>text</div>");
this.test = document.body.firstChild;
this.test.style.backgroundColor = "blue";
That's a div created in code, and a reference that can be returned. Stick it in a function, it works.
UPDATE AGAIN:
I've got draggable popups created and manipulated as objects with one prototype function. Here's the fiddle. That's my first fiddle! The popups are key to my project, and from what I've learned the data functionality will come easy.
This is pretty close:
// globals
var pairs = {
{ div : 'div1', url : 'http://some.net/address?client=Some+Client' } ,
{ div : 'div2', url : 'http://some.net/otheraddress?client=Some+Client' } ,
};
var since_record_id; //?? not sure what this is
var intervals = [];
// window onload
window.onload(){ // I don't think this is gonna work
for(var i; i<pairs.length; i++) {
getRecent(pairs[i]);
intervals.push(setInterval(function(){
pollForNew(map[i]);
}, 300000));
}
}
function getRecent(map){
var url = map.url + '&recent=20';
// do stuff here to retrieve the resource
var content = loadResoucrce(url); // must define this
var elt = document.getElementById(map.div);
elt.innerHTML = content;
}
function pollForNew(map){
var url = map.url + '&since_record_id=' + since_record_id;
var content = loadResoucrce(url); // returns an html fragment
var elt = document.getElementById(map.div);
elt.innerHTML = content;
}
and the html obviously needs two divs:
<div id='div1' class='data_div'></div>
<div id='div2' class='data_div'></div>
Your 'window.onload` - I don't think that's gonna work, but maybe you have it set up correctly and didn't want to bother putting in all the code.
About my suggested code - it defines an array in the global scope, an array of objects. Each object is a map, a dictionary if you like. These are the params for each div. It supplies the div id, and the url stub. If you have other params that vary according to div, put them in the map.
Then, call getRecent() once for each map object. Inside the function you can unwrap the map object and get at its parameters.
You also want to set up that interval within the loop, using the same parameterization. I myself would prefer to use setTimeout(), but that's just me.
You need to supply the loadResource() function that accepts a URL (string) and returns the HTML available at that URL.
This solves the problem of modularity, but it is not "an object" or class-based approach to the problem. I'm not sure why you'd want one with such a simple task. Here's a crack an an object that does what you want:
(function() {
var getRecent = function(url, div){
url = url + '&recent=20';
// do stuff here to retrieve the resource
var content = loadResoucrce(url); // must define this
var elt = document.getElementById(div);
elt.innerHTML = content;
}
var pollForNew = function(url, div){
url = url + '&since_record_id=' + since_record_id;
var content = loadResoucrce(url); // returns an html fragment
var elt = document.getElementById(div);
elt.innerHTML = content;
}
UpdatingDataDiv = function(map) {
if (! (this instanceof arguments.callee) ) {
var error = new Error("you must use new to instantiate this class");
error.source = "UpdatingDataDiv";
throw error;
}
this.url = map.url;
this.div = map.div;
this.interval = map.interval || 30000; // default 30s
var self = this;
getRecent(this.url, this.div);
this.intervalId = setInterval(function(){
pollForNew(self.url, self.div);
}, this.interval);
};
UpdatingDataDiv.prototype.cancel = function() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
})();
var d1= new UpdatingDataDiv('div1','http://some.net/address?client=Some+Client');
var d2= new UpdatingDataDiv('div2','http://some.net/otheraddress?client=Some+Client');
...
d1.cancel();
But there's not a lot you can do with d1 and d2. You can invoke cancel() to stop the updating. I guess you could add more functions to extend its capability.
OK, figured out what I needed. It's pretty straight forward.
First off disregard window.onload, the object is defined as a function and when you instantiate a new object it runs the function. Do your setup in the function.
Second, for global variables that you wish to make local to your object, simply define them as this.variable_name; within the object. Those variables are visible throughout the object, and its member functions.
Third, define your member functions as object.prototype.function = function(){};
Fourth, for my case, the object function should return this; This allows regular program flow to examine the variables of the object using dot notation.
This is the answer I was looking for. It takes my non-functional example code, and repackages it as an object...
function ServerObject(url){
// global to the object
this.server_url = url;
this.data = new Object();
this.since_record_id;
this.interval_id;
// do the onload functions
this.getRecent();
this.interval_id = setInterval(function(){
this.pollForNew();
}, 300000);
// do other stuff to setup the object
return this;
}
// define the getRecent function
ServerObject.prototype.getRecent = function(){
// do getRecent(); stuff
// reference object variables as this.variable;
}
// same for pollForNew();
ServerObject.prototype.pollForNew = function(){
// do pollForNew(); stuff here.
// reference object variables as this.variable;
}
Then in your program flow you do something like...
var server = new ServerObject("http://some.net/address");
server.variable = newValue; // access object variables
I mentioned the ADD in the first post. I'm smart enough to know how complex objects can be, and when I look for examples and explanations they expose certain layers of those complexities that cause my mind to just swim. It is difficult to drill down to the simple rules that get you started on the ground floor. What's the scope of 'this'? Sure I'll figure that out someday, but the simple truth is, you gotta reference 'this'.
Thanks
I wish I had more to offer.
Skip

Categories

Resources