I have nested view models like below. I am trying to access value in container view model from the contained view model (child). I got undefined error when the modelA.prop1 trying to get mainVM.prop1 value. Thanks for your help.
function mainVM() {
var self = this;
//chain associated view models
self.modelA = new modelA();
self.modelB = new modelB();
self.prop1 = ko.observable("some value from mainVM.prop1");
}
function modelA(){
var self = this;
self.prop1 = ko.observable(mainVM.prop1); //I'd like to get value in containing view model above
}
function modelB(){....}
$(function () {
var viewModel = new mainVM();
ko.applyBindings(viewModel);
});
If you want to make sub-ViewModels dependent/aware of their parent you'll have to pass it to them. E.g.:
function mainVM() {
var self = this;
//chain associated view models
self.modelA = new modelA(self);
self.modelB = new modelB(self);
self.prop1 = ko.observable("some value from mainVM.prop1");
}
function modelA(parent){
var self = this;
self.prop1 = ko.observable(parent.prop1); //I'd like to get value in containing view model above
}
function modelB(parent){....}
$(function () {
var viewModel = new mainVM();
ko.applyBindings(viewModel);
});
Think carefully though if this dependency is something you want in your design.
An alternative (though arguably worse from a design standpoint) solution would be to give them access through the scope, e.g.:
$(function () {
function mainVM() {
var self = this;
//chain associated view models
self.modelA = new modelA();
self.modelB = new modelB();
self.prop1 = ko.observable("some value from mainVM.prop1");
}
function modelA(){
var self = this;
self.prop1 = ko.observable(viewModel.prop1); //I'd like to get value in containing view model above
}
function modelB(){....}
var viewModel = new mainVM();
ko.applyBindings(viewModel);
});
Some additional thoughts to #Jeroen answer
Having dependencies to parent from children is not only bad design it can create hard to find memory leaks
If you use the parent from a computed in the child KO will hook up a dependency, if you remove the child it's computed will still fire when the parent change state.
My general way of solving dependencies between models is to use a EventAggregator pattern, I have made one for this library
https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy
Its a signalR library, if you do not need singalR you can extract the event aggregation part
Demo
http://jsfiddle.net/jh8JV/
ViewModel = function() {
this.events = ko.observableArray();
this.subModel = new SubViewModel();
signalR.eventAggregator.subscribe(Event, this.onEvent, this);
};
ViewModel.prototype = {
onEvent: function(e) {
this.events.push(e);
}
};
I think you've got an "XY problem" here: you want to accomplish task X (which you haven't named here) and you think that implementation Y (in this case, a child VM having a dependency on its parent) is the way to do it, even though Y might not be the best (or even a good) way to do it.
What's the actual problem you're trying to solve? If you need to access the parent property from within a child binding, Knockout's binding context ($root, $parent, $parents[], etc.) will let you do it, e.g.
<div data-bind="with:modelA">
<p>prop2 is <span data-bind="text:prop2"></span>
and prop1 from the main model is
<span data-bind="text:$root.prop1"></span>
</p>
</div>
In this case you could use $parent in place of $root since there's only one level of nesting.
Related
I am working with Knockout for the first time and I am struggling with an observable. I have declared it in one view model and I need to gain access to the value in another. Any tips on how to go about that?
What you have to do, it's to inherit the parentViewModel
function parentViewModel() {
// Just a best practice potato here :P
var self = this;
// Initialize the childViewModel change it's 'this'
childViewModel.call(self);
self.observable = ko.observable();
}
function childViewModel() {
var self = this;
console.log(self); // It will output the parentViewModel scope
}
First declare your 1st model in a shared scope, then the 2nd. If you do something like myfirstmodel.myobservable() within your second model, you should see it and interact with it.
var myModel = whatever();
var mySndModel = whateverElse();
ko.applyBindings(myModel, document.getElementById('whatever'))
ko.applyBindings(mySndModel, document.getElementById('whateverElse'))
whateverElse is the constructor of your second model, in which you can call myModel.myObservable()
I'm using KnockoutJS to develop a plugin based on viewmodels. Is there any way to access the functions and properties of another viewmodel running in the same application? Something like this:
My view model:
function myViewModel()
{
this.prop1 = ko.observable(123);
this.prop2 = ko.observable("Hello");
..
..
}
myViewModel.prototype.func1 = function() {
//do something...
};
myViewModel.prototype.func2 = function() {
//do something...
};
And the other view model:
function otherViewModel()
{
this.propA = ko.observable(456);
this.propB = ko.observable("Goodbye");
..
..
}
otherViewModel.prototype.funcA = function() {
//do something...
};
otherViewModel.prototype.funcB = function() {
//do something...
};
The observables of the otherViewModel control certain common functions like pop-ups and masks. Is there any way to instantiate otherViewModel in myViewModel and set those properties?
Or is there any way to globally get and set them?
Please tread lightly as I'm very new to this paradigm. Thank you.
I agree with the comment to use scopes - but there are a couple of quick and dirty ways...
when you instantiate myViewModel - you could instantiate it on the window - and then reference it directly
window.myViewInstance = new myViewModel()
function myOtherViewModel () {
this.propA = myViewInstance.xyz
}
I use this method when I have something that provides global functionality that I want to use elsewhere. Its what jQuery and ko do... bind $ and ko to the window.
if myViewModel.xyz = ko.observable() then passing it without parens passes it as an observable - which will change as its value changes. With the parens will pass the result at the time it is evaluated.
Alternatively - you can reference it using ko.dataFor like this.
myViewModel () {...}
instance = new myViewModel
ko.applyBindings(instance, $('div')[0])
// this applies bindings of myViewModel to the first div on the page only
myOtherViewModel () {
this.propA = ko.dataFor($('div')[0])
// passes the entire object
this.propB = ko.dataFor($('div')[0]).xyz
// gives you just one property
}
Which would scope your object to just a part of the page
I have been using Knockout.js for a lot of projects lately, and I am writing a lot of repetitive code. I would like to be able to define a BaseViewModel class and have my page-specific ViewModels inherit from it. I am a bit confused about how to do this is Javascript. Here is my basic BaseViewModel:
(function (ko, undefined) {
ko.BaseViewModel = function () {
var self = this;
self.items = ko.observable([]);
self.newItem = {};
self.dirtyItems = ko.computed(function () {
return self.items().filter(function (item) {
return item.dirtyFlag.isDirty();
});
});
self.isDirty = ko.computed(function () {
return self.dirtyItems().length > 0;
});
self.load = function () { }
};
}(ko));
I would like to be able to list signatures for methods like load in the BaseViewModel and then give them definitions in the inheriting ViewModel. Is any of this possible? I have found a few solutions online but they all rely on defining functions/classes to make the inheritance work.
Since your BaseViewModel is just adding all of the properties/methods to this (and not using prototype) then it is pretty easy:
In your new view models, just call BaseViewModel:
var MyVM = function () {
var self = this;
ko.BaseViewModel.call(self);
self.somethingElse = ko.observable();
self.itemCount = ko.computed(function() { return self.items().length; });
self.items([1, 2, 3]);
};
// ...
var vm = new MyVM();
Javascript inheritance is done in two pieces. The first is in the constructor, and the second is on the prototype (which you aren't using, so you could skip).
var ViewModel = function(data) {
BaseViewModel.call(this);
};
//you only need to do this if you are adding prototype properties
ViewModel.prototype = new BaseViewModel();
To your last point, about overriding load, its no different that putting a load function on your viewmodel normally. Javascript allows you to override any objects properties with anything, there are no special steps here.
Here is a fiddle demonstrating the inheritance.
In knockout js I see View Models declared as either:
var viewModel = {
firstname: ko.observable("Bob")
};
ko.applyBindings(viewModel );
or:
var viewModel = function() {
this.firstname= ko.observable("Bob");
};
ko.applyBindings(new viewModel ());
What's the difference between the two, if any?
I did find this discussion on the knockoutjs google group but it didn't really give me a satisfactory answer.
I can see a reason if I wanted to initialise the model with some data, for example:
var viewModel = function(person) {
this.firstname= ko.observable(person.firstname);
};
var person = ... ;
ko.applyBindings(new viewModel(person));
But if I'm not doing that does it matter which style I choose?
There are a couple of advantages to using a function to define your view model.
The main advantage is that you have immediate access to a value of this that equals the instance being created. This means that you can do:
var ViewModel = function(first, last) {
this.first = ko.observable(first);
this.last = ko.observable(last);
this.full = ko.computed(function() {
return this.first() + " " + this.last();
}, this);
};
So, your computed observable can be bound to the appropriate value of this, even if called from a different scope.
With an object literal, you would have to do:
var viewModel = {
first: ko.observable("Bob"),
last: ko.observable("Smith"),
};
viewModel.full = ko.computed(function() {
return this.first() + " " + this.last();
}, viewModel);
In that case, you could use viewModel directly in the computed observable, but it does get evaluated immediate (by default) so you could not define it within the object literal, as viewModel is not defined until after the object literal closed. Many people don't like that the creation of your view model is not encapsulated into one call.
Another pattern that you can use to ensure that this is always appropriate is to set a variable in the function equal to the appropriate value of this and use it instead. This would be like:
var ViewModel = function() {
var self = this;
this.items = ko.observableArray();
this.removeItem = function(item) {
self.items.remove(item);
}
};
Now, if you are in the scope of an individual item and call $root.removeItem, the value of this will actually be the data being bound at that level (which would be the item). By using self in this case, you can ensure that it is being removed from the overall view model.
Another option is using bind, which is supported by modern browsers and added by KO, if it is not supported. In that case, it would look like:
var ViewModel = function() {
this.items = ko.observableArray();
this.removeItem = function(item) {
this.items.remove(item);
}.bind(this);
};
There is much more that could be said on this topic and many patterns that you could explore (like module pattern and revealing module pattern), but basically using a function gives you more flexibility and control over how the object gets created and the ability to reference variables that are private to the instance.
I use a different method, though similar:
var viewModel = (function () {
var obj = {};
obj.myVariable = ko.observable();
obj.myComputed = ko.computed(function () { return "hello" + obj.myVariable() });
ko.applyBindings(obj);
return obj;
})();
Couple of reasons:
Not using this, which can confusion when used within ko.computeds etc
My viewModel is a singleton, I don't need to create multiple instances (i.e. new viewModel())
I'm using CoffeeScript and KnockoutJS and have a problem getting the values of my view model from within a function.
I have a view model:
window.Application || = {}
class Application.ViewModel
thisRef = this
searchTerm: ko.observable("")
search: ->
alert #searchTerm
Which compiles to:
window.Application || (window.Application = {});
Application.ViewModel = (function() {
var thisRef;
function ViewModel() {}
thisRef = ViewModel;
ViewModel.prototype.searchTerm = ko.observable("");
ViewModel.prototype.search = function() {
return alert(this.searchTerm);
};
return ViewModel;
})();
This view model is part of a parent view model which exposes it as field. The problem is that I can't get a reference to the child view model. In the search function 'this' is a instance of the parent, which I don't want.
In the search function 'this' is a instance of the parent...
That depends on how you call it. If you do
m = new Application.ViewModel
m.search()
then this will be m; if you write
obj = {search: m.search}
obj.search()
then this will be obj.
Anyway, just use CoffeeScript's => operator:
search: =>
alert #searchTerm
That way, this/# within search will point to the ViewModel instance.
thisRef will, as Travis says, just point to the class, not the instance.
You already have a thisRef object hanging around, use thisRef.searchTerm instead of #searchTerm. I often have that happen when using jQuery...
doSomething = ->
target = $(#)
$("#blah").click ->
target.doSomethingElse()
Since #doSomethingElse() would be bound to the DOM element the click was executed for. Not what I want.