Backbone: Pattern for rendering and re-rendering subscriber views in a correct order - oop

So basically I've been toying with this pattern of pubsub with subviews re-rendering when called by parent 'controller' view (sorry if that's confusing). If the subviews are based on a fetch of a collection or model (not shown below), sometimes they aren't rendered in the correct order I need them too, ie if SubView1 is a small nav for Subview2, I don't want it below SubView2.
I figure there has to be a pattern for such a common problem. Lemme know if this doesn't make sense and I will clarify. But the basic situation I'm dealing with is below.
markup:
<div id="main-container">
<div class="inner-container"></div>
</div>
js:
var ToggleNavView = Backbone.View.extend({
//let's say this template has two links
template: Handbars.compile(linkstmpl),
el: $('#main-container'),
events: {
"click a": "toggleViews"
}
initialize: function(){
_.bindAll(this, 'render', 'toggleViews');
// whoa, nice looking event aggregator http://bit.ly/p3nTe6
this.vent = _.extend({}, Backbone.Events);
this.render();
},
render: function(){
$(this.el).append(this.tmpl);
// suppose subviews below are declared as modules above with, say, requirejs
var sub1 = new SubView1({ vent: this.vent }),
sub2 = new SubView2({ vent: this.vent });
},
toggleViews: function(e){
e.preventDefault();
// get name of section or view you're toggling to
var section = $(e.currentTarget).data('section');
// publish events to subscribers
this.vent.trigger('toggleInboxViews', this, section);
},
});
var SubView1 = Backbone.View.Extend({
template: Handlebars.compile(tmpl1),
initialize: function(ops){
_.bindAll(this, 'render', 'removeOrRerender');
this.vent = ops.vent || null;
this.render()
},
render: function(){
$(this.el).append(this.template()).appendTo($(".inner-container"))
},
removeOrRerender: function(obj, section){
if( section == 'my-section'){
this.render();
} else if( section == 'other-section' ) {
$(this.el).fadeOut();
}
},
})
// another subview with same functionality etc...
// init view
new ToggleNavView();

If you need your sub-views to show up in specific places then the parent view should define that structure and the sub-views should be told where to render themselves. Then it won't matter what order things are draw in as the overall structure doesn't change.
For example, if you want one sub-view to appear at the top and the other below it, the main view should look like this:
<div id="main-view">
<div id="sub1"></div>
<div id="sub2"></div>
</div>
then the main view would render the sub-views with something like this:
var sub1 = new SubView1({ el: this.$el.find('#sub1'), vent: this.vent }),
var sub2 = new SubView2({ el: this.$el.find('#sub2'), vent: this.vent });
By specifying the el for the sub-views, their location on the page is no longer their problem and they won't shift positions if they're rendered in a different order. A happy side effect of this structure is that the sub-views are only concerned with themselves and are nicely self-contained; the parent view just needs to put the pieces in the right place by structuring its template properly and everything just works.
Here's a simple demo that might clarify the structure: http://jsfiddle.net/ambiguous/9u3S5/

Related

How to change contents of a virtual dom element in Mithril?

How do I access a virtual dom element to change its contents using Mithril? I am new to Mithril and still trying to figure things out. For example, I want to access the third div with id "three" and change it's contents to "Blue Jays" without touching any of the other div's.
Thanks.
<div id='main'>
<div id='one'>Yankees</div><br>
<div id='two'>Red Sox</div><br>
<div id='three'>Orioles</div>
</div>
In mithril, like in react/vue/angular, you dont act on the actual DOM directly. Instead, you define the outcome that you want, so for example, to render the DOM tree that you posted you would do something like this:
var my_view = {
view: vnode => m('div#main', [
m('div#one', 'Yankees'),
m('div#two', 'Red Sox'),
m('div#three', 'Orioles')
])
}
m.mount(root, my_view)
<script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/2.0.4/mithril.js"></script>
<div id="root"></div>
the m(...) functions inside the array have a string as their second argument, that makes the output static, but we can change that to a variable:
var my_view = {
oninit: vnode => vnode.state.fave_team = 'Orioles',
view: vnode => m('div#main', [
m('div#one', 'Yankees'),
m('div#two', 'Red Sox'),
m('div#three', vnode.state.fave_team)
])
}
m.mount(root, my_view)
<script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/2.0.4/mithril.js"></script>
<div id="root">
</div>
In this case I used the state property of the vnode argument, but you can also use a third party state manager like flux or any other.
Now that we have it as a variable, it will show the current value on every call m.redraw(), most of the times we dont have to do this call ourselves, for example:
var my_view = {
oninit: vnode => {
vnode.state.fave_team = 'Orioles'
},
view: vnode => m('div#main', [
m('div#one', 'Yankees'),
m('div#two', 'Red Sox'),
m('div#three', vnode.state.fave_team),
m('button', { onclick: () => vnode.state.fave_team = 'Dodgers' }, 'Change')
])
}
m.mount(root, my_view)
<script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/2.0.4/mithril.js"></script>
<div id="root"></div>
And thats it, any dynamic content in your DOM elements you set it as a variable/property in an object.
One of the beautiful things about mithril is that it doesnt force you to do things one specific way, so if you really want to work on the actual DOM node, there are lifecycle events that you can attach to any virtual node ("vnode")
You can easily capture the HTMLElement (i.e., HTMLInputElement) with the Mithril Lifecycle event of oncreate(). This is an actual example from my code (in TypeScript) where I need to hook up a few event listneres after the canvas element was created and its underlying DOM is available to me at "raw" HTML level. Once you get a hold of dom, then I manipulate that element directly. Many people think that why not use oninit(), but oninit() is before the generation of dom, so you will not get the element back at that stage.
Now, if you just do that, you will likely be posting another question - "Why the browser views not updating?" And that's because you do have to manually do a m.redraw() in your event handlers. Otherwise Mithril would not know when the view diffs to be computed.
const canvas = m(`.row[tabIndex=${my.tabIndex}]`, {
oncreate: (element: VnodeDOM<any, any>) => {
const dom = element.dom;
dom.addEventListener("wheel", my.eventWheel, false);
dom.addEventListener("keydown", my.eventKeyDown, false);
}
},

Vue.js - Highmaps - Redraw map on series change

I have a highmaps 'chart' and the only thing that I want is to redraw the whole map inside an external function. Let me explain better. The map draws itself immediatly when the page loads up but I fetch some data from an external service and set it to a variable. Then I would like to just redraw the chart so that the new data appears in the map itself. Below is my code.
<template>
<div>
<highmaps :options="chartOptions"></highmaps>
</div>
</template>
<script>
import axios from 'axios';
import HighCharts from 'vue-highcharts';
import json from '../map.json'
let regions = [];
export default {
data: function () {
return {
chartOptions: {
chart: {
map: json, // The map data is taken from the .json file imported above
},
map: {
/* hc-a2 is the specific code used, you can find all codes in the map.json file */
joinBy: ['hc-key', 'code'],
allAreas: false,
tooltip: {
headerFormat: '',
pointFormat: '{point.name}: <b>{series.name}</b>'
},
series: [
{
borderColor: '#a0451c',
cursor: 'pointer',
name: 'ERROR',
color: "red",
data: regions.map(function (code) {
return {code: code};
}),
}
],
}
},
created: function(){
let app = this;
/* Ajax call to get all parameters from database */
axios.get('http://localhost:8080/devices')
.then(function (response) {
region.push(response.parameter)
/* I would like to redraw the chart right here */
}).catch(function (error){
console.error("Download Devices ERROR: " + error);
})
}
}
</script>
As you can see I import my map and the regions variable is set to an empty array. Doing this results in the map having only the borders and no region is colored in red. After that there is the created:function() function that is used to make the ajax call and retrieve data. After that I just save the data pushing it into the array and then obviously nothing happens but I would like to redraw the map so that the newly imported data will be shown. Down here is the image of what I would like to create.
If you have any idea on how to implement a thing like this or just want to suggest a better way of handling the problem, please comment.
Thanks in advance for the help. Cheers!
After a few days without any answer I found some marginal help online and came to a pretty satisfying conclusion on this problem so I hope it can help someone else.
So the first thing I did was to understand how created and mounted were different in Vue.js. I used the keyword created at first when working on this project. Because of that, inside this function, I placed my ajax call that gave me data which I then loaded inside the 'chart' by using the .addSeries method of the chart itself.
To reference the chart itself I used this: let chart: this.$refs.highcharts.chart. This searches for the field refs in any of your components/html elements and links it to the variable. So in the html there was something like this:
<template>
<div>
<highmaps :options="chartOptions" ref="highcharts"></highmaps>
</div>
</template>
The real problem was that the chart didn't even start rendering while all this process was going on so I changed the created keyword with mounted which means that it executes all the code when all of the components are correctly mounted and so my chart would be already rendered.
To give you (maybe) a better idea of what I am talking about I will post some code down below
mounted: function(){
let errorRegions = [];
let chart = this.$refs.highcharts.chart;
axios.get('localhost:8080/foo').then(function(response)
{
/* Code to work on data */
response.forEach(function(device){
errorRegions.push(device);
}
chart.addSeries({
name: "ERROR",
color: "red",
data: errorRegions
}
/* ...Some more code... */
})
}
And this is the result (have been adding some more series in the same exact manner)
Really hoping I have been of help to someone else. Cheers!

vue-router view caching / not resetting data

Im working on a car sales website and using vue-router.
I have an index page with a list of all cars for sale, and then when clicked they link to the single view of that specific vehicle.
I have a large 'header' image on the single view page and have it inside a container with a fixed height so that when the page loads there is not jumping in page height.
When going to this single view, I do an API call to get the vehicle data and then wish to fade in the heading image.
To do this:
<div class="singleVehicle__mainImage">
<span :style="styles" :class="{'imageLoaded' : mainImageLoaded }" v-if="vehicle"></span>
</div>
export default {
data() {
return {
vehicle: null,
styles: {
backgroundImage: null
},
mainImageLoaded: null
}
},
created() {
this.getVehicle().then(() => {
this.mainImageBackground();
});
},
methods: {
mainImageBackground() {
var source = "IMAGE SOURCE URL";
this.styles.backgroundImage = "url("+source+")";
var $this = this;
var img = new Image();
img.onload = function() {
$this.mainImageLoaded = true;
}
img.src = source;
if (img.complete) img.onload();
}
}
}
By default, the span inside the image wrapper has a 0 opacity and then that is transitioned to 1 when the .imageLoaded class is added.
This works fine, but only the first time each vehicle loaded. The image waits till it loads and then fades in. Everyother time afterwards the image simply pops in when it loads almost like the imageLoaded class is not being reset / the data is not being reset when leaving the view.
When clearing browser cache, it works again but once for each vehicle view.
This is probably due to your v-if="vehicle". The vehicle call is possibly taking longer and so the span is not showing until after the class is added or some timing issue related to that.

How to Lazy load mvc4 webgrid rows using knockout.js ?

I have a web grid with large number of rows and I am not interested in paging the grid. I need to view only a particular number of rows initially. Then while scrolling I need to view rows one after the other. I have read it somewhere that it is possible with knockout.js. Do anyone have a sample code to share? Am working with MVC 4 Razor.
I implemented similar control. It was tree view with button "Load more".
A lot of items in observable array might slow down your app, especially when you are showing them, because it's a lot of DOM operations.
So, all my data pushes into ordinary array on page load. For data to be shown I have KO observable array. I am pushing more data into an observable array when I need to show it.
Here is basic example:
JavaScript:
$(function () {
$.get("URL TO GET DATA FROM", function (data) {
// data = [{name: "Andrei"}, {name: "James"}, {name: "Bill"}]
var page = new PageModel(data);
ko.applyBindings(page);
});
});
function PageModel(data) {
self = this;
//Show items from this array on the page
self.itemsToShow = ko.computed(function () {
return self.allItems.slice(0, self.numberToShow);
});
self.numberToShow = 10;
self.allItems = data;
self.showMore = function () {
self.numberToShow += 10;
}
}
HTML Template:
<div data-bind="foreach: itemsToShow">
<span data-bind="text: name"></span>
</div>
If you need to show more items, you can just call page.showMore();

Dojo/Dijit TitlePane

How do you make a titlePane's height dynamic so that if content is added to the pane after the page has loaded the TitlePane will expand?
It looks like the rich content editor being an iframe that is loaded asynchronously confuses the initial layout.
As #missingno mentioned, the resize function is what you want to look at.
If you execute the following function on your page, you can see that it does correctly resize everything:
//iterate through all widgets
dijit.registry.forEach(function(widget){
//if widget has a resize function, call it
if(widget.resize){
widget.resize()
}
});
The above function iterates through all widgets and resizes all of them. This is probably unneccessary. I think you would only need to call it on each of your layout-related widgets, after the dijit.Editor is initialized.
The easiest way to do this on the actual page would probably to add it to your addOnLoad function. For exampe:
dojo.addOnLoad(function() {
dijit.byId("ContentLetterTemplate").set("href","index2.html");
//perform resize on widgets after they are created and parsed.
dijit.registry.forEach(function(widget){
//if widget has a resize function, call it
if(widget.resize){
widget.resize()
}
});
});
EDIT: Another possible fix to the problem is setting the doLayout property on your Content Panes to false. By default all ContentPane's (including subclasses such as TitlePane and dojox.layout.ContentPane) have this property set to true. This means that the size of the ContentPane is predetermined and static. By setting the doLayout property to false, the size of the ContentPanes will grow organically as the content becomes larger or smaller.
Layout widgets have a .resize() method that you can call to trigger a recalculation. Most of the time you don't need to call it yourself (as shown in the examples in the comments) but in some situations you have no choice.
I've made an example how to load data after the pane is open and build content of pane.
What bothers me is after creating grid, I have to first put it into DOM, and after that into title pane, otherwise title pane won't get proper height. There should be cleaner way to do this.
Check it out: http://jsfiddle.net/keemor/T46tt/2/
dojo.require("dijit.TitlePane");
dojo.require("dojo.store.Memory");
dojo.require("dojo.data.ObjectStore");
dojo.require("dojox.grid.DataGrid");
dojo.ready(function() {
var pane = new dijit.TitlePane({
title: 'Dynamic title pane',
open: false,
toggle: function() {
var self = this;
self.inherited('toggle', arguments);
self._setContent(self.onDownloadStart(), true);
if (!self.open) {
return;
}
var xhr = dojo.xhrGet({
url: '/echo/json/',
load: function(r) {
var someData = [{
id: 1,
name: "One"},
{
id: 2,
name: "Two"}];
var store = dojo.data.ObjectStore({
objectStore: new dojo.store.Memory({
data: someData
})
});
var grid = new dojox.grid.DataGrid({
store: store,
structure: [{
name: "Name",
field: "name",
width: "200px"}],
autoHeight: true
});
//After inserting grid anywhere on page it gets height
//Without this line title pane doesn't resize after inserting grid
dojo.place(grid.domNode, dojo.body());
grid.startup();
self.set('content', grid.domNode);
}
});
}
});
dojo.place(pane.domNode, dojo.body());
pane.toggle();
});​
My solution is to move innerWidget.startup() into the after advice to "toggle".
titlePane.aspect = aspect.after(titlePane, 'toggle', function () {
if (titlePane.open) {
titlePane.grid.startup();
titlePane.aspect.remove();
}
});
See the dojo/aspect reference documentation for more information.