淘汰双向绑定

时间:2014-08-05 06:30:40

标签: javascript knockout.js

我想在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。

提前致谢

2 个答案:

答案 0 :(得分:1)

你需要在observable中提供id

id: ko.observable('test')

这将产生id

Fiddle Demo

答案 1 :(得分:0)

从原始问题的评论中,我认为你没有想要双向绑定 - 你正在寻找一种缓存jQuery选择器的方法,以便可以在你的视图模型中访问它。 / p>

为此,我建议如下:

  • 在视图模型中添加将保存选择器结果的属性或变量。这些不需要是可观察的,因为元素的ID永远不会改变。
  • 创建一个在视图模型初始化时调用一次的函数,该函数将jQuery选择器的结果分配给它们各自的属性/变量。
  • 订阅包含数据的任何observable,并从那里触发动画。

以下是在视图模型(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 );