In my app, I have a section called 'notifications' inside a view, called 'home.html'
. Now I need to use this section in another view, so I copied all the notifications markup inside 'notifications.html', that I'm using through composition.
The problem is that I don't want to copy all the code that I use for the notifications to work from 'home.js' to the another viewmodel of my new view that is going to use notifications. So instead of having an observableArray
of notifications inside the view viewmodel, I want to have a module only for 'notification.html' that contains this data. But I don't know how I can change the value of the observableArray
inside 'notification.js' from my other viewmodels.
Here is what I did so far:
notification.js
define(['knockout'], function(ko) {
var notifications = ko.observableArray([]),
setNotifications = function(data) {
notifications(data)
}
return {
notifications: notifications,
setNotifications: setNotifications
}
home.js
define(['knockout', 'notification'], function(ko, notification) {
var self = this
...
self.activate = function() {
http.get('...').then(function(data) {
notification.setNotification(data)
})
}
home.html
<div data-bind="compose: 'viewmodels/notifications'"></div>
What I know is that when using a viewmodel path in the compose binding, the markup of that viewmodel is injected and is bound to it's module viewmodel.
The problem: I want to change the value of the 'notifications' array inside 'notification.js'
from the viewmodel of my main view, 'home.js'
. I know that my current tentative isn't going to work, because I believe that the instance of notifications.js
viewmodel being injected into notifications.html
isn't the same instance that I require inside home.js
. So how can I achieve that?
I could solve this problem using the model
property on the compose
binding.
Markup:
<div data-bind="compose: { view: 'views/notifications', model: $root.notificationModel }"></div>
notification.js has the same code - it returns the viewmodel ("return vm")
And in the home.js file:
define(['knockout', 'plugins/http', 'notification'], function(ko, http, NotificationModel) {
var self = this
self.notificationModel;
...
self.activate = function() {
return http.get('').then(function(data) {
self.notificationModel = new NotificationModel()
self.notificationModel.setNotifications(data)
})
}
})