Augmentation and hooking into knockout bindng mechanism - performance

This is something I've been trying to do for quite some time. I've managed something, but I am pretty sure there is a better way.
Question
I want to be able to hook into the bindingProvider process to augment the name of the observable with a prefix (or something similar).
So if I have:
<button data-bind="text: label"></button>
I want to be able to intercept the processig of the binding and replace label with myLabel, so it essentially processed as:
<button data-bind="text: myLabel"></button>
and that is based on some data on the ViewModel that is being applied to the node.
Attempts
use preprocessNode and replace the label value with myLabel before KO gets to it
Obviously, I'd like to avoid doing that, especially since myLabel may be used only in some cases - since it's based on dynamic data on the ViewModel.
Also, no bindingContext reference is available, so I am not sure how to get to ViewModel.
Use custom bindingProvider and do some string/$data mash-up in getBindings
Use preprocess and augment the value
This would be the perfect candidate if not for 2 things: I will have to repeat that for all bindings, since the form is ko.bindingHandlers.<name>.preprocess and it doesn't give me bindingContext, so I can't use that ViewModel data :)
Use extenders
The problem with this is that I need that augmentation behaviour to be applied to all observable values, not just specific ones. By default.
Any suggestions?
Thank you.
Example
To further illustrate the requirement - imagine that I have a template that looks like this:
<ul data-bind="foreach: people">
<li>
<span data-bind="text: name"></span>,
<span data-bind="text: age"></span>
</li>
</ul>
Trivial. Now imagine that ViewModel data looks like this:
{
people: [
{name: 'John', age: 30},
{name: 'Dean', age: 40},
{age: 0.2}
]
}
Basically, there are people and some of them are just born and don't have a name yet.
I'd like to be able to return something like 'noname' for those who are nameless and under the age of 1.
I clearly can do it by changing the template, but this is something I do not want to do. The template may be reused for something that prints noname based on gender, rather than age or something similar.
Hope that helps.

An alternative approach that would solve this particular use case is a custom binding which takes the property name as a string and sets the text to the given property using the viewModel parameter to the binding handler.
A binding like that could look like this:
ko.bindingHandlers.customText = {
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var field = ko.unwrap(valueAccessor())
element.innerText = ko.unwrap(viewModel[field]);
}
}
Here's a full jsfiddle example.
You could also do something more sophisticated than a straight property name lookup - you could even pass in a function to the binding which takes the view model as a parameter and returns the relevant data.

So, observable are the way to go, thank you all who suggested it.
Eventually one of my colleagues had an idea that turned out to be a very nifty simple trick (and I was kicking myself for blacking out on this).
The idea is based on creating a label computed for mylabel observable. This would work in most cases, aside from the case when ViewModel already has an unrelated label observable, which will then be overridden by the computed - something that may not be desired.
For the ViewModel observable I want to map to (in the above example myLabel), instead of the original label you create a computed with the name of label (so that template still works as before), but a trick is to add the label observable not to the ViewModel itself, rather to an object that is instantiated with ViewModel as prototype.
Tha way - all the rest of elements to which this ViewModel is applied will use the label value that it has, and for this specific template the new label computed will shadow the "old" one - which is the desired effect.
Basically:
var Context = function() {
// create computed observable `label` for observable `myLabel`
// based on whatever ViewModel data is needed.
};
Context.prototype = ViewModel;
var context = new Context();
ko.applyBindings(context, node);

Related

Dynamically adding custom elements to DOM Aurelia [duplicate]

It seems Aurelia is not aware when I create and append an element in javascript and set a custom attribute (unless I am doing something wrong). For example,
const e = document.createElement('div');
e.setAttribute('custom-attr', 'some value');
body.appendChild(e);
Is there a way to make Aurelia aware of this custom attribute when it gets appended?
A little background: I am creating an app where the user can select their element type (e.g. input, select, checkbox etc.) and drag it around (the dragging is done in the custom attribute). I thought about creating a wrapper <div custom-attr repeat.for="e of elements"></div> and somehow render the elements array, but this seemed inefficient since the repeater will go through all the elements everytime I push a new one and I didn't not want to create a wrapper around something as simple as a text input that might be created.
You would have to manually trigger the Aurelia's enhance method for it to register the custom attributes or anything Aurelia related really. And you also have to pass in a ViewResources object containing the custom attribute.
Since this isn't as straight forward as you might think, I'll explain it a bit.
The enhance method requires the following parameters for this scenario:
Your HTML as plain text (string)
The binding context (in our scenario, it's just this)
A ViewResources object that has the required custom attribute
One way to get access to the ViewResources object that meets our requirements, is to require the custom attribute into your parent view and then use the parent view's ViewResources. To do that, require the view inside the parent view's HTML and then implement the created(owningView, thisView) callback in the controller. When it's fired, thisView will have a resources property, which is a ViewResources object that contains the require-d custom attribute.
Since I am HORRIBLE at explaining, please look into the example provided below.
Here is an example how to:
app.js
import { TemplatingEngine } from 'aurelia-framework';
export class App {
static inject = [TemplatingEngine];
message = 'Hello World!';
constructor(templatingEngine, viewResources) {
this._templatingEngine = templatingEngine;
}
created(owningView, thisView) {
this._viewResources = thisView.resources;
}
bind() {
this.createEnhanceAppend();
}
createEnhanceAppend() {
const span = document.createElement('span');
span.innerHTML = "<h5 example.bind=\"message\"></h5>";
this._templatingEngine.enhance({ element: span, bindingContext: this, resources: this._viewResources });
this.view.appendChild(span);
}
}
app.html
<template>
<require from="./example-custom-attribute"></require>
<div ref="view"></div>
</template>
Gist.run:
https://gist.run/?id=7b80d2498ed17bcb88f17b17c6f73fb9
Additional resources
Dwayne Charrington has written an excellent tutorial on this topic:
https://ilikekillnerds.com/2016/01/enhancing-at-will-using-aurelias-templating-engine-enhance-api/

Does nativescript use 2 view models

In the image of this project which is the view model file? I would have thought main-page.js but then main-view-model.js is titled "-view-model".
"view-model file" is not really a set programming concept. But I guess you mean a file which only holds one function which acts as a view-model. If that's the case, then main-view-model.js is most probably the "view-model file". Looking at the content it looks view-model-ish.
However 1, you need to look at main-page.js to see how that is used.
However 2, in NativeScript, view models are often observable objects and looking at this code, the ViewModelItem is not an observable object.
not sure about that ViewModelItem object, but in NativeScript, view1.xml is the view and view1.js would be the "code-behind" and that means you will code the logic directly related to the view itself: Button has a tap="getName"? that function goes to view1.js...
viewModel files would be where you create observables with the datas you fetch from a remote source for exemple, and all the methods say 'saveName(ppl)' that would POST your object to the server would be in the viewModel file...
you would create your observable like this:
var studentList = new StudentListViewModel([]);
var pageData = observableModule.fromObject({
studentList: studentList,
student: "",
prof: "Choisir"
});
and any changes has to be set like that:
pageData.set("prof", prof)
hope it is clear...

How to trigger DataBinding Validation for all Controls?

I have an OpenUI5 form consisting of a number of Inputcontrols. These Inputcontrols are bound to a model using the OpenUI5 DataBinding as described in the documentation.
For example:
new sap.m.Input({
value: {
path: "/Position/Bezeichnung",
type: new sap.ui.model.type.String(null, {
minLength: 1,
maxLength: 128
})
}
})
As in the example above I'm using constraints on the stringlength.
When a User changes the Value of the Input, the Validation is triggered and according to the Validationresult one of the functions descripted here is called.
In these functions I'm setting the ValueState of the control like this:
setupValidation: function() {
var oCore = sap.ui.getCore();
oCore.attachValidationError(function (oEvent) {
oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.Error);
});
oCore.attachValidationSuccess(function (oEvent) {
oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.None);
});
oCore.attachFormatError(function (oEvent) {
oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.Error);
});
oCore.attachParseError(function (oEvent) {
oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.Error);
});
},
Let's assume the bound model variable is initial.
I'm loading the view, the property value is parsed and displayed as empty.
The Validationerror/Parseerror method is not called although the constraints are not met.
This seems to be standard behaviour of OpenUI5. Only changes in the Control will be a validated.
Now let's assume I've a submit button and the Value of the Inputcontrol is still empty. When the user hits the submit button I'd like to trigger the DataBinding Validation for all childcontrols of my view. This would validate the above mentioned input and would result in an errorstate.
My question is: How can I trigger the databinding validation for all childcontrols of my view?
There is another question on SO where the poster asks for a way to define required fields. The proposed solution is to call getValue() on the control and validate the value manually. I think this is kind of cumbersome as formating and constraint information and logic is already present.
I suggest looking into field groups.
An example here in the UI5 docs
Field Groups allow you to assign group IDs to the input fields. Then you can call all of the input fields at once. You can set the name property and required property on each <Input> separately in your view, allowing you to handle some logic when you perform validation.
You can call this.getView().getControlsByFieldGroupId("fieldGroupId"), which will return an array of the input controls. Then you can loop through the controls, pass them through your logic, and use setValueState() to show the results.
Or, you can assign the validateFieldGroup event on the parent container, which is usually a form, but can be anything like a <VBox> that contains the controls. When the users focus moves out of the field group, the event is fired. You can then use the event handler in your controller to perform the validation.
In your case, I would assign a press event to your submit button, and in the handler, call the field group by ID and loop through the controls. At the end of your function, check to see if all fields are validated before continuing.
View
<Input name="email" required="true" value="{/user/email}" fieldGroupIds="fgUser"/>
<Input name="firstName" required="false" value="{/user/firstName"} fieldGroupIds="fgUser"/>
<Button text="Submit" press="onSubmit"/>
Controller
onSubmit: function() {
var aControls = this.getView().getControlsByFieldGroupId("fgUser");
aControls.forEach(function(oControl) {
if (oControl.getRequired()) {
//do validation
oControl.setValueState("Error");
oControl.setValueStateText("Required Field");
}
if (oControl.getName() === "firstName") {
//do validation
oControl.setValueState("Success");
}
});
var bValidated = aControls.every(function(oControl) {
return oControl.getValueState() === "Success";
});
if (bValidated) {
//do submit
}
}
The concept goes like this.
Use custom types while binding, to define validations. Validation
rules go inside these custom types (in the method 'validateValue').
When Submit is pressed, loop through the control hierarchy and
validate each control in your view. (By calling 'validateValue'
method of the Custom Type).
Validator (https://github.com/qualiture/ui5-validator ) uses this concept and it is a small library to make your life easy. Its main advantage is that it recursively traverses through the control library.
Using Message Manager (using sap.ui.get.core().getMessageManager() ) is the way to show the validation messages on the UI control.
Triggering data binding validations is not possible. Rather for empty fields that are having required property true you can do a work around using jQuery.
Please refer my answer to this same problem at Checking required fields

An aesthetic or correct way of invoking an action that requires DOM manipulation as well as controller related tasks in EmberJS

My EmberJS app has a couple of actions (triggered by buttons) that require a view/DOM manipulation as well as setting a state in the controller, followed by a model update. The way I do this, it does not appeal to my programming aesthetics. It gets the job done, but it doesn't look good :(
Here is a gist of how I do things :
<button {{action 'whatever' target='view'}}></button>
App.MyView = Ember.View.extend({
actions:{
whatever:function(){
var ctrl = this.get('controller');
ctrl.set('property',value); // arbitrary example of setting a controller property through it's view
ctrl.controllerMethod(); // invoking a controller method through the view
**// do some DOM manipulation**
}
}
});
Naturally, I can wrap whatever controller related steps I am performing in the view in a controller method and invoke that method through the view, but IMO that's just equally ugly. The view shouldn't really be invoking a controller method like how I have done. Unfortunately, this specific action requires a DOM manipulation as well as setting some state and performing an action in the controller.
I am not sure what is the recommended way of performing this. Can anyone enlighten ?
I suggest you handle the action from the controller. I noticed you're setting a property. You can use that to signal something to the view and then do the DOM manipulation within the view.
App.MyView = Ember.View.extend({
function () {
**// do some DOM manipulation**
}.observe('controller.property');
});
The way I think about it is that UI 'actions' are mapped to a business event (e.g. addClient instead of click), then as a result of that something happens that could change properties of the model, controller. As a result of those changes the view might need to update directly, ideally through a binding, but sometimes is needed to modify the DOM manually.
as #LukeMelia said in his comment you should really handle the changes in your controller and update your view (if you need to?) via databinding.
so, you would just omitt the target="view" argument from your view helper and Ember will look for the proper action in the nearest controller, bubbling all the way up to the route, and so on.
a simple code snippet (with what you provided in your first post) would look like:
Handlebars Template:
<button {{action someAction}}>Fire!</button>
Ember.Controller:
App.MyController = Ember.ObjectController.extend({
myProperty: 'cool',
printMyCoolness: function () {
console.log("I'm using Ember.js!");
},
actions: {
someAction: function () {
this.set('myProperty', 'set on fire!');
this.printMyCoolness();
}
}
});

knockout js - How to do Conditional Binding on a dropdownlist

I've got a Knockout viewmodel populated from a variety of Mvc actions.
A Category is chosen from the first dropdown (say Fruit, Meat, Drinks etc).
A second dropdown is automatically populated from the first choice. However, there may be 2 matches for fruit (say Apples, Oranges), 2 for meat (say Beef, Lamb) and many choices for drink (several hundred).
My page currently displays a search box depending on the Category chosen.
I was wondering how to automatically bind the second dropdown for Fruit & Meat, or wait and do the bind from the results of the search query.
Sorry this is vague - twitchy client! Very new to KnockoutJs.
Thanks in advance.
If I understood you right, you could create a method in your viewmodel which you bind to the change event of the dropdown.
Example method:
var myViewModel = {
firstDropDownArray: ko.observableArray([]),
secondDropDownArray: ko.observableArray([]),
// Validates Selection
validateSelection: function (item) {
var anotherList;
switch (item.toUpperCase()) {
case "FRUIT":
// Do something...
break;
case "DRINKS":
// Do something else...
break;
default:
}
}
};
Your Dropdown can bind then to the method like this:
<select id="FirstDropDown" data-bind="options: myViewModel.firstDropDownArray, <any other binding options>, event: {change: myViewModel.validateSelection(currentItem)}">
</select>
As stated here: event-binding,
When calling your handler, Knockout will supply the current model
value as the first parameter.
I'm assuming this means the currentItem will be the selected item when you are calling the method.
I know in my sample code I wrote item.toUpperCase() but that is just assuming the item is passed as a string. This syntax obviously has to change depending on how you have declared and populated your dropdown but in essence you still should be able to write a method in your viewmodel you can bind then to the change event,..or any other event you like.

Resources