Unbind view model from view in knockout - forms

I'm looking for unbind functionality in knockout. Unfortunately googling and looking through questions asked here didn't give me any useful information on the topic.
I will provide an example to illustrate what kind of functionality is required.
Lets say i have a form with several inputs.
Also i have a view model binded to this form.
For some reason as a reaction on user action i need to unbind my view model from the form, i.e. since the action is done i want all my observables to stop reacting on changes of corresponding values and vise versa - any changes done to observables shouldn't affect values of inputs.
What is the best way to achieve this?

You can use ko.cleanNode to remove the bindings. You can apply this to specific DOM elements or higher level DOM containers (eg. the entire form).
See http://jsfiddle.net/KRyXR/157/ for an example.

#Mark Robinson answer is correct.
Nevertheless, using Mark answer I did the following, which you may find useful.
// get the DOM element
var element = $('div.searchRestults')[0];
//call clean node, kind of unbind
ko.cleanNode(element);
//apply the binding again
ko.applyBindings(searchResultViewModel, element);

<html>
<head>
<script type="text/javascript" src="jquery-1.11.3.js"></script>
<script type="text/javascript" src="knockout-2.2.1.js"></script>
<script type="text/javascript" src="knockout-2.2.1.debug.js"></script>
<script type="text/javascript" src="clickHandler.js"></script>
</head>
<body>
<div class="modelBody">
<div class = 'modelData'>
<span class="nameField" data-bind="text: name"></span>
<span class="idField" data-bind="text: id"></span>
<span class="lengthField" data-bind="text: length"></span>
</div>
<button type='button' class="modelData1" data-bind="click:showModelData.bind($data, 'model1')">show Model Data1</button>
<button type='button' class="modelData2" data-bind="click:showModelData.bind($data, 'model2')">show Model Data2</button>
<button type='button' class="modelData3" data-bind="click:showModelData.bind($data, 'model3')">show Model Data3</button>
</div>
</body>
</html>
#Mark Robinson gave perfect solution, I've similar problem with single dom element and updating different view models on this single dom element.
Each view model has a click event, when click happened everytime click method of each view model is getting called which resulted in unnecessary code blocks execution during click event.
I followed #Mark Robinson approach to clean the Node before apply my actual bindings, it really worked well.
Thanks Robin.
My sample code goes like this.
function viewModel(name, id, length){
var self = this;
self.name = name;
self.id = id;
self.length = length;
}
viewModel.prototype = {
showModelData: function(data){
console.log('selected model is ' + data);
if(data=='model1'){
ko.cleanNode(button1[0]);
ko.applyBindings(viewModel1, button1[0]);
console.log(viewModel1);
}
else if(data=='model2'){
ko.cleanNode(button1[0]);
ko.applyBindings(viewModel3, button1[0]);
console.log(viewModel2);
}
else if(data=='model3'){
ko.cleanNode(button1[0]);
ko.applyBindings(viewModel3, button1[0]);
console.log(viewModel3);
}
}
}
$(document).ready(function(){
button1 = $(".modelBody");
viewModel1 = new viewModel('TextField', '111', 32);
viewModel2 = new viewModel('FloatField', '222', 64);
viewModel3 = new viewModel('LongIntField', '333', 108);
ko.applyBindings(viewModel1, button1[0]);
});

Related

Issues getting validation working with dynamically generating form inputs?

I have some basic form/input html that works (including validation) if explicitly written as follows:
<form name="forms.create" novalidate>
<div class="si-container">
<div class="si-input-container">
<input class="si-input" name="someNum" placeholder="Enter a number" ng-model="formdata.number" type="number" min="40"/>
</div>
<div class="si-error">
<div ng-show="forms.create.someNum.$error.min">Error! Value must be > 40.</div>
</div>
</div>
</form>
Now what I want to do is create a directive that allows me to write the html below, but result in the html above:
<form name="forms.create" novalidate>
<div special-input name="someNum" placeholder="Enter a number" type="number" ng-model="formdata.number">
<div error-type="min" error-value="40">Error! Value must be > 40.</div>
</div>
</form>
My attempt at the special-input directive (simplified) is as follows:
.directive('specialInput', [function(){
return {
compile: function(elem, attrs){
var input = angular.element('<input class="si-input"/>');
input.attr('placeholder', attrs.placeholder);
input.attr('type', attrs.type);
input.attr('name', attrs.name);
input.attr('ng-model', attrs.ngModel);
var errorCont = angular.element('<div class="si-error"></div>');
var errors = elem.children();
angular.forEach(errors, function(error){
var err = angular.element(error);
var type = err.attr('error-type');
var value = err.attr('error-value');
input.attr(type, value);
var formName = elem.parent().attr('name');
errorCont.append('<div ng-show="' + formName + '.' + attrs.name + '.$error.' + type + '">' + err.html() + '</div>');
});
var cont = angular.element('<div class="si-container"></div>');
cont.append('<div class="si-floating-label">' + attrs.placeholder + '</div>');
cont.append('<div class="si-input-container">' + input[0].outerHTML + '</div>');
cont.append('<div class="si-underline"></div>');
cont.append(errorCont);
elem.replaceWith(cont[0].outerHTML);
}
};
}]);
Now the resultant html using the directive above looks about right. If I put {{formdata.number}} below the form the value changes as expected. The problem is that now the validation never shows.
For example, if I put the value 5 in the input and inspect the form object, I get weird results. $dirty is set to true for form, but not for form.someNum. If I put 55 in the input, $dirty is still set to false for form.someNum, but $modelValue and $viewValue both show 55.
Any ideas or suggestions? Here is a fiddle to help with any testing.
If you put 50 in the input box you should see the value below, but put 5 and the error does not appear
UPDATE
I have managed to get it working by moving the dom changes into the link function instead of the compile function, and adding this:
elem.replaceWith(cont);
$compile(cont)(scope);
I am still puzzled though, as to why this works, while altering the dom in the exact same way in the compile function doesn't work. Is anyone able to explain this?
It's because the original ng-model is still get compiled even the original DOM has already been replaced by the new one in your compile function.
The ng-model directive will register itself to a parent form in its postLink function. Due to the fact that the postLink function will be executed in reverse (child's before parent's), the new ng-model will do the registration first, thus it will be overridden by the one from the original ng-model eventually.
To avoid this problem, you could change the original ng-model to another name such as my-model, then rename it to ng-model later in your compile function.
Example jsfiddle: http://jsfiddle.net/Wr3cJ/1/
Hope this helps.

how to create dojo data onclick event for dojo dynamic tree in zend framework for programatic approach

i am new to Zend framework and dojo.i have created dynamic tree structure using dojo in zend framework but i want to make on click of each folder and element of tree structure to naigation to another form by writing a function .Pleas check my code and help me i have gone through some dojo on click event link and could not solve ..
<html>
<head>
<title> Tree Structure </title>
<link rel="stylesheet" href=/dojo/dijit/themes/ claro/claro.css" />
<script type="text/javascript" src="/ dojo/dojo/dojo.js"
djConfig="parseOnLoad:true, isDebug:true" >
</script>
<script type="text/javascript">
dojo.require("dojo.parser");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.TabContainer")
dojo.require("dijit.form.Button");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.tree.ForestStoreModel");
dojo.require("dijit.Tree");
dojo.require("dojo.parser");
function myTree( domLocation ) {
var store = new dojo.data.ItemFileReadStore({url: "http://localhost/CMTaSS_module1.0/public/dojo/cbtree/datastore/Family-1.7.json"});
var treeModel = new dijit.tree.TreeStoreModel({
store: store,
query: { name:'John'}
});
var tree = new dijit.Tree( {
model: treeModel,
id: "mytree",
openOnClick: true
});
tree.placeAt( domLocation );
}
var tree_obj = new dijit.Tree({
model: treeModel
},
"tree_obj");
dojo.connect(tree_obj, 'onClick', function(item, node, evt){
console.log("Item", item);
console.log("Node", node);
console.log("Event", evt);
//console.log('node: ' +tree_obj.getLabel(node));
//console.log('event: ' +tree_obj.getLabel(evt));
console.log('identifier: ' + tree_obj.getLabel(item))
});
</script>
</head>
<body class="claro"><br><br><br>
<div id="CheckboxTree">
<script type="text/javascript">
myTree("CheckboxTree");
</script>
</div>
</body>
</html>
Looks like your code sample is not formatted correctly as some of the logic is outside the myTree function. I used jsbeautifier.org to confirm this.
Other notes...
You should wait until dojo is ready. Either use dojo.addonload or, create a widget and reference that widget in the html portion of your code. Widgets are amazing and are what make dojo great, so getting a grasp on how they work will pay dividends.
Also note that if creating a widget programmatically (new dijit.Tree), you should call startup on it. This is not needed when creating it declaratively (inline html).
I hope this helps.

Callback for when a child dom element is inserted or has its class changed?

In Ember.js, I have a view that has
{{#if obj.property}}
<div {{bindAttr class="prop"}}>content</div>
{{/if}}
How can I get called back for when this element is inserted into the view, and for when the class is attached onto the element? I want to do this because the CSS class is an animation class, and I'd like to hook onto the onAnimationEnd event of the element so that I get notified when the animation ends.
How about changing the div to be a custom view subclass that implements didInsertElement? e.g.
{{#if obj.property}}
{{view App.MyView}}
{{/if}}
and
App.MyView = Ember.View.extend({
classNameBindings: "prop",
didInsertElement: function() {
// use this.$() to get a jQuery handle for the element and do what you'd like
}
})
In addition to Luke's answer, I found out another way to achieve this, which may be preferable since creating a view is required for Luke's approach.
By exploiting the fact that DOM events bubble up, I can setup an event handler for animationEnd on a parent DOM element that contains whatever may be inserted. E.g.
<div id="container">
{{#if obj.property}}
<div {{bindAttr class="prop"}}>content</div>
{{/if}}
</div>
// view.js
didInsertElment: function() {
this.$('#container').bind('webkitAnimationEnd', function(e) {
// e.target is the element whose animation ended.
}
}

Dojo events: getting it to work with dynamically added DOM elements

I have a method of a class as follows:
add_file: function(name, id, is_new){
// HTML: <div class="icon mime zip">name.zip <a>x</a></div>
var components = name.split('.');
var extension = components[components.length-1];
this.container.innerHTML += "<div id='"+id+"' class='icon mime "+extension+"'>"+name+" <a id='remove-"+id+"' href='#remove'>x</a></div>";
// Add event to a tag
dojo.connect(dojo.byId('remove-'+id), 'onclick', function(ev){
// here i am
});
},
All is working well, until I run this method more than once. The first time the event is registered correctly, and clicking the 'x' will run the "here i am" function. However, once I add more than one node (and yes, the ID is different), the event is registered to the last node, but removed from any previous ones.
In affect I have this:
<div id="field[photos]-filelist">
<div id="file1" class="icon mime jpg">file1.jpg <a id="remove-file1" href="#remove">x</a></div>
<div id="file2" class="icon mime jpg">file2.jpg <a id="remove-file2" href="#remove">x</a></div>
</div>
...and the remove link only works for the last node (remove-file2 in this case).
The problem is you are using the innerHTML +=
That is going to take the existing html, convert it to plain markup, and then completely create new nodes from the markup. In the process, all of the nodes with events get replaced with nodes that look exactly the same but are not connected to anything.
The correct way to do this is to use dojo.place(newNodeOrHTML, refNode, positionString)
var myNewHTML = "<div id='"+id+"' class='icon mime "+extension+"'>"+name+" <a id='remove-"+id+"' href='#remove'>x</a></div>"
//This won't work as is breaks all the connections between nodes and events
this.container.innerHTML += myNewHTML;
//This will work because it uses proper dom manipulation techniques
dojo.place(myNewHTML, this.container, 'last');

Determine if a dijit's DOM has finished loading

Is there a way to query a dojo dijit to tell if the dijit's DOM has finished loading?
I believe if the dijit's "domNode" property is set, the DOM for the widget has been created. The widget may or may not be attached to the larger DOM, that can be a separate step. Checking domNode.parentNode as being a real element might help, but it is no guarantee that parentNode is also in the live document.
I believe something like this might work, although I didn't test it :
if (yourWidget.domNode) {
// here your widget has been rendered, but not necessarily its child widgets
} else {
// here the domNode hasn't been defined yet, so the widget is not ready
}
Dijit widgets' rendering is handled through extension points, called in that order :
postMixinProperties
buildRendering
postCreate <== at this point, your widget has been turned into HTML and inserted into the page, and you can access properties like this.domNode. However, none of the child widgets has been taken care of
startup : this is the last extension point called, after all the child widgets have been drawn
(This is the explanation of the widgets' lifecycle on "Mastering Dojo").
EXAMPLE :
<html>
<head>
<script src="path/to/your/dojo/dojo.js" djConfig="parseOnLoad: true, isDebug: true"></script>
<script type="text/javascript">
dojo.require("dojo.parser");
dojo.require("dojox.lang.aspect");
dojo.require("dijit.form.Button");
// Define your aspects
var startupAspect = {
before : function() {console.debug("About to execute the startup extension point");},
after : function() {console.debug("Finished invoking the startup extension point");},
};
function traceWidget(theWidget) {
// Attach the aspect to the advised method
dojox.lang.aspect.advise(theWidget, "startup", startupAspect);
}
</script>
</head>
<body>
<button dojoType="dijit.form.Button" type=button">
dijitWidget
<script type="dojo/method" event="postCreate">
traceWidget(this);
</script>
<script type="dojo/method" event="startup">
console.debug("Inside startup");
</script>
</button>
</body>
</html>