Mixing Knockout with jQuery
我正在使用基因敲除(snockout.js)创建一个注释系统,但是在使用我们现有的jQuery函数进行模板制作时遇到了一些问题。
一个示例是创建注释的日期。我写了一个jQuery函数,使数据从
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <ul data-bind="foreach: Comments"> <li data-bind="attr: { id: Id }" class="Comment"> ... </li> </ul> <script type="text/javascript"> $(function(){ $(".prettyDate").prettify(); }); |
使用此代码,当我动态添加新注释时,日期保持为
如何将这些自定义的jQuery函数应用于由kickout.js生成的动态数据?
一种选择是使用自定义绑定处理程序,该处理程序通过jQuery插件发送绑定的元素,例如:
http://jsfiddle.net/mikebridge/Q9r86/4/
另一种可能是在视图模型中添加一个可计算的可观察值。
If you need to run some further custom logic on the generated DOM elements, you can use any of the afterRender/afterAdd/beforeRemove/beforeMove/afterMove callbacks described below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <ul data-bind="foreach: { data: myItems, afterAdd: yellowFadeIn }"> <li data-bind="text: $data"> </li> </ul> <button data-bind="click: addItem">Add</button> <script type="text/javascript"> ko.applyBindings({ myItems: ko.observableArray([ 'A', 'B', 'C' ]), yellowFadeIn: function(element, index, data) { $(element).filter("li") .animate({ backgroundColor: 'yellow' }, 200) .animate({ backgroundColor: 'white' }, 800); }, addItem: function() { this.myItems.push('New item'); } }); |
来源:http://knockoutjs.com/documentation/foreach-binding.html#note-7-post-processing-or-animating-the-generation-dom-elements
但是,请注意以下注意事项:
If your goal is actually to attach other behaviors to new DOM elements when they have been added (e.g., event handlers, or to activate third-party UI controls), then your work will be much easier if you implement that new behavior as a custom binding instead