我想在Knockout.js中进行双向绑定,但我不太确定,我的方法是正确的建议。
我需要的是非常简单的: 我需要我的observable的binded元素的id。
这是我的第一个方法:
HTML:
<div id='test' data-bind="attr {id: 'test'}, html: id"></div>
使用Javascript:
var vm = {
id: ko.observable()
};
ko.applyBindings(vm);
最后,我需要在我的viewmodel中使用id iformation。
也许这是不可能的,也不是真正可靠的淘汰赛。但是如果我的viewmodel中没有信息,我不想通过jquery选择器浏览domtree。
提前致谢
答案 0 :(得分:1)
答案 1 :(得分:0)
从原始问题的评论中,我认为你没有想要双向绑定 - 你正在寻找一种缓存jQuery选择器的方法,以便可以在你的视图模型中访问它。 / p>
为此,我建议如下:
以下是在视图模型(JSFiddle example)中如何完成此操作的示例:
var ViewModel = ( function () {
var ViewModel = function () {
// ... stuff
this.data = ko.observable( 'No data here :(' );
this.data.subscribe( this.animate.bind( this ) );
};
// This is the function where you store the result of the jQuery selectors
ViewModel.prototype.cacheSelectors = function () {
this.testElement = $( '#test' );
};
// This is an example function that will load your data
ViewModel.prototype.loadData = function () {
this.data( 'Oh wait, here\'s some data!' );
};
// This is an example function that you could trigger to animate your element
ViewModel.prototype.animate = function () {
this.testElement.animate( { 'padding-left': '+=250px' }, 'slow' );
};
return new ViewModel();
}() );
ViewModel.cacheSelectors();
ko.applyBindings( ViewModel );