Knockout SPA Ajax loaded templates - ajax

I am lost between the possibilities offered to handle this case: let's say we have the following constraints:
Knockout
SPA with Sammy.js - Html loaded via Ajax
My page:
+-------------------------------+
| #navigation |
+---------+---------------------+
| #sidebar| #content |
| | |
| | |
| | |
+---------+---------------------+
Currently, I have one appViewModel which handle the data-bind for all the shared elements of my website: #navigation and #sidebar. This appViewModel has observable used on every pages of my website.
appViewModel = function () {
var self = this;
self.sidebarItemArray = ko.observableArray([x, y, z]);
self.currentRoute = ko.observable();
...
self.updateView = function(path, currentRoute) {
return $.get(path, function( data ) {
var $data = $(data);
// Updates #content, TITLE and update the currentRoute observable.
$( '#content' ).replaceWith($data.find('#content'));
document.title = $data.filter('title').text();
self.currentRoute(currentRoute);
}, 'html');
}
Sammy(function() {
this.get(':link'', function() {
self.updateView(this.path, this.params.link);
});
}).run();
}
ko.applyBindings(new appViewModel());
Now, let's say that #content is a piece of DOM loaded through an Ajax Call. Each time a user click a link inside #navigation or #sidebar, Sammy.js intercept it and then update #content. The problem is that the new DOM inside #content has data-bindings itself.
1) First, should I use the html data-bind on #content, replaceWith(as above) or the template binding with custom function to get the template?
(http://knockoutjs.com/documentation/template-binding.html#note-5-dynamically-choosing-which-template-is-used)? What is the best practice here?
2) Should Sammy necessary lives inside the appViewModel as in the documentation or elsewhere is just fine?
3) Once the updateView method is completed, how would you bind the new DOM? Like below? Isn't there a risk of rebinding some DOM because ko.applyBindings has already been called without second argument?
ko.applyBindings(new routeSpecificViewModel() , document.getElementById("content"));
I am thankful for your help.

One simple solution is to make the page's viewmodel an observable, and load it ondemand. Use a variable to record if ko.applyBindings has been called. Example from the knockout-spa framework:
/*! knockout-spa (https://github.com/onlyurei/knockout-spa) * Copyright 2015-2016 Cheng Fan * MIT Licensed (https://raw.githubusercontent.com/onlyurei/knockout-spa/master/LICENSE) */
define(['app/shared/root-bindings', 'framework/page-disposer', 'ko', 'sugar'], function (
RootBindings, PageDisposer, ko) {
var initialRun = true;
var Page = {
init: function (name, data, controller, path) {
Page.loading(false);
name = name.toLowerCase();
if ((Page.page().name == name) && (Page.page().data == data)) { // if the requested page is the same page, immediately call controller without going further
if (controller) {
controller(data);
}
document.title = Page.title();
if (Page.initExtra) {
Page.initExtra(name, data, controller);
}
return data;
}
var autoDispose = (Page.page().data.dispose && Page.page().data.dispose(Page)) || true; // if the requested page is not the same page, dispose current page first before swap to the new page
if (autoDispose !== false) {
// auto-dispose page's exposed observables and primitive properties to initial values. if not desired, return
// false in dispose function to suppress auto-disposal for all public properties of the page, or make the
// particular properties private
PageDisposer.dispose(Page.page().data);
}
PageDisposer.init(data); //store initial observable and primitive properties values of the page
var initialized = (data.init && data.init(Page)) || true; // init view model and call controller (optional) before template is swapped-in
if (initialized === false) {
return false; // stop initialization if page's init function return false (access control, etc.)
}
if (controller) {
controller(data);
}
Page.pageClass([name, ('ontouchstart' in document.documentElement) ? 'touch' : 'no-touch'].join(' '));
Page.page({
name: name,
data: data,
path: path
}); // to test if template finished rendering, use afterRender binding in the template binding
document.title = Page.title();
if (Page.initExtra) {
Page.initExtra(name, data, controller); // useful for common init tasks for all pages such as anaylitics page view tracking, can be set in RootBindings
}
if (initialRun) {
ko.applyBindings(Page, document.getElementsByTagName('html')[0]); // apply binding at root node to be able to bind to anywhere
initialRun = false;
}
return data;
},
page: ko.observable({
name: '', // name of the page - auto-set by the framework, no need to worry
data: {
init: function () {}, // preparation before the page's template is rendered, such as checking access control, init/instantiate modules used by the page, etc.
dispose: function () {} // properly dispose the page to prevent memory leaks and UI leftovers (important for SPA since page doesn't refresh between page views) - remove DOM element event listeners, dispose knockout manual subscriptions, etc.
}
}),
pageClass: ko.observable(''),
loading: ko.observable(false),
title: function () {
return Page.page().name.titleize(); // override in RootBindings as needed
}
};
Object.merge(Page, RootBindings); // additional root bindings as needed by the app
return Page;
});
A mini but full-fledged SPA framework built on top of Knockout, Require, Director, jQuery, Sugar.
https://github.com/onlyurei/knockout-spa
Live Demo: https://knockout-spa.mybluemix.net

Related

Working with PageObjects inside of other PageObjects using nightwatch

I'm using the last version of nightwatch I had some issues when a Page Object can have another Page Object as 'field'.
I develop PageObjects for the header, footer and for html elements related for a login action as below:
menu.js
var commands = {
// commands for the menu
}
module.exports = {
elements: {
// menu html elements selectors, i.e.
someElementInHeader : '.cssSelector'
},
commands: [commands]
}
footer.js
module.exports = {
elements: {
// footer html elements selectors
}
}
But I need to embed these two Page Objects in a third Page Object, as example, a login page that contains the same menu and the same footer.
loginPage.js
// import the menu and footer js some way
module.exports = {
url: function() {
// get the url from configuration
return this.api....
}
// should have the elements from menu and footer, along with this page elements
elements: { ... },
// should contain the commands from menu and some commands from the page itself
commands: [{ ... }]
}
I tried to use a constructor for the loginPage Page Object, but it's not working.
Now I'm using this approach for the loginPage.js, but I don't think that is the better one:
// the header.js is a Page Object for nightwatch because it's located on the page objects path
const header = require('../common/header.js');
/**
* commands related to this page
*/
let _commands = [];
// add comands from dependencies
_commands = _commands.concat(header.commands);
/**
* elements related to this page
*/
let _elements = {};
// add elements from dependencies
Object.assign(_elements, header.elements);
/**
* page object configuration
*/
module.exports = {
url: function() {
return this.api.globals.baseUrl + '/login';
},
elements: _elements,
commands: _commands
};
And this is an example for tests (simplelogin.spec.js):
var customer = null;
module.exports = {
// set tests parameters
before : function (browser) {
var loginPage = browser.page.pages.loginPage();
browser
.useCss()
.pause(1000);
customer = loginPage.navigate();
},
// check for a basic element in header is present because it's needed
'a basic element should be present' : function (browser) {
customer.expect.element('#someElementInHeader').to.be.present;
},
after : function (browser) {
browser.end();
}
}
Even though I'm reusing the code for the the header, I didn't like the design and the readibility of the code for the loginPage.js... also, if a lot of page objects is needed in this page object for further testing, it will became very verbose.
Any ideas?

css manipulation happens before rendering so it wont be effective

I am using react and redux for my current project. I have a button and whenever user click on that it first call the server and load some data and then manipulate the css of some dom elements.
Here is my code:
var allClickableStories = document.getElementById("dummyClickStory" + this.props.story.id);
$(allClickableStories).click(function () {
if (!$("#" + this.id + " .expansion-handler").hasClass("show")) {
var storyId = this.id.replace("dummyClickStory", "");
thisRef.props.getStoryDetail(storyId, thisRef.props.channel);
$("#" + this.id + " .expansion-handler").addClass("show");
$("#" + this.id + " .cutline").addClass("show");
}
});
Also it is noteworthy that the above code in in componentDidMount to make sure that first render happens. However this does not guarantee that ajax call ( thisRef.props.getStoryDetail) happens before css manipulation and this is exactly where I am stuck at. what is happenning is the ajax call is sent and then css manipulation fires however ajax call may return after and render will happend and hide the manipulated dom element again.An easy way to fix it is to set asynch to false in jquery ajax call but not a good solution. So how can I can make sure that first ajax call finishes and render happens then css manipulation takes place?
Also just for more info here are my code in Action and reducer:
Action:
export function getStoryDetail(storyId,channel){
return dispatch => {
$.ajax({
url: "http://localhost:3003/json5.txt",
dataType: 'json',
cache: false,
success: function(data) {
var storyDetatil=[];
for (var key in data) {
storyDetatil.push(data[key]);
}
var storyDetailObj={"storyArray":storyDetatil,"storyId":storyId, "channel":channel};
dispatch({
type: "STORY_EXPANSION",
payload: storyDetailObj
});
}.bind(this)
});
};
}
Reducer:
case "STORY_EXPANSION":
var tempStateExpansion = state.slice();
if (action.payload.storyId > -1 && state[0].channel !=undefined) {
for(var i=0;i<state.length;i++){
if(state[i].channel.toLowerCase()===action.payload.channel.toLowerCase()){
for(var j=0;j<state[i].storiesSnippet.length;j++){
if(action.payload.storyId===state[i].storiesSnippet[j].id){
tempStateExpansion[i].storiesSnippet[j]=action.payload.storyArray[0];
break;
}
}
break;
}
}
}
else{
tempStateExpansion[0].storiesSnippet[0]=action.payload.storyArray[0];
}
state=tempStateExpansion;
break;
In short, you can not do this with React. You are using jQuery to manipulate the DOM which is basically the opposite approach to React. React manipulates the DOM for you.
What you should do instead is to have a component (you could look at inline styles perhaps: https://facebook.github.io/react/docs/dom-elements.html) that will rerender based on an updated state.
App renders with whatever defaults and fires off ajax request.
Ajax response updates the redux store, which through connect and a mapStateToProps updates the props of a component that should change when the ajax request is fulfilled.
Component rerenders based on the new state. The render path has the new styles (possibly inline)
I would recommend running through the TODO List example with redux and React here: http://redux.js.org/docs/basics/UsageWithReact.html. Your Redux usage looks alright, it's the React that is problematic.
Here is an example of using a React component which would rerender based on a data property of the redux state. It assumes that you would have an application wide CSS that contains definitions for foo and bar CSS classes.
import React from 'react';
import { connect } from 'react-redux';
class Example extends React.Component {
render() {
const { data } = this.props;
// If data is present (render a div using CSS from class foo)
// and put the data in the div asuming it's a string
if (data) {
return <div className='foo'>{ data }</div>;
}
// If data is not present (render a div using CSS from class bar)
// Display No Content
return <div className='bar'>No Content</div>;
}
}
// Data is an object, but not required as initially it will be undefined
Example.propTypes = {
data: React.PropTypes.object
};
// Map redux state to react props
const mapStateToProps = state => ({
data: state.data
});
// Connect to redux store helper using our mapping function
export default connect(mapStateToProps)(Example);

KendoUI DataSource binding to MVVM grid in durandal (using hottowel template) doesn't seem to work

I am using Visual Studio 2012 Update 2 hottowel template with updated durandal and jquery nuget packages...
Here is my code:
Durandal main.js:
require.config({
paths: { "text": "durandal/amd/text" }
});
define(['durandal/app', 'durandal/viewLocator', 'durandal/viewModelBinder', 'durandal/system', 'durandal/plugins/router', 'services/logger'],
function (app, viewLocator, viewModelBinder, system, router, logger) {
// Enable debug message to show in the console
system.debug(true);
app.start().then(function () {
toastr.options.positionClass = 'toast-bottom-right';
toastr.options.backgroundpositionClass = 'toast-bottom-right';
router.handleInvalidRoute = function (route, params) {
logger.logError('No Route Found', route, 'main', true);
};
// When finding a viewmodel module, replace the viewmodel string
// with view to find it partner view.
router.useConvention();
viewLocator.useConvention();
// Adapt to touch devices
app.adaptToDevice();
kendo.ns = "kendo-";
viewModelBinder.beforeBind = function (obj, view) {
kendo.bind(view, obj.viewModel || obj);
};
//Show the app by setting the root view model for our application.
app.setRoot('viewmodels/shell', 'entrance');
});
});
Durandal viewmodel:
define(['services/datacontext', 'durandal/plugins/router'],
function (datacontext, router) {
var activate = function () {
//yes yes - I will separate this out to a datacontext - it is here for debugging simplicity
var service = $data.initService("https://open.jaystack.net/c72e6c4b-27ba-49bb-9321-e167ed03d00b/6494690e-1d5f-418d-adca-0ac515b7b742/api/mydatabase/");
//return promise as durandal seems to want...
return service.then(function (db) {
vm.set("airports", db.Airport.asKendoDataSource());
});
};
var deactivate = function () {
};
var viewAttached = function (view) {
//kendo.init($("#airportGrid"));
//kendo.bind(view, vm);
//kendo.bind($("#airportGrid"), vm);
};
var vm = new kendo.data.ObservableObject({
activate: activate,
deactivate: deactivate,
airports: [],
title: 'Airports',
viewAttached: viewAttached
});
return vm;
});
Durandal view:
<section>
<h2 class="page-title" data-bind="text: title"></h2>
<div id="airportGrid" data-kendo-role="grid" data-kendo-sortable="true" data-kendo-pageable="true" data-kendo-page-size="25" data-kendo-editable="true" data-kendo-columns='["id", "Abbrev", "Name"]' data-kendo-bind="source: airports"></div>
</section>
I see the call being made to jaystack in Chrome's network monitor:
https://open.jaystack.net/c72e6c4b-27ba-49bb-9321-e167ed03d00b/6494690e-1d5f-418d-adca-0ac515b7b742/api/mydatabase//Airport?$inlinecount=allpages&$top=25
And I see data coming back.
The kendoui grid is created nicely but there is no data in it (I think this means kendoui is happy and the MVVM bindings are being bound to, however the created kendoui grid doesn't seem to want to understand the kendoui datasource created from jaydata)
Without durandal this works just nicely as demonstrated in:
http://jsfiddle.net/t316/4n62B/29/
I have been trying and trying for 2 days now - can someone please help me out?
Thanks
TJ
Sounds like everything is working now after removing the parts that are only required by breeze.
Nevertheless I'd suggest restructuring the working dFiddle code slightly to ensure that a) vm is defined before setting vm.airports in activate and b) there's no need to create a dummy vm.airports kendo.data.DataSource() that gets overwritten in activate anyway.
define(function( ) {
var vm = new kendo.data.ObservableObject({
activate: activate,
deactivate: deactivate,
// airports: new kendo.data.DataSource(),
title: 'Airports',
viewAttached: viewAttached
});
return vm;
function activate () {
var service = $data.initService("https://open.jaystack.net/c72e6c4b-27ba-49bb-9321-e167ed03d00b/6494690e-1d5f-418d-adca-0ac515b7b742/api/mydatabase/");
return service.then(function( db ) {
vm.airports = db.Airport.asKendoDataSource();
});
}
function deactivate () {
}
function viewAttached ( view ) {
//kendo.init($("#airportGrid"));
//kendo.bind(view, vm);
//kendo.bind($("#airportGrid"), vm);
}
});
Which version on jQuery do you use? Try with 1.8.3 or 1.9 + Migration.
In Chrome switch the stop sign to purple (two clicks) to catch uncaught exceptions and see if there is any.

Is Backbone.js suitable for getting HTML from server?

As far as I can tell, Backbone.js view represents DOM element. I take it from existing DOM or create it on the fly in el attribute.
In my case, I want to take it from server with AJAX request because I'm using Django templates and don't want to rewrite everything to JavaScript templates.
So I define el function that performs AJAX request.
el: function() {
model.fetch().success(function(response) {
return response.template
})
}
Of course, it does NOT work because AJAX request is executed asynchronous.
This means that I don't have el attribute and events does NOT work neither. Can I fix it?
Maybe the Backbone.js framework isn't the right tool for my needs? The reason I want to use that was to have some structure for the code.
P.S. I'm new to Backbone.js.
Do your ajax request from another view, or directly after the page load using jquery directly, and after you've downloaded your template, THEN instantiate your backbone view class with the proper id/el or whatever (depending on where you stored your ajax fetched template). Depending on your use-case, this may or may not be a sensible approach.
Another, perhaps more typical approach, would be to set up your view with some placeholder element (saying "loading" or whatever), then fire off the ajax, and after the updated template has been retrieved, then update your view accordingly (replace the placeholder with the actual template you requested).
When/if you update your view with new/other DOM elements, you need to call the view's delegateEvents method to rebind your events to the new elements, see:
http://backbonejs.org/#View-delegateEvents
I came across a similar requirement. In my instance, I was running asp.net and wanted to pull my templates from user controls. The first thing I would recommend is looking into Marionette because it will save you from writing a lot of boiler plate code in Backbone. The next step is to override how your templates are loaded. In this case I created a function that uses Ajax to retrieve the HTML from the server. I found an example of this function where they were using it to pull down html pages so I did a little modification so I can make MVC type requests. I can't remember where I found the idea from; otherwise, I would give the link here.
function JackTemplateLoader(params) {
if (typeof params === 'undefined') params = {};
var TEMPLATE_DIR = params.dir || '';
var file_cache = {};
function get_filename(name) {
if (name.indexOf('-') > -1) name = name.substring(0, name.indexOf('-'));
return TEMPLATE_DIR + name;
}
this.get_template = function (name) {
var template;
var file = get_filename(name);
var file_content;
var result;
if (!(file_content = file_cache[name])) {
$.ajax({
url: file,
async: false,
success: function (data) {
file_content = data; // wrap top-level templates for selection
file_cache[name] = file_content;
}
});
}
//return file_content.find('#' + name).html();
return file_content;
}
this.clear_cache = function () {
template_cache = {};
};
}
The third step would be to override Marionette's method to load templates. I did this in the app.addInitializer method. Here I am initializing my template loader and setting it's directory to a route handler. So when I want to load a template, I just set the template: "templatename" in my view and Backbone will load the template from api/ApplicationScreens/templatename. I am also overriding my template compiling to use Handlebars because ASP.net is not impressed with the <%= %> syntax.
app.JackTemplateLoader = new JackTemplateLoader({ dir: "/api/ApplicationScreens/", ext: '' });
Backbone.Marionette.TemplateCache.prototype.loadTemplate = function (name) {
if (name == undefined) {
return "";
} else {
var template = app.JackTemplateLoader.get_template(name);
return template;
}
};
// compiling
Backbone.Marionette.TemplateCache.prototype.compileTemplate = function (rawTemplate) {
var compiled = Handlebars.compile(rawTemplate);
return compiled;
};
// rendering
Backbone.Marionette.Renderer.render = function (template, data) {
var template = Marionette.TemplateCache.get(template);
return template(data);
}
Hopefully this helps. I've been working on a large dynamic website and it is coming along very nicely. I am constantly being surprised by the overall functionality and flow of using Marionette and Backbone.js.

In jQuery, how can I create a custom event with a default?

The Event object in jQuery has this helpful preventDefault() method that prevents the default behaviour, obviously.
This is usually used to prevent click events from performing the browser default behaviour.
It seems like it would also be useful for custom events as well.
The task I'd like to achieve with this behaviour is a separate concern but I will explain it as an example for the behaviour I'm looking for:
I have a simple plugin that creates a popup out of a div. I found it on the internet.
$(selector).pop();
I have hacked it to close when you click on anything but a child of the popup, and to prevent default click behaviour on the clicked element.
function closeInactivePop() {
var foundAny = false;
jQ.each(function (i) {
var $this = $(this);
if ($this.hasClass('active') && ! $this.data('activePop')) {
$this.removeClass('active');
foundAny = true;
}
});
return foundAny;
}
$('body').click(function(){
// If we closed any, cancel the propagation. Otherwise let it be.
if (closeInactivePop()) {
$(document).trigger('jQuery.pop.menuClosed');
return false;
}
});
(Now that I paste it I realise I could have done this a bit better, but that notwithstanding).
Now I have added a new plugin that draws a colour picker inside the popup. Except the DOM that this colour picker creates is not inside the popup; it is only inside it visually. The DOM structure is separate.
In the aforementioned hack I would prefer to in fact fire another event, one whose default behaviour is to close the popup.
function closeInactivePop() {
var foundAny = false;
jQ.each(function (i) {
var $this = $(this);
if ($this.hasClass('active') && ! $this.data('activePop')) {
$(document).trigger('jQuery.pop.menuClosed');
$this.removeClass('active');
foundAny = true;
}
});
return foundAny;
}
$('*').click(function(e) {
var $this = $(this);
// This bit is pseudocode, where the Function is the default behaviour
// for this event.
// It is helpful that $this is actually the clicked element and not the body.
$this.trigger('jQuery.pop.menuBeforeClose', function() {
// if we run default behaviour, try to close the popup, or re-trigger the click.
if (!closeInactivePop()) {
$this.trigger(e);
}
});
});
Then I could later do
$('#colour-picker').bind('jQuery.pop.menuBeforeClose', function(e) {
e.preventDefault();
});
And this would prevent the closeInactivePopup default behaviour running when the target of the original click event was the colour picker or something inside it.
Can I do this somehow, even hackily?
I doubt that there is a native way to do that. However, you can either use "triggerHandler()" instead of "trigger()", which provides the ability to return values from the event handlers. Another relatively simple solution is to pass a custom "event" object that can be used to cancel the planned action:
function Action() {
var status = true;
this.cancel = function() { status = false; };
this.status = function() { return status; };
}
$('button').click(function() {
var action = new Action();
$(this).trigger('foo', [action]);
if (action.status()) {
// ... perform default action
}
});​
In the event handler:
$('*').bind('foo', function(event, action) {
action.cancel();
});

Resources