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

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.

Related

Knockout SPA Ajax loaded templates

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

Kendo UI droppable drop event not firing

I have a simple application that binds to a view model using Knockout JS. It uses a foreach loop that fires the Knockout afterAdd event when a new item is added to the view model. The result is supposed to be a Kendo draggable that can be dropped on a target. For some reason I can't get the drop event on the target to fire.
JSFiddle
<button data-bind="click: $root.add">Add</button>
Drop target
var ViewModel = function () {
this.operations = ko.observableArray([]);
this.add = function () {
this.operations.push("drag");
}.bind(this);
this.bind = function () {
$(".draggable").kendoDraggable({
hint: function (e) {
$("#console").append("<li>firing hint</li>");
return e.clone();
},
});
$(".droptarget").kendoDropTarget({
drop: function (e) {
$("#console").append("<li>firing drop</li>");
}
});
};
};
ko.applyBindings(new ViewModel());
The problem is that you're instantiating the KendoDropTarget widget multiple times. If I click the Add button in your example kendoDropTarget() is invoked three times. If I add a guard against this (see http://jsfiddle.net/tj_vantoll/rk6qwsy4/1/) the drop event works as expected.

Using durandal with jaydata and kendoui

I created a new VS2012 project using the hottowel template, which in return uses durandal, knockout and breeze.
I want to use jaydata instead of breeze and for the ui layer I want to use the excellent asKendoDataSource() functionality to power a kendoui grid.
I followed all the instructions to make kendoui work well with durandal. This is fine.
I have a model in which I get the jaydata entities and run asKendoDataSource() on it. My view is an MVVM declared kendoui grid with its source property set to the viewmodel's property that contains a reference to the asKendoDataSource().
In the knockout world the viewModel property would be an empty entities = ko.observableArray() which would then would be initialized by using entities(values) when the data service returns.
I need to mimic this such that I have a viewModel property that is an empty kendo datasource which then is initialized by the asKendoDataSource() conversion when the data comes back from jaydata. This way the mvvm kendo grid is bound initially to the empty datasource and then receives its items when the asKendoDataSource() is called.
This is all because the model - viewModel binding in durandal is asynchronous and there needs to be a placeholder property in the viewModel from the very beginning, which then, after the viewModel's activate() method promise is resolved, gets updated with the bound data and in return powers the DOM that the viewModel is bound to.
I can't figure out how to mimic the knockoutjs practice of an empty observable array which is bound to the dom and then (the same exact reference) gets initialized and populates the dom. There seems to be no way to create an empty kendo datasource which then is re-initialized by the asKendoDataSource() method. Reassigning the viewModel property to the new data source doesn't work because the kendo grid is bound to the original reference.
This is my airport 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>
This is my datacontext:
define([
'durandal/system',
'services/logger'],
function (system, logger) {
var getAirports = function (airportsObservable) {
$data.Entity.extend("Airport", {
Id: { type: "int", key: true, computed: true },
Abbrev: { type: String, required: true, maxLength: 200 },
Name: { type: String, required: true, maxLength: 512 }
});
$data.EntityContext.extend("JumpSeatDatabase", {
Airports: { type: $data.EntitySet, elementType: Airport }
});
var airportDB = new AirportDatabase('http://localhost:2663/odata');
var deferred = Q.defer();
airportDB.onReady(function () {
deferred.resolve(airportDB.Airports);
});
return deferred.promise;
}
var datacontext = {
getAirports: getAirports
};
return datacontext;
function log(msg, data, showToast) {
logger.log(msg, data, system.getModuleId(datacontext), showToast);
}
function logError(msg, error) {
logger.logError(msg, error, system.getModuleId(datacontext), true);
}
//#endregion
});
This is my airport viewmodel:
define(['services/datacontext', 'durandal/plugins/router'],
function (datacontext, router) {
var airports = null;// = kendo.data.ObservableArray([]);
var activate = function () {
var airportRes = datacontext.getAirports();
return airportRes.then(function (airp) {
vm.airports = airp.asKendoDataSource();
});
};
var deactivate = function() {
//airports([]);
};
var viewAttached = function (view) {
//using this type of reach in to the viewModel is considered bad practice in durandal
//$('#airportGrid').kendoGrid({
// dataSource: airports.asKendoDataSource({ pageSize: 10 }),
// filterable: true,
// sortable: true,
// pageable: true,
// height: 500,
// columns: ['Id', 'Abbrev', 'Name']
//});
//kendo.init($("#container"));
kendo.bind(view, vm);//this should eventually go away the recommended ViewModelBinder code in main.js is not firing for me
};
var vm = {
activate: activate,
deactivate: deactivate,
airports: airports,
title: 'Airports',
viewAttached: viewAttached
};
return vm;
});
One last issue that I am seeing:
It seems to me that an MVVM declared kendoui grid, bound to the view model through data-kendo-bind={source: airports)" where airports is a property of the viewmodel that was created through entities.asKendoDataSource() does not work. Somehow the grid does not show the data. Is there something extra that needs to be done?
Thanks
My best guess is that this is a timing issue, where the Grid is binding to vm.airports while it is still null, then vm.airports = airp.asKendoDataSource(); is called after it is already bound? Perhaps try something like:
return airportRes.then(function (airp) {
vm.airports.data(airp.asKendoDataSource().data());
});

requirejs on a windows phone 7

So I asked a question earlier about windows phone 7 with backbone and jquery and require.
I carried on investigating this and stripped it down to the bare minimum
and index page that just has
<script data-main="js/main" src="js/vendor/require/requireNew.js"></script>
and then a main.js that just has one path to jQuery
require.config({
//path mappings for module names not found directly under baseUrl
paths: {
jquery: 'vendor/jqm/jquery_1.7_min'
}
});
alert('why');
$(document).ready(function() {
alert('DOM IS READY ');
});
in windows 7 it will show the alert why - but not DOM is here...
it will do this on every other browser including ie7!!
Can anyone help?
Not sure if you are using Phonegap or not, if not you should be (or an equivalent framework).
If you follow the instructions here enter link description here
You will be able to build a default phonegap WP7 application when you have that take a look at the generated index.js
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// `load`, `deviceready`, `offline`, and `online`.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of `this` is the event. In order to call the `receivedEvent`
// function, we must explicity call `app.receivedEvent(...);`
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
It's a bit more complicated on mobile devices as you first must wait for the "device ready" event before you can get a "dom ready" event

Backbone click event fires events for all collection rather than model

Can't figure out what's wrong. When I click on a model title, it fetches all models in collection at once rather than fetch one model. If I move this event from logView to logsView it works properly but doesn't have access to model, well I can find this model using index or ant other model's ID but don't think this is a nice way.
var Log = Backbone.Model.extend({});
window.LogsList = Backbone.Collection.extend({
model:Log,
url:function (tag) {
this.url = '/logs/' + tag;
return this;
}
});
window.colList = new LogsList();
window.logView = Backbone.View.extend({
el:$('.accordion'),
template:_.template($('#log').html()),
initialize:function () {
this.model.bind('add', this.render, this);
},
events:{
"click .accordion-toggle" :"getLogBody"
},
render:function () {
return this.template(this.model.toJSON());
},
getLogBody:function () {
this.model.fetch();
}
});
window.LogsView = Backbone.View.extend({
el:$("#content"),
initialize:function (options) {
colList.bind('reset', this.addAll, this);
colList.url(options.data).fetch();
},
addOne:function (model) {
var view = new logView({model:model});
$("#accordion").append(view.render());
},
addAll:function () {
colList.each(this.addOne);
}
});
window.listView = new LogsView({data:"Visa_Cl"});
The problem is caused by your el in the LogView: el:$('.accordion')
Backbone's view events are scope to the view's el. In this case, you've specified the view's el as ALL HTML elements with a class of "accordion". Therefore, when you click on any of your HTML elements with this class, the code runs for all of them, which is why you are seeing this behavior.
This article will show you a few options for doing what you want, correctly:
Backbone.js: Getting The Model For A Clicked Element
I would also recommend reading this one, to better understand the use of el in Backbone, and a few of the tricks and traps of it:
Backbone.js: Object Literals, Views Events, jQuery, and el

Resources