How to find rootNode bind with viewModel?

301 views
Skip to first unread message

Zogg

unread,
Jul 5, 2011, 5:09:56 PM7/5/11
to KnockoutJS
Having viewModel, is there a way to find the rootNode it has been bind to?

Say, i have template, and initialize some viewModels later:

<div id="list_test" data-bind="template: {name: 'tpl', foreach:
models}"></div>

<script id="tpl" type="text/template">
<div data-bind="text: data"></div>
</script>


<script type="text/javascript">
var viewModel = function(text) {
this.data = ko.observable(text);
};

var viewModelArray = function() {
this.models = ko.observableArray([new viewModel("can i get"), new
viewModel("elements?")]);
};

var list = new viewModelArray();
ko.applyBindings(list, $('#list_test').get(0));
</script>

Or is the viewModel untraceable? If so, is there a built-in method of
finding element(s) bind to the observable?

rpn

unread,
Jul 5, 2011, 11:46:05 PM7/5/11
to knock...@googlegroups.com
Hi Zogg-
Currently the subscriptions that an observable has are held privately inside the function.  There is also not a built-in way from an element to tell what it is bound to.

Maybe if you describe your use case a little bit more, I could help brainstorm ideas to accomplish what you are after using Knockout's current functionality.

With that said, there are a couple of techniques that you could use to help link an element to an observable.

If you are using jQuery Templates, then you are able to access the data that was the overall context of that templates binding using the tmplItem function.  Here is a sample: http://jsfiddle.net/rniemeyer/e9JcH/

You could also use a custom binding to be more explicit about this type of relationship.  Something like: http://jsfiddle.net/rniemeyer/EtTuU/.  You could use a "data" binding like this on any element to associate some data with it.  If you are not using jQuery, then you could replace the $.data calls with ko.utils.domData.get(element, key) and ko.utils.domData.set(element, key, value)

If you need more information or help, please let me know.  I would be happy to give you a hand.



Reply all
Reply to author
Forward
0 new messages