Reputation: 103
I've just started looking at knockout components.
I am trying to do the following.
from the main module
var setup = {color:"pink"};
ko.components.register('headerbar', {require:"/headerbar"});
the component
define(["ko", "text!./headerbar.html"], function(ko, html) {
"use strict";
var vm = function(prms){
//use passed setup info here
};
return { viewModel: vm, template: html };
});
I hope to be able to do this, so I can pass in some set up details and not have to express them in each instance of the component via its params
Upvotes: 0
Views: 480
Reputation: 103
This is what I ended up with.
var ctxPassingLoader = {
to_pass: {
},
loadComponent:function(name, cfg, callback){
if(cfg.ctx){
this.to_pass[name] = cfg.ctx;
}
app.ko.components.defaultLoader.loadComponent(name, cfg, callback);
},
loadViewModel: function(name, original, callback) {
var ctx = this.to_pass[name] || original.ctx;
this.to_pass[name] = null;
if (ctx) {
var wrapper;
if(original.createViewModel){
wrapper = {
createViewModel : function(params, info){
original.createViewModel(params, info, ctx);
}
};
}else{
wrapper = function(params){
return original(params, ctx);
};
}
app.ko.components.defaultLoader.loadViewModel(name, wrapper, callback);
} else {
callback(null);
}
}
};
app.ko.components.loaders.unshift(ctxPassingLoader);
calling code
var setup = {color:"pink"};
ko.components.register('headerbar', {require:"/headerbar", ctx:setup});
Upvotes: 0