Is there any kind of wildcard operator in the Durandal observable plugin, to subscribe to a change in any property? - durandal

Is there any kind of wildcard operator in the Durandal observable plugin, as there is in (for example) JsObservable?
The Durandal observable documentation gives this example:
var observable = require('plugins/observable');
var viewModel:{
firstName:'',
lastName:''
};
observable(viewModel, 'firstName').subscribe(function(value){
console.log('First name changed.');
});
viewModel.firstName = 'Test';
What I'd like to do is use a wildcard to subscribe to any changed property on the target. Something like this:
observable(viewModel, '*').subscribe(function(property, value){
console.log(property + ' changed.');
});
I don't see anything in the API documentation, but wondered if there was anything undocumented, or if anyone has a workaround to implement this behaviour.

Unfortunately, there is no wildcard operator for this functionality.
But you can easily create wrapper module for this functionality.
Here is small example:
var observable = require('plugins/observable');
var wildcardObservable = function(obj, changeCallback){
for(var prop in obj){
observable(obj, prop).subscribe(changeCallback);
}
}
var changeCallback = function() {
console.log('property changed.');
}
Usage:
var viewModel:{
firstName:'',
lastName:''
};
wildcardObservable(viewModel, changeCallback);

With thanks to U10 for the start above, (and with reference to a few examples on the web) I came up with the following, which uses a closure to track all the necessary properties. It's a bit messy but it does what I need for now - hopefully it will be of use to someone.
var ChangeTracker = (function () {
function ChangeTracker() {
}
ChangeTracker.prototype._trackChange = function (prop, target) {
var type = typeof (target[prop]);
var value = target[prop];
_logger.log("_trackChange", { target: target, prop: prop, type: type, value: value }, "CT");
_obs(target, prop).subscribe(function (newValue) {
var obj = {
target: target,
prop: prop,
newValue: newValue,
oldValue: value
};
_logger.log(">>>>>>>>>>>>>>> CHANGE!", obj, "CT");
value = newValue;
});
};
ChangeTracker.prototype.TrackChanges = function (target) {
var _this = this;
for (var prop in target) {
if (target.hasOwnProperty(prop)) {
this._trackChange(prop, target);
}
var underlying = ko.utils.unwrapObservable(target[prop]);
if (underlying instanceof Array) {
ko.utils.arrayForEach(underlying, function (item) {
_this.TrackChanges(item);
});
} else if (typeof underlying === "object") {
this.TrackChanges(underlying);
}
}
}
};
return ChangeTracker;
})();

Related

ExtJS Callback Functions Example

I'm a newbie at ExtJs and I'm struggling to figure out how to use callback functions in ExtJs. The ExtJs version I'm using is 4.2.1
Basically I want to chain the execution of 2 functions:
func1: function() {
}
func2: function() {
}
so that func2() only starts executing after func1() completes.
From what I've read so far, I need to use callback function, but for the life of me I cannot get it.
Here Is my code:
filter: function (filters, value) {
if (Ext.isString(filters)) {
filters = {
property: filters,
value: value
};
}
var me = this,
decoded = me.decodeFilters(filters),
i = 0,
length = decoded.length;
for (; i < length; i++) {
me.filters.replace(decoded[i]);
}
Ext.Array.each(me.filters.items, function (filter) {
Ext.Object.each(me.tree.nodeHash, function (key, node) {
if (filter.filterFn) {
if (!filter.filterFn(node)) node.remove();
} else {
if (node.data[filter.property] != filter.value) node.remove();
}
});
});
me.hasFilter = true;
console.log(me);
},
clearFilter: function() {
var me = this;
me.filters.clear();
me.hasFilter = false;
me.load();
},
isFiltered: function() {
return this.hasFilter;
},
filterNavAdminSTByUserName: function (nameValue) {
this.clearFilter();
this.filter([{
property: 'userName',
value: nameValue
}]);
}
My problem is that this.filter() gets executed before this.clearFilter(); How do I force this.filter() to execute only after this.clearFilter() completes?
Thanks in advance!
After some soul searching I've finally figured out how callback functions work.
So here is the solution:
clearAndFilter: function (nameValue) {
var me = this;
me.filters.clear();
me.hasFilter = false;
me.load({
scope: me,
callback: function () {
// filter the store
me.filter('userName', nameValue);
}
});
},
filterNavAdminSTByUserName: function (nameValue) {
this.clearAndFilter(nameValue);
}
Feels good to answer to my first ever post here!

get is not defined when trying to extends JSONSerializer

I try to define my custom serializer by extending DS.JSONSerialzer.
I pick the serialize function without modifications but when i run Ember,i get this error:
ReferenceError: get is not defined
This is my code :
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = {};
if (options && options.includeId) {
var id = get(record, 'id');
if (id) {
json[get(this, 'primaryKey')] = id;
}
}
record.eachAttribute(function(key, attribute) {
this.serializeAttribute(record, json, key, attribute);
}, this);
record.eachRelationship(function(key, relationship) {
if (relationship.kind === 'belongsTo') {
this.serializeBelongsTo(record, json, relationship);
} else if (relationship.kind === 'hasMany') {
this.serializeHasMany(record, json, relationship);
}
}, this);
return json;
},
});
I didn't change any code. This is the original. Why get is suddenly undefined? It's imported in line 1 in the original file JSONSerialiser
Can you help me?
They have get defined in the scope when creating the serializer, but that doesn't extend outside of their scope into your files.
var get = Ember.get;
var isNone = Ember.isNone;
var map = Ember.ArrayPolyfills.map;
var merge = Ember.merge;
Either replace all of the get methods with Ember.get or define get to be Ember.get

knockout search issue Property 'model' of object #<Object> is not a function

how can i get it work ?
define(['plugins/router', 'knockout', 'services/logger', 'durandal/app', 'mapping', 'services/routeconfig', 'services/dataBindingHandlers'], function (router, ko, logger, app, mapping, routeconfig, dataBindingHandlers) {
//#region Internal Methods
function activate() {
logger.log('Übersicht View Activated', null, 'newSearch', true);
return true;
}
//#endregion
//==jquery=================================================
function attached() {
}//-->end of attached()
var url = "https://www.googleapis.com/books/v1/volumes?q=the+Cat+In+The+Hat", path = $.getJSON(url);
path.then(function (data) {
console.log(data.items);
var viewModel = {
title: 'Overview',
query: ko.observable('')
};
viewModel.activate = activate();
viewModel.attached = attached();
viewModel.model = mapping.fromJS(data.items, {}, viewModel);
/*understanding ko.mapping.fromJS signature:knockoutjs.com/documentation/plugins-mapping.html
ko.mapping.fromJS(data) - this syntax will create view model.
ko.mapping.fromJS(data, mappingOptions) - this will create view model with particular options.
ko.mapping.fromJS(data, mappingOptions, viewModel) -
ko.mapping.fromJS(data, viewModel) -
ko.mapping.fromJS(data, {}, viewModel) - and this one convers your data without mapping options and put it to view model.
*/
viewModel.filteredItems = ko.computed(function () {
var search = this.query().toLowerCase();
alert("i'am here in viewModel.books computed");
console.log(viewModel.model);
return ko.utils.arrayFilter(this.model(), function (book) {
return book.id().toLowerCase().indexOf(search) >= 0 || book.kind().toLowerCase().indexOf(search) >= 0 || book.etag().toLowerCase().indexOf(search) >= 0
});
}, viewModel);
return viewModel;
});
});
Utility Functions in KnockoutJS
UPDATES: i recieve a loop of objects when i console.log(viewModel.model);
You haven't clearly stated what it is that doesn't work about it?
However, you probably need to add the activate and attached methods to the viewModel in order for them to be called by durandal.
viewModel.activate = activate;
viewModel.attached = attached;
You probably also intend this chunk of code to be called within the activate function and not in the define call:
var url = "https://www.googleapis.com/books/v1/volumes?q=the+Cat+In+The+Hat",path =$.getJSON(url);
path.then( function (data) {
var books = data.items;
console.log(books);

Inheritance for durandal (HotTowel) viewmodels?

Simple question, pretty sure it's a complicated answer :)
Is it possible to implement some form of inheritance for viewmodels in Durandal?
So if you have a viewmodel something like this:
define(['durandal/app', 'services/datacontext', 'durandal/plugins/router', 'services/logger'],
function (app, datacontext, router, logger) {
var someVariable = ko.observable();
var isSaving = ko.observable(false);
var vm = {
activate: activate,
someVariable : someVariable,
refresh: refresh,
cancel: function () { router.navigateBack(); },
hasChanges: ko.computed(function () { return datacontext.hasChanges(); }),
canSave: ko.computed(function () { return datacontext.hasChanges() && !isSaving(); }),
goBack: function () { router.navigateBack(); },
save: function() {
isSaving(true);
return datacontext.saveChanges().fin(function () { isSaving(false); })
},
canDeactivate: function() {
if (datacontext.hasChanges()) {
var msg = 'Do you want to leave and cancel?';
return app.showMessage(msg, 'Navigate Away', ['Yes', 'No'])
.then(function(selectedOption) {
if (selectedOption === 'Yes') {
datacontext.cancelChanges();
}
return selectedOption;
});
}
return true;
}
};
return vm;
//#region Internal Methods
function activate(routeData) {
logger.log('View Activated for id {' + routeData.id + '}, null, 'View', true);
});
}
//#endregion
function refresh(id) {
return datacontext.getById(client, id);
}
});
Is it possible to make that into some kind of base type and inherit further viewmodels from it, being able to extend the requires list and so on?
There is another question on this, but the viewmodels don't appear to be quite the same as the one's that I build for durandal/HotTowel.
Thanks.
I'm pretty sure this can be accomplished with jQuery's extend method. This just occurred to me, so there may be something that I'm missing, but a basic example would be something along the lines of:
basevm.js
... your mentioned viewmodel
inheritingvm.js
define(['basevm'], function (basevm) {
var someNewObservable = ko.observable();
var vm = $.extend({
someNewObservable : someNewObservable
}, basevm);
return vm;
});
Please let me know if this works. I just coded from the top of my head and it hasn't been tested.
Just based off what your saying I came up with this. Let me know if this works for you and if it doesn't then let me know what I did wrong.
Thanks.
viewmodelBase
define(['durandal/app', 'services/datacontext', 'durandal/plugins/router', 'services/logger'],
function (app, datacontext, router, logger) {
var vm = function () {
var self = this;
this.someVariable = ko.observable();
this.isSaving = ko.observable(false);
this.hasChanges = ko.computed(function () { return datacontext.hasChanges(); });
this.canSave = ko.computed(function () { return datacontext.hasChanges() && !self.isSaving(); });
};
vm.prototype = {
activate: function (routeData) {
logger.log('View Activated for id {' + this.routeData.id + '}', null, 'View', true);
},
refresh: function (id) {
return datacontext.getById(client, id);
},
cancel: function () {
router.navigateBack();
},
goBack: function () { router.navigateBack(); },
save: function() {
var self = this;
this.isSaving(true);
return datacontext.saveChanges().fin(function () { self.isSaving(false); })
},
canDeactivate: function() {
if (datacontext.hasChanges()) {
var msg = 'Do you want to leave and cancel?';
return app.showMessage(msg, 'Navigate Away', ['Yes', 'No'])
.then(function(selectedOption) {
if (selectedOption === 'Yes') {
datacontext.cancelChanges();
}
return selectedOption;
});
}
return true;
}
};
return vm;
});
parent viewmodel
define([viewmodelBase], function (vmbase) {
var vm1 = new vmbase();
vm1.newProperty = "blah";
var vm2 = new vmbase();
});
I wrote a post on my blog that addresses this issue. In short, I use prototypical inheritance for all of my modal dialog views in one of my projects. Here's the link to the post I wrote (feel free to skip to the code part) and a jsFiddle example that demonstrates it.
Simplified example that can work in Durandal (NOTE: each view-model returns its constructor function, not an object):
viewmodels/modal.js
define(['durandal/system'],
function(system) {
var modal = function () {
this.name = 'Modal';
}
modal.prototype = {
activate: function() {
system.log(this.name + ' activating');
},
attached: function(view) {
system.log(this.name + ' attached');
},
deactivate: function() {
system.log(this.name + ' deactivating');
},
detached: function(view, parent) {
system.log(this.name + ' detached');
}
};
return modal;
});
viewmodels/child.js
define(['durandal/system', 'viewmodels/modal'],
function(system, Modal) {
var child = function() {
this.name = 'Child Modal';
}
// inherits from Modal
child.prototype = new Modal();
child.prototype.constructor = child;
child.prototype._super = Modal.prototype;
// overrides Modal's activate() method
child.prototype.activate = function() {
this._super.activate.call(this); // we can still call it from the _super property
system.log(this.name + ' activating [overridden version]');
};
return child;
});
I prefer this implementation because it supports code reuse, conforms to OOP principles as best as javascript allows, and it gives me the ability to call the base class' methods via the _super property when I need to. You can easily convert this as needed.

Migrating from YUI2 to YUI3 and domready

I want to migrate the javascript in my site from YU2 to YUI3, but I am only a poor amateur programer and I am stuck at the first pitfall.
I have the following code:
MyApp.Core = function() {
return {
init: function(e, MyAppConfig) {
if (MyAppConfig.tabpanels) {
MyApp.Core.prepareTabpanels(MyAppConfig.tabpanels);
}
},
prepareTabpanels: function(tabpanels) {
// Code here
}
}
}();
var MyAppConfig = {
"tabpanels":{"ids":["navigation"]}
};
YAHOO.util.Event.addListener(window, "load", MyApp.Core.init, MyAppConfig);
How can I pass the MyAppConfig object to the MyApp.Core.init function by using YUI3 "domready" event listener?
Thanks in advance!
You should be able to do something like:
var MyApp = {};
MyApp.Core = function(){ return {
init: function(MyAppConfig) {
console.log(MyAppConfig);
},
prepareTabpanels: function(tabpanels) {
// Code here
}
}
}();
var MyAppConfig = {
"tabpanels":{"ids":["navigation"]}
};
YUI().use('node', 'event', function(Y){
Y.on('domready', MyApp.Core.init, this, MyAppConfig);
});
Note that the event is not passed in as the first parameter, it is the config.
Y.on accepts parameters as <event_type>, <callback_function>, <context>, <params>..
any parameter after the third item is passed through to the callback function so MyAppConfig becomes the first parameter in your init.
EDIT
See the YUI3 API documentation here: http://developer.yahoo.com/yui/3/api/YUI.html#method_on